<?php
session_start();
ob_start();
error_reporting(E_ALL);
ini_set('display_errors', 1);

include "../include/config.php";

// Check login and instructor role
if (!isset($_SESSION['email'])) {
    header("location:../index.php");
    exit();
}

$success = "";
$error = "";

// Handle assignment insertion
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_assignment'])) {
    $program = $_POST['program'] ?? '';
    $period = $_POST['period'] ?? '';
    $intake = $_POST['intake'] ?? '';
    $course = $_POST['course'] ?? '';
    $email = $_SESSION['email'] ?? '';
    $year = $_POST['year'] ?? '';
    $posteddate = date('Y-m-d H:i:s');
    $duedate = $_POST['duedate'] ?? '';
    
    // Handle file upload
    $file = '';
    if (isset($_FILES['assignment_file']) && $_FILES['assignment_file']['error'] == 0) {
        $target_dir = "../../assignments/uploads/";
        if (!file_exists($target_dir)) {
            mkdir($target_dir, 0777, true);
        }
        
        $file_extension = pathinfo($_FILES['assignment_file']['name'], PATHINFO_EXTENSION);
        $unique_filename = uniqid() . '_' . time() . '.' . $file_extension;
        $target_file = $target_dir . $unique_filename;
        
        // Validate file type
        $allowed_types = ['pdf', 'doc', 'docx', 'txt', 'zip', 'rar', 'ppt', 'pptx'];
        if (in_array(strtolower($file_extension), $allowed_types)) {
            if (move_uploaded_file($_FILES['assignment_file']['tmp_name'], $target_file)) {
                $file = $unique_filename;
            } else {
                $error = "Sorry, there was an error uploading your file.";
            }
        } else {
            $error = "Sorry, only PDF, DOC, DOCX, TXT, ZIP, RAR, PPT, PPTX files are allowed.";
        }
    }
    
    if (empty($error)) {
        // Insert into assignments table (matching your table structure)
        $stmt = $conn->prepare("INSERT INTO assignments (program, period, intake, file, course, email, posteddate, duedate, year) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)");
        $stmt->bind_param("sssssssss", $program, $period, $intake, $file, $course, $email, $posteddate, $duedate, $year);
        
        if ($stmt->execute()) {
            $assignment_id = $stmt->insert_id;
            $success = "Assignment posted successfully!";
            
            // Pre-create result entries for all students
            preCreateResults($conn, $program, $period, $intake, $course, $year, $email);
            
            // Clear form fields
            $program = $period = $intake = $course = $year = $duedate = '';
        } else {
            $error = "Error: " . $conn->error;
        }
        $stmt->close();
    }
}

// Handle assignment deletion
if (isset($_GET['delete_assignment'])) {
    $assignment_id = intval($_GET['delete_assignment']);
    $instructor_email = $_SESSION['email'];
    
    // Check if assignment belongs to this instructor
    $check_sql = "SELECT id, file FROM assignments WHERE id = ? AND email = ?";
    $check_stmt = $conn->prepare($check_sql);
    $check_stmt->bind_param("is", $assignment_id, $instructor_email);
    $check_stmt->execute();
    $check_result = $check_stmt->get_result();
    
    if ($check_result->num_rows > 0) {
        $assignment = $check_result->fetch_assoc();
        
        // Delete associated file if exists
        if (!empty($assignment['file'])) {
            $file_path = "../../assignments/uploads/" . $assignment['file'];
            if (file_exists($file_path)) {
                unlink($file_path);
            }
        }
        
        // Delete assignment from database
        $delete_sql = "DELETE FROM assignments WHERE id = ?";
        $delete_stmt = $conn->prepare($delete_sql);
        $delete_stmt->bind_param("i", $assignment_id);
        
        if ($delete_stmt->execute()) {
            $_SESSION['success'] = "Assignment deleted successfully!";
        } else {
            $_SESSION['error'] = "Error deleting assignment: " . $conn->error;
        }
        $delete_stmt->close();
    } else {
        $_SESSION['error'] = "Assignment not found or you don't have permission to delete it!";
    }
    
    $check_stmt->close();
    header("Location: assignment.php#view");
    exit();
}
// Function to pre-create result entries
function preCreateResults($conn, $program, $period, $intake, $course, $year, $instructor_email) {
    // Trim all input values to remove whitespace
    $program = trim($program);
    $period = trim($period);
    $intake = trim($intake);
    $course = trim($course);
    $year = trim($year);
    $instructor_email = trim($instructor_email);
    
    // Get all students in this program/intake
    $program_esc = $conn->real_escape_string($program);
    $intake_esc = $conn->real_escape_string($intake);
    $student_query = $conn->query("SELECT studentid FROM students WHERE program='$program_esc' AND intake='$intake_esc'");
    
    while ($student = $student_query->fetch_assoc()) {
        $student_id = trim($student['studentid']);
        $student_id_esc = $conn->real_escape_string($student_id);
        $course_esc = $conn->real_escape_string($course);
        $intake_esc = $conn->real_escape_string($intake);
        $year_esc = $conn->real_escape_string($year);
        $period_esc = $conn->real_escape_string($period);
        
        // Debug: Log the values being checked
        error_log("preCreateResults checking: studentid='$student_id', course='$course', term='$period', year='$year', intake='$intake'");
        
        // Check if result already exists - use TRIM in comparison too
        $check_sql = "SELECT id FROM results 
                      WHERE TRIM(studentid) = '$student_id_esc' 
                      AND TRIM(course) = '$course_esc' 
                      AND TRIM(term) = '$period_esc' 
                      AND TRIM(year) = '$year_esc' 
                      AND TRIM(intake) = '$intake_esc'";
        
        $check_result = $conn->query($check_sql);
        
        if ($check_result->num_rows == 0) {
            // Also check with case-insensitive comparison
            $check_sql2 = "SELECT id FROM results 
                          WHERE LOWER(TRIM(studentid)) = LOWER('$student_id_esc') 
                          AND LOWER(TRIM(course)) = LOWER('$course_esc') 
                          AND LOWER(TRIM(term)) = LOWER('$period_esc') 
                          AND LOWER(TRIM(year)) = LOWER('$year_esc') 
                          AND LOWER(TRIM(intake)) = LOWER('$intake_esc')";
            
            $check_result2 = $conn->query($check_sql2);
            
            if ($check_result2->num_rows == 0) {
                // Create entry with ca=0 (matching your exam pattern)
                $sql = "INSERT INTO results (studentid, course, term, year, intake, ca, email) 
                        VALUES ('$student_id_esc', '$course_esc', '$period_esc', '$year_esc', '$intake_esc', 0, '$instructor_email')";
                
                if ($conn->query($sql)) {
                    error_log("preCreateResults INSERTED: $sql");
                } else {
                    error_log("preCreateResults ERROR: " . $conn->error);
                }
            } else {
                error_log("preCreateResults: Entry exists (case-insensitive check)");
            }
        } else {
            error_log("preCreateResults: Entry already exists");
        }
    }
    
    return true;
}
// Fetch all existing courses from assignments table for select option
$courses_result = $conn->query("SELECT DISTINCT course FROM course ORDER BY course");
// Fetch all existing programs from assignments table for select option
$programs_result = $conn->query("SELECT DISTINCT program FROM programs ORDER BY program");
$intakes = $conn->query("SELECT id, intake FROM intake");

// Fetch instructor's assignments for viewing
$instructor_email = $_SESSION['email'];
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Post Assignment to Students</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body { background-color: #f8f9fa; }
        .card { border-radius: 10px; box-shadow: 0 4px 6px rgba(0,0,0,0.1); }
        .nav-tabs .nav-link { border-radius: 8px 8px 0 0; }
        .nav-tabs .nav-link.active,{ background-color: var(--primary); color: white; }
        .assignment-card { transition: transform 0.2s; }
        .assignment-card:hover { transform: translateY(-5px); box-shadow: 0 6px 12px rgba(0,0,0,0.15); }
        .btn-locked { background-color: #6c757d; color: white; cursor: not-allowed; }
        .delete-confirm { color: #dc3545; }
        .card-header{ background-color: var(--primary) !important; color: white; }
    </style>
</head>
<body>
<?php include "../include/nav.php"; ?>
<div class="content">
<div class="container mt-4">
    <!-- Display success/error messages -->
    <?php if (isset($_SESSION['success'])): ?>
        <div class="alert alert-success alert-dismissible fade show" role="alert">
            <i class="fas fa-check-circle"></i> <?php echo $_SESSION['success']; unset($_SESSION['success']); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>
    
    <?php if (isset($_SESSION['error'])): ?>
        <div class="alert alert-danger alert-dismissible fade show" role="alert">
            <i class="fas fa-exclamation-triangle"></i> <?php echo $_SESSION['error']; unset($_SESSION['error']); ?>
            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
        </div>
    <?php endif; ?>
    
    <!-- Tabs for Posting and Viewing -->
    <ul class="nav nav-tabs" id="myTab" role="tablist">
        <li class="nav-item" role="presentation">
            <button class="nav-link active" id="post-tab" data-bs-toggle="tab" data-bs-target="#post" type="button">
                <i class="fas fa-plus-circle"></i> Post New Assignment
            </button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="view-tab" data-bs-toggle="tab" data-bs-target="#view" type="button">
                <i class="fas fa-list"></i> View Posted Assignments
            </button>
        </li>
        <li class="nav-item" role="presentation">
            <button class="nav-link" id="submissions-tab" data-bs-toggle="tab" data-bs-target="#submissions" type="button">
                <i class="fas fa-file-upload"></i> View Submissions
            </button>
        </li>
    </ul>
    
    <div class="tab-content mt-4" id="myTabContent">
        
        <!-- Tab 1: Post New Assignment -->
        <div class="tab-pane fade show active" id="post" role="tabpanel">
            <div class="row justify-content-center">
                <div class="col-md-10">
                    <div class="card">
                        <div class="card-header text-white">
                            <h4 class="mb-0"><i class="fas fa-paper-plane"></i> Send Assignment to Students</h4>
                        </div>
                        <div class="card-body">
                            <?php if ($success): ?>
                                <div class="alert alert-success alert-dismissible fade show" role="alert">
                                    <i class="fas fa-check-circle"></i> <?php echo $success; ?>
                                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                                </div>
                            <?php endif; ?>
                            
                            <?php if ($error): ?>
                                <div class="alert alert-danger alert-dismissible fade show" role="alert">
                                    <i class="fas fa-exclamation-triangle"></i> <?php echo $error; ?>
                                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                                </div>
                            <?php endif; ?>
                            
                            <form method="POST" enctype="multipart/form-data">
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="course" class="form-label">Course <span class="text-danger">*</span></label>
                                        <select class="form-select" id="course" name="course" required>
                                            <option value="">Select Course</option>
                                            <?php 
                                            if ($courses_result && $courses_result->num_rows > 0) {
                                                while($course_row = $courses_result->fetch_assoc()): ?>
                                                    <option value="<?php echo htmlspecialchars($course_row['course']); ?>"
                                                        <?php echo ($_POST['course'] ?? $_SESSION['course'] ?? '') == $course_row['course'] ? 'selected' : ''; ?>>
                                                        <?php echo htmlspecialchars($course_row['course']); ?>
                                                    </option>
                                                <?php endwhile; 
                                            } else {
                                                // If no courses exist yet, allow manual entry
                                                echo '<option value="">Type course name</option>';
                                            }
                                            ?>
                                        </select>
                                        <small class="form-text text-muted">Select existing course </small>
                                    </div>
                                    
                                    <div class="col-md-6 mb-3">
                                        <label for="program" class="form-label">Program <span class="text-danger">*</span></label>
                                        <select class="form-select" id="program" name="program" required>
                                            <option value="">Select Program</option>
                                            <?php 
                                            if ($programs_result && $programs_result->num_rows > 0) {
                                                // Reset pointer if needed
                                                $programs_result->data_seek(0);
                                                while($program_row = $programs_result->fetch_assoc()): ?>
                                                    <option value="<?php echo htmlspecialchars($program_row['program']); ?>"
                                                        <?php echo ($_POST['program'] ?? $_SESSION['program'] ?? '') == $program_row['program'] ? 'selected' : ''; ?>>
                                                        <?php echo htmlspecialchars($program_row['program']); ?>
                                                    </option>
                                                <?php endwhile; 
                                            } else {
                                                // If no programs exist yet, allow manual entry
                                                echo '<option value="">Type program name</option>';
                                            }
                                            ?>
                                        </select>
                                    </div>
                                </div>
                                
                                <!-- Add text input for new course if not in dropdown -->
                                <div class="row" id="newCourseRow" style="display: none;">
                                    <div class="col-md-12 mb-3">
                                        <label for="new_course" class="form-label">New Course Name <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="new_course" name="new_course" placeholder="Enter new course name">
                                    </div>
                                </div>
                                
                                <!-- Add text input for new program if not in dropdown -->
                                <div class="row" id="newProgramRow" style="display: none;">
                                    <div class="col-md-12 mb-3">
                                        <label for="new_program" class="form-label">New Program Name <span class="text-danger">*</span></label>
                                        <input type="text" class="form-control" id="new_program" name="new_program" placeholder="Enter new program name">
                                    </div>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-4 mb-3">
                                        <label for="intake" class="form-label">Intake <span class="text-danger">*</span></label>
                                        <select style="margin-top:-5px; color: #7c828c;" name="intake" id="intake" class="form-select" required>
                                            <option value="">Select Intake</option>
                                            <?php
                                            if ($intakes && $intakes->num_rows > 0) {
                                                $intakes->data_seek(0);
                                                while($row = $intakes->fetch_assoc()): ?>
                                                    <option value="<?php echo htmlspecialchars($row['intake']); ?>"
                                                        <?php echo ($_POST['intake'] ?? '') == $row['intake'] ? 'selected' : ''; ?>>
                                                        <?php echo htmlspecialchars($row['intake']); ?>
                                                    </option>
                                                <?php endwhile; 
                                            }
                                            ?>
                                        </select> 
                                    </div>
                                    
                                    <div class="col-md-4 mb-3">
                                        <label for="year" class="form-label">Year <span class="text-danger">*</span></label>
                                        <select class="form-select" id="year" name="year" required>
                                            <option value="">Select Year</option>
                                            <?php for ($y = date('Y'); $y >= 2020; $y--): ?>
                                                <option value="<?php echo $y; ?>" 
                                                    <?php echo ($_POST['year'] ?? $_SESSION['year'] ?? '') == $y ? 'selected' : ''; ?>>
                                                    <?php echo $y; ?>
                                                </option>
                                            <?php endfor; ?>
                                        </select>
                                    </div>
                                    
                                    <div class="col-md-4 mb-3">
                                        <label for="period" class="form-label">Semester <span class="text-danger">*</span></label>
                                        <select class="form-select" id="period" name="period" required>
                                            <option value="">Select Semester</option>
                                            <option value="1" <?php echo ($_POST['period'] ?? $_SESSION['period'] ?? '') == '1' ? 'selected' : ''; ?>>Semester 1</option>
                                            <option value="2" <?php echo ($_POST['period'] ?? $_SESSION['period'] ?? '') == '2' ? 'selected' : ''; ?>>Semester 2</option>
                                            <option value="3" <?php echo ($_POST['period'] ?? $_SESSION['period'] ?? '') == '3' ? 'selected' : ''; ?>>Trimester</option>
                                        </select>
                                    </div>
                                </div>
                                
                                <div class="row">
                                    <div class="col-md-6 mb-3">
                                        <label for="duedate" class="form-label">Due Date & Time <span class="text-danger">*</span></label>
                                        <input type="datetime-local" class="form-control" id="duedate" name="duedate" required>
                                    </div>
                                </div>
                                
                                <div class="mb-3">
                                    <label for="assignment_file" class="form-label">Assignment File (Optional)</label>
                                    <input type="file" class="form-control" id="assignment_file" name="assignment_file">
                                    <small class="form-text text-muted">Upload supporting materials (Max: 10MB)</small>
                                </div>
                                
                                <div class="d-grid gap-2 d-md-flex justify-content-md-end">
                                    <button type="reset" class="btn btn-secondary me-md-2">
                                        <i class="fas fa-redo"></i> Clear Form
                                    </button>
                                    <button type="submit" name="add_assignment" class="btn " style="background-color: var(--primary) !important; color: white; ">
                                        <i class="fas fa-paper-plane"></i> Send to Students
                                    </button>
                                </div>
                            </form>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Tab 2: View Posted Assignments -->
        <div class="tab-pane fade" id="view" role="tabpanel">
            <div class="card">
                <div class="card-header bg-info text-white">
                    <h5 class="mb-0"><i class="fas fa-history"></i> Assignments You've Posted</h5>
                </div>
                <div class="card-body">
                    <div class="table-responsive">
                        <table class="table table-hover table-striped">
                            <thead class="table-dark">
                                <tr>
                                    <th>#</th>
                                    <th>Course</th>
                                    <th>Program</th>
                                    <th>Intake</th>
                                    <th>Year</th>
                                    <th>Semester</th>
                                    <th>Posted Date</th>
                                    <th>Due Date</th>
                                    <th>File</th>
                                    <th>Submissions</th>
                                    <th>Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                $assignments_sql = "SELECT a.*, 
                                        (SELECT COUNT(*) FROM submit WHERE assignment_id = a.id) as submission_count
                                    FROM assignments a 
                                    WHERE a.email = '$instructor_email' 
                                    ORDER BY a.posteddate DESC";
                                $assignments_result = $conn->query($assignments_sql);
                                
                                if ($assignments_result->num_rows > 0) {
                                    $count = 1;
                                    while($assignment = $assignments_result->fetch_assoc()) {
                                        $due_date = strtotime($assignment['duedate']);
                                        $posted_date = strtotime($assignment['posteddate']);
                                        $now = time();
                                        $status = $due_date < $now ? 'Overdue' : 'Active';
                                        $status_class = $due_date < $now ? 'danger' : 'success';
                                        $submission_count = $assignment['submission_count'];
                                        
                                        echo "<tr>";
                                        echo "<td>{$count}</td>";
                                        echo "<td>" . htmlspecialchars($assignment['course']) . "</td>";
                                        echo "<td>" . htmlspecialchars($assignment['program']) . "</td>";
                                        echo "<td>" . htmlspecialchars($assignment['intake']) . "</td>";
                                        echo "<td>" . htmlspecialchars($assignment['year']) . "</td>";
                                        echo "<td>" . htmlspecialchars($assignment['period']) . "</td>";
                                        echo "<td>" . date('d M Y, H:i', $posted_date) . "</td>";
                                        echo "<td>
                                            <span class='badge bg-{$status_class}'>" . date('d M Y, H:i', $due_date) . "</span>
                                        </td>";
                                        echo "<td>";
                                        if (!empty($assignment['file'])) {
                                            echo "<a href='../../assignments/uploads/{$assignment['file']}' target='_blank' class='btn btn-sm btn-outline-primary'>
                                                <i class='fas fa-download'></i> Download
                                            </a>";
                                        } else {
                                            echo "No file";
                                        }
                                        echo "</td>";
                                        echo "<td>
                                            <span class='badge bg-primary'>$submission_count submissions</span>
                                        </td>";
                                        echo "<td>
                                            <div class='btn-group' role='group'>";
                                                
                                        // Only show delete button if no submissions
                                        if ($submission_count == 0) {
                                            echo "<button class='btn btn-sm btn-danger' onclick='confirmDelete({$assignment['id']}, \"" . htmlspecialchars($assignment['course']) . "\")' title='Delete Assignment'>
                                                    <i class='fas fa-trash'></i>
                                                </button>";
                                        } else {
                                            echo "<button class='btn btn-sm btn-secondary' disabled title='Cannot delete - has submissions'>
                                                    <i class='fas fa-trash'></i>
                                                </button>";
                                        }
                                        
                                        echo "</div>
                                        </td>";
                                        echo "</tr>";
                                        $count++;
                                    }
                                } else {
                                    echo "<tr><td colspan='11' class='text-center text-muted'>No assignments posted yet</td></tr>";
                                }
                                ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- Tab 3: View Submissions -->
        <div class="tab-pane fade" id="submissions" role="tabpanel">
            <div class="card">
                <div class="card-header bg-success text-white">
                    <h5 class="mb-0"><i class="fas fa-file-upload"></i> Student Submissions</h5>
                </div>
                <div class="card-body">
                    <div class="row mb-3">
                        <div class="col-md-6">
                            <select class="form-select" id="filterAssignment">
                                <option value="">Filter by Course</option>
                                <?php
                                $filter_sql = "SELECT DISTINCT course FROM assignments WHERE email='$instructor_email' ORDER BY course";
                                $filter_result = $conn->query($filter_sql);
                                if ($filter_result && $filter_result->num_rows > 0) {
                                    while($filter = $filter_result->fetch_assoc()) {
                                        echo "<option value='" . htmlspecialchars($filter['course']) . "'>" . htmlspecialchars($filter['course']) . "</option>";
                                    }
                                }
                                ?>
                            </select>
                        </div>
                        <div class="col-md-6">
                            <input type="text" class="form-control" id="searchSubmissions" placeholder="Search by student ID or name...">
                        </div>
                    </div>
                    
                    <div class="table-responsive">
                        <table class="table table-hover" id="submissionsTable">
                            <thead>
                                <tr>
                                    <th>Student</th>
                                    <th>Course</th>
                                    <th>Submitted On</th>
                                    <th>Status</th>
                                    <th>Marks</th>
                                    <th>File</th>
                                    <th>Action</th>
                                </tr>
                            </thead>
                            <tbody>
                                <?php
                                $submissions_sql = "SELECT s.*, a.course as course_name,
                                        st.studentname as student_name, st.email as student_email
                                    FROM submit s
                                    JOIN assignments a ON s.assignment_id = a.id
                                    JOIN students st ON s.student_id = st.studentid
                                    WHERE a.email = '$instructor_email'
                                    ORDER BY s.submitted_at DESC
                                    LIMIT 20";
                                $submissions_result = $conn->query($submissions_sql);
                                
                                if ($submissions_result && $submissions_result->num_rows > 0) {
                                    while($sub = $submissions_result->fetch_assoc()) {
                                        $is_graded = !empty($sub['marks']) && $sub['marks'] !== '' && $sub['marks'] > 0;
                                        $marks = $is_graded ? $sub['marks'] : 'Not Graded';
                                        $badge_class = $is_graded ? 'success' : 'warning';
                                        
                                        echo "<tr data-course='" . htmlspecialchars($sub['course_name']) . "'>";
                                        echo "<td>
                                            <strong>" . htmlspecialchars($sub['student_name']) . "</strong><br>
                                            <small class='text-muted'>" . htmlspecialchars($sub['student_email']) . "</small>
                                        </td>";
                                        echo "<td>" . htmlspecialchars($sub['course_name']) . "</td>";
                                        echo "<td>" . date('d M Y, H:i', strtotime($sub['submitted_at'])) . "</td>";
                                        echo "<td>" . ($is_graded ? '<span class="badge bg-success">Graded</span>' : '<span class="badge bg-warning">Pending</span>') . "</td>";
                                        echo "<td><span class='badge bg-$badge_class'>$marks</span></td>";
                                        echo "<td>";
                                        if (!empty($sub['file'])) {
                                            echo "<a href='../../students/login/{$sub['file']}' target='_blank' class='btn btn-sm btn-outline-primary'>
                                                <i class='fas fa-download'></i> Download
                                            </a>";
                                        } else {
                                            echo "No file";
                                        }
                                        echo "</td>";
                                        echo "<td>";
                                        if ($is_graded) {
                                            // If already graded, show disabled/locked button
                                            echo "<button class='btn btn-sm btn-secondary' disabled>
                                                <i class='fas fa-lock'></i> Graded
                                            </button>";
                                        } else {
                                            // If not graded, show active grade button
                                            echo "<button class='btn btn-sm btn-primary' onclick='gradeSubmission({$sub['id']}, \"" . htmlspecialchars($sub['student_name']) . "\")'>
                                                <i class='fas fa-edit'></i> Grade
                                            </button>";
                                        }
                                        echo "</td>";
                                        echo "</tr>";
                                    }
                                } else {
                                    echo "<tr><td colspan='7' class='text-center text-muted'>No submissions yet</td></tr>";
                                }
                                ?>
                            </tbody>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>
</div>

<!-- Grade Modal -->
<div class="modal fade" id="gradeModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <form method="post" action="grade_assignment.php">
                <div class="modal-header">
                    <h5 class="modal-title">Grade Assignment</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                </div>
                <div class="modal-body">
                    <div id="studentInfo"></div>
                    <div class="mb-3">
                        <label class="form-label">Marks (0-100)</label>
                        <input type="number" name="marks" id="gradeInput" class="form-control" required min="0" max="100" step="0.5" placeholder="Enter marks">
                    </div>
                    <input type="hidden" name="submission_id" id="submissionId">
                    <input type="hidden" name="save_grade" value="1">
                </div>
                <div class="modal-footer">
                    <button type="submit" class="btn btn-primary">Save Grade & Update Results</button>
                    <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                </div>
            </form>
        </div>
    </div>
</div>

<!-- Delete Confirmation Modal -->
<div class="modal fade" id="deleteModal" tabindex="-1">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header bg-danger text-white">
                <h5 class="modal-title"><i class="fas fa-exclamation-triangle"></i> Confirm Delete</h5>
                <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <p id="deleteMessage"></p>
                <p class="text-danger"><strong>Warning:</strong> This action cannot be undone!</p>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Cancel</button>
                <a href="#" id="confirmDeleteBtn" class="btn btn-danger">Delete Assignment</a>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.0/dist/js/bootstrap.bundle.min.js"></script>
<script>
// Set default due date
document.addEventListener('DOMContentLoaded', function() {
    const now = new Date();
    now.setHours(now.getHours() + 24);
    const defaultDateTime = now.toISOString().slice(0, 16);
    document.getElementById('duedate').min = new Date().toISOString().slice(0, 16);
    document.getElementById('duedate').value = defaultDateTime;
    
    // Tab persistence
    const hash = window.location.hash;
    if (hash) {
        const tab = new bootstrap.Tab(document.querySelector(hash));
        tab.show();
    }
    
    // Show new course input if user selects "Type course name"
    document.getElementById('course').addEventListener('change', function() {
        const newCourseRow = document.getElementById('newCourseRow');
        if (this.value === '') {
            newCourseRow.style.display = 'block';
        } else {
            newCourseRow.style.display = 'none';
        }
    });
    
    // Show new program input if user selects "Type program name"
    document.getElementById('program').addEventListener('change', function() {
        const newProgramRow = document.getElementById('newProgramRow');
        if (this.value === '') {
            newProgramRow.style.display = 'block';
        } else {
            newProgramRow.style.display = 'none';
        }
    });
    
    // Filter submissions by course
    document.getElementById('filterAssignment').addEventListener('change', function() {
        const course = this.value;
        const rows = document.querySelectorAll('#submissionsTable tbody tr');
        
        rows.forEach(row => {
            if (!course || row.dataset.course === course) {
                row.style.display = '';
            } else {
                row.style.display = 'none';
            }
        });
    });
    
    // Search submissions
    document.getElementById('searchSubmissions').addEventListener('input', function() {
        const searchTerm = this.value.toLowerCase();
        const rows = document.querySelectorAll('#submissionsTable tbody tr');
        
        rows.forEach(row => {
            const text = row.textContent.toLowerCase();
            row.style.display = text.includes(searchTerm) ? '' : 'none';
        });
    });
});

function gradeSubmission(submissionId, studentName) {
    console.log("Grading submission:", submissionId, "for student:", studentName);
    
    // Set the submission ID
    document.getElementById('submissionId').value = submissionId;
    
    // Display student info
    document.getElementById('studentInfo').innerHTML = `
        <div class="alert alert-info p-3">
            <strong><i class="fas fa-user"></i> Student:</strong> ${studentName}<br>
            <strong><i class="fas fa-id-card"></i> Submission ID:</strong> ${submissionId}
        </div>
    `;
    
    // Clear previous marks
    document.getElementById('gradeInput').value = '';
    
    // Show modal
    const gradeModal = new bootstrap.Modal(document.getElementById('gradeModal'));
    gradeModal.show();
    
    // Focus on input
    setTimeout(() => {
        document.getElementById('gradeInput').focus();
    }, 500);
}

function confirmDelete(assignmentId, courseName) {
    // Set the delete message
    document.getElementById('deleteMessage').innerHTML = 
        `Are you sure you want to delete the assignment: <strong>${courseName}</strong>?`;
    
    // Set the delete link
    document.getElementById('confirmDeleteBtn').href = 
        `assignment.php?delete_assignment=${assignmentId}`;
    
    // Show the delete confirmation modal
    const deleteModal = new bootstrap.Modal(document.getElementById('deleteModal'));
    deleteModal.show();
}
</script>
</body>
</html>
<?php
$conn->close();
ob_end_flush();
?>