<?php
require_once('../source/session.php');
require_once('../source/error.php');
require_once('../source/dbconfig.php');
require_once('../source/function.php');
require_once('../source/restrict_admin.php');

// Get admin name from session
$adminName = $_SESSION['SESS_FULLNAME_ADMIN'] ?? 'Administrator';

// School information
$schoolName = "Henzy Royal International School";
$schoolAddress = "No 17 Amadi Street, Amakohia, Uratta Owerri Imo State Nigeria";
$supportPhone = "+234 803 292 9756";
$supportEmail = "support@hris.com.ng";

// Get assignment ID from URL
$assignment_id = isset($_GET['id']) ? intval($_GET['id']) : 0;

if ($assignment_id === 0) {
    $_SESSION['error'] = "Invalid assignment ID.";
    header("Location: add_subject_to_exam.php");
    exit();
}

try {
    // Fetch the assignment details
    $stmt = $DBH->prepare("
        SELECT es.*, e.exam_name, s.subject 
        FROM tbl_exam_subject es
        JOIN tbl_exam e ON es.exam_id = e.id
        JOIN tbl_subject s ON es.subject_id = s.id
        WHERE es.id = ?
    ");
    $stmt->execute([$assignment_id]);
    $assignment = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$assignment) {
        $_SESSION['error'] = "Assignment not found.";
        header("Location: add_subject_to_exam.php");
        exit();
    }

    // Fetch all available exams for dropdown
    $stmt_exams = $DBH->query("SELECT id, exam_name FROM tbl_exam ORDER BY exam_name");
    $exams = $stmt_exams->fetchAll(PDO::FETCH_ASSOC);

    // Fetch all available subjects for dropdown
    $stmt_subjects = $DBH->query("SELECT id, subject FROM tbl_subject ORDER BY subject");
    $subjects = $stmt_subjects->fetchAll(PDO::FETCH_ASSOC);

} catch (PDOException $e) {
    $_SESSION['error'] = "Database error: " . $e->getMessage();
    header("Location: add_subject_to_exam.php");
    exit();
}

// Initialize form variables with current values
$exam_id = $assignment['exam_id'];
$subject_id = $assignment['subject_id'];
$assessment_type = $assignment['assessment_type'];
$exam_date = $assignment['exam_date'];
$duration_minutes = $assignment['duration_minutes'];
$instructions = $assignment['instructions'];

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Get form data - make sure we're getting the values correctly
    $exam_id = isset($_POST['exam_id']) ? intval($_POST['exam_id']) : 0;
    $subject_id = isset($_POST['subject_id']) ? intval($_POST['subject_id']) : 0;
    $assessment_type = $_POST['assessment_type'] ?? '';
    $exam_date = $_POST['exam_date'] ?? '';
    $duration_minutes = $_POST['duration_minutes'] ?? '';
    $instructions = trim($_POST['instructions'] ?? '');

    // Debug - you can remove this after fixing
    error_log("POST data: " . print_r($_POST, true));

    // Validate required fields
    $errors = [];
    
    if (empty($exam_id) || $exam_id === 0) {
        $errors[] = "Please select an exam.";
    }
    
    if (empty($subject_id) || $subject_id === 0) {
        $errors[] = "Please select a subject.";
    }
    
    if (empty($assessment_type)) {
        $errors[] = "Please select an assessment type.";
    }
    
    if (empty($exam_date)) {
        $errors[] = "Please select an exam date.";
    }
    
    if (empty($duration_minutes) || $duration_minutes < 1) {
        $errors[] = "Please enter a valid duration (minimum 1 minute).";
    }

    if (empty($errors)) {
        try {
            // Check if another record already exists with same combination (excluding current record)
            $stmt = $DBH->prepare("SELECT id FROM tbl_exam_subject 
                                   WHERE exam_id = :exam_id 
                                   AND subject_id = :subject_id 
                                   AND assessment_type = :assessment_type 
                                   AND id != :id");
            $stmt->execute([
                'exam_id' => $exam_id,
                'subject_id' => $subject_id,
                'assessment_type' => $assessment_type,
                'id' => $assignment_id
            ]);
            
            if ($stmt->fetch(PDO::FETCH_ASSOC)) {
                // Get names for better error message
                $examName = getExamName($DBH, $exam_id);
                $subjectName = getSubjectName($DBH, $subject_id);
                $_SESSION['error'] = "Another record already exists for '$examName' - '$subjectName' with assessment type '$assessment_type'.";
                header("Location: edit_exam_subject.php?id=" . $assignment_id);
                exit();
            } else {
                // Update the record
                $stmt = $DBH->prepare("UPDATE tbl_exam_subject 
                                      SET exam_id = :exam_id,
                                          subject_id = :subject_id,
                                          assessment_type = :assessment_type,
                                          exam_date = :exam_date,
                                          duration_minutes = :duration_minutes,
                                          instructions = :instructions
                                      WHERE id = :id");
                
                $result = $stmt->execute([
                    'exam_id' => $exam_id,
                    'subject_id' => $subject_id,
                    'assessment_type' => $assessment_type,
                    'exam_date' => $exam_date,
                    'duration_minutes' => $duration_minutes,
                    'instructions' => $instructions,
                    'id' => $assignment_id
                ]);

                if ($result) {
                    $_SESSION['success'] = "Exam-subject assignment updated successfully!";
                    header("Location: add_subject_to_exam.php");
                    exit();
                } else {
                    $_SESSION['error'] = "Failed to update the assignment. Please try again.";
                    header("Location: edit_exam_subject.php?id=" . $assignment_id);
                    exit();
                }
            }
            
        } catch (PDOException $e) {
            $_SESSION['error'] = "Database error: " . $e->getMessage();
            header("Location: edit_exam_subject.php?id=" . $assignment_id);
            exit();
        }
    } else {
        $_SESSION['error'] = implode("<br>", $errors);
        header("Location: edit_exam_subject.php?id=" . $assignment_id);
        exit();
    }
}

// Helper functions
function getExamName($DBH, $exam_id) {
    $stmt = $DBH->prepare("SELECT exam_name FROM tbl_exam WHERE id = ?");
    $stmt->execute([$exam_id]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    return $result ? $result['exam_name'] : "Exam ID: $exam_id";
}

function getSubjectName($DBH, $subject_id) {
    $stmt = $DBH->prepare("SELECT subject FROM tbl_subject WHERE id = ?");
    $stmt->execute([$subject_id]);
    $result = $stmt->fetch(PDO::FETCH_ASSOC);
    return $result ? $result['subject'] : "Subject ID: $subject_id";
}

// Get error/success messages from session
$error_message = $_SESSION['error'] ?? '';
$success_message = $_SESSION['success'] ?? '';
unset($_SESSION['error'], $_SESSION['success']);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Edit Exam Subject - Henzy Royal International School CBT</title>
    <link rel="icon" type="image/png" href="../coll_logo.png">
    
    <!-- Bootstrap 5 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    
    <!-- Font Awesome -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    
    <!-- Google Fonts - Poppins -->
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;600;700&display=swap" rel="stylesheet">
    
    <!-- Select2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    <link href="https://cdn.jsdelivr.net/npm/select2-bootstrap-5-theme@1.3.0/dist/select2-bootstrap-5-theme.min.css" rel="stylesheet" />
    
    <!-- Custom CSS -->
    <style>
        :root {
            --primary-blue: #1a4b8c;    /* Royal Blue */
            --secondary-gold: #FFD700;    /* Gold */
            --dark-blue: #0f2b4f;         /* Dark Blue */
            --light-blue: #4a7db5;         /* Medium Blue */
            --light-gold: #FFF1B8;          /* Light Gold */
            --bg-light: #f5f9ff;
        }
        
        body {
            font-family: 'Poppins', sans-serif;
            background-color: var(--bg-light);
            color: #333;
            padding-bottom: 60px;
        }
        
        /* Header Styles */
        .admin-header {
            background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue));
            box-shadow: 0 2px 15px rgba(26, 75, 140, 0.3);
            border-bottom: 3px solid var(--secondary-gold);
            color: white;
            margin-bottom: 2rem;
        }
        
        .logo-container {
            background: white;
            border-radius: 10px;
            padding: 5px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.2);
        }
        
        .img-fluid {
            width: 60px;
            height: 60px;
            object-fit: cover;
            border-radius: 8px;
        }
        
        .header-title h1 {
            font-weight: 700;
            margin-bottom: 0;
            font-size: 1.5rem;
            color: white;
        }
        
        .header-title small {
            color: var(--secondary-gold);
            font-weight: 500;
        }
        
        /* Dropdown Styles */
        .admin-dropdown {
            background: rgba(255, 255, 255, 0.1);
            border: 1px solid rgba(255, 215, 0, 0.3);
            color: white;
            padding: 0.5rem 1rem;
            border-radius: 50px;
            transition: all 0.3s ease;
        }
        
        .admin-dropdown:hover {
            background: rgba(255, 215, 0, 0.2);
            border-color: var(--secondary-gold);
        }
        
        .dropdown-menu {
            border: 1px solid var(--secondary-gold);
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
        
        .dropdown-item:hover {
            background-color: var(--light-gold);
            color: var(--dark-blue);
        }
        
        .dropdown-item i {
            color: var(--primary-blue);
        }
        
        /* Card Styles */
        .action-card {
            border: none;
            border-radius: 15px;
            box-shadow: 0 4px 20px rgba(26, 75, 140, 0.1);
            transition: all 0.3s ease;
            background: white;
            border: 1px solid rgba(255, 215, 0, 0.2);
            overflow: hidden;
        }
        
        .action-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 8px 25px rgba(26, 75, 140, 0.2);
            border-color: var(--secondary-gold);
        }
        
        .card-header {
            background: linear-gradient(135deg, var(--light-gold), #ffffff);
            border-bottom: 2px solid var(--secondary-gold);
            padding: 1.5rem;
        }
        
        .card-header h3 {
            color: var(--dark-blue);
            font-weight: 700;
            margin: 0;
        }
        
        .card-header i {
            color: var(--secondary-gold);
        }
        
        .card-body {
            padding: 2rem;
        }
        
        /* Form Styles */
        .form-label {
            font-weight: 600;
            color: var(--dark-blue);
            margin-bottom: 0.5rem;
        }
        
        .form-label i {
            color: var(--secondary-gold);
            margin-right: 0.5rem;
        }
        
        .form-control, .form-select {
            border: 1px solid #ced4da;
            border-radius: 10px;
            padding: 0.75rem 1rem;
            font-size: 0.95rem;
            transition: all 0.3s ease;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: var(--secondary-gold);
            box-shadow: 0 0 0 0.25rem rgba(255, 215, 0, 0.25);
            outline: none;
        }
        
        /* Buttons */
        .btn-primary {
            background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue));
            border: none;
            color: white;
            padding: 0.75rem 1.5rem;
            border-radius: 50px;
            font-weight: 500;
            transition: all 0.3s ease;
        }
        
        .btn-primary:hover {
            background: linear-gradient(135deg, var(--dark-blue), #0a1f3a);
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(26, 75, 140, 0.3);
        }
        
        .btn-outline-secondary {
            border: 2px solid #6c757d;
            color: #6c757d;
            background: transparent;
            padding: 0.75rem 1.5rem;
            border-radius: 50px;
            font-weight: 500;
            transition: all 0.3s ease;
        }
        
        .btn-outline-secondary:hover {
            background: #6c757d;
            color: white;
            transform: translateY(-2px);
        }
        
        .btn-danger {
            background: linear-gradient(135deg, #dc3545, #c82333);
            border: none;
            color: white;
            padding: 0.75rem 1.5rem;
            border-radius: 50px;
            font-weight: 500;
            transition: all 0.3s ease;
        }
        
        .btn-danger:hover {
            background: linear-gradient(135deg, #c82333, #bd2130);
            transform: translateY(-2px);
            box-shadow: 0 4px 15px rgba(220, 53, 69, 0.3);
        }
        
        /* Alert Styles */
        .alert {
            border-radius: 10px;
            border: none;
            padding: 1rem;
            margin-bottom: 1.5rem;
            border-left: 4px solid transparent;
        }
        
        .alert-success {
            background: linear-gradient(135deg, #d4edda, #c3e6cb);
            color: #155724;
            border-left-color: #28a745;
        }
        
        .alert-danger {
            background: linear-gradient(135deg, #f8d7da, #f5c6cb);
            color: #721c24;
            border-left-color: #dc3545;
        }
        
        .alert i {
            margin-right: 0.5rem;
        }
        
        /* Assessment Type Badges */
        .badge-ca1 { background: linear-gradient(135deg, #17a2b8, #138496); color: white; }
        .badge-ca2 { background: linear-gradient(135deg, #28a745, #218838); color: white; }
        .badge-ca3 { background: linear-gradient(135deg, #ffc107, #e0a800); color: var(--dark-blue); }
        .badge-term { background: linear-gradient(135deg, #6610f2, #520dc2); color: white; }
        .badge-mock { background: linear-gradient(135deg, #fd7e14, #e56b08); color: white; }
        
        .badge {
            padding: 0.5rem 1rem;
            font-size: 0.85rem;
            font-weight: 500;
            border-radius: 50px;
        }
        
        /* Select2 Customization */
        .select2-container--bootstrap-5 .select2-selection {
            border: 1px solid #ced4da;
            border-radius: 10px;
            min-height: 50px;
        }
        
        .select2-container--bootstrap-5 .select2-dropdown {
            border-color: var(--secondary-gold);
        }
        
        .select2-container--bootstrap-5 .select2-results__option--selected {
            background-color: var(--light-gold);
            color: var(--dark-blue);
        }
        
        .select2-container--bootstrap-5 .select2-results__option--highlighted {
            background-color: var(--primary-blue);
            color: white;
        }
        
        /* Current Info Box */
        .info-box {
            background: linear-gradient(135deg, var(--light-gold), #ffffff);
            border-left: 4px solid var(--secondary-gold);
            padding: 1rem;
            border-radius: 10px;
            margin-top: 1rem;
        }
        
        .current-info {
            background: #f8f9fa;
            border-radius: 10px;
            padding: 1rem;
            margin-bottom: 2rem;
            border: 1px solid #dee2e6;
        }
        
        .current-info-item {
            padding: 0.5rem;
            border-bottom: 1px dashed #dee2e6;
        }
        
        .current-info-item:last-child {
            border-bottom: none;
        }
        
        .current-info-label {
            font-weight: 600;
            color: var(--primary-blue);
            min-width: 150px;
            display: inline-block;
        }
        
        /* Footer */
        .footer {
            background: linear-gradient(135deg, var(--dark-blue), var(--primary-blue));
            color: white;
            padding: 1.5rem 0;
            margin-top: 3rem;
            border-top: 3px solid var(--secondary-gold);
        }
        
        .footer a {
            color: var(--secondary-gold);
            text-decoration: none;
            font-weight: 500;
        }
        
        .footer a:hover {
            text-decoration: underline;
        }
        
        .footer img {
            height: 25px;
            margin-left: 5px;
            filter: brightness(0) invert(1);
        }
        
        /* Responsive */
        @media (max-width: 768px) {
            .header-title h1 {
                font-size: 1.2rem;
            }
            
            .admin-dropdown {
                padding: 0.4rem 0.8rem;
                font-size: 0.9rem;
            }
            
            .card-header h3 {
                font-size: 1.3rem;
            }
            
            .card-body {
                padding: 1.5rem;
            }
            
            .current-info-label {
                min-width: 120px;
            }
        }
    </style>
</head>
<body>
    <!-- Header -->
    <header class="admin-header py-3">
        <div class="container">
            <div class="d-flex justify-content-between align-items-center">
                <div class="d-flex align-items-center">
                    <div class="logo-container me-3">
                        <img src="../coll_logo.png" alt="Henzy Royal International School Logo" class="img-fluid">
                    </div>
                    <div class="header-title">
                        <h1 class="h4 mb-0">HENZY ROYAL INT'L SCHOOL</h1>
                        <small>CBT - Edit Exam Subject</small>
                    </div>
                </div>
                <div class="dropdown">
                    <button class="btn admin-dropdown dropdown-toggle" type="button" id="adminDropdown" data-bs-toggle="dropdown" aria-expanded="false">
                        <i class="fas fa-user-circle me-1"></i> <?= htmlspecialchars($adminName) ?>
                    </button>
                    <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="adminDropdown">
                        <li><a class="dropdown-item" href="cbt_admin_home.php"><i class="fas fa-tachometer-alt me-2"></i> CBT Dashboard</a></li>
                        <li><a class="dropdown-item" href="add_subject_to_exam.php"><i class="fas fa-plus-circle me-2"></i> Add New Assignment</a></li>
                        <li><a class="dropdown-item" href="../main.php"><i class="fas fa-home me-2"></i> Main Dashboard</a></li>
                        <li><hr class="dropdown-divider"></li>
                        <li><a class="dropdown-item" href="../logout.php"><i class="fas fa-sign-out-alt me-2"></i> Logout</a></li>
                    </ul>
                </div>
            </div>
        </div>
    </header>

    <!-- Main Content -->
    <div class="container py-4">
        <div class="row justify-content-center">
            <div class="col-md-8">
                <!-- Breadcrumb -->
                <nav aria-label="breadcrumb" class="mb-4">
                    <ol class="breadcrumb">
                        <li class="breadcrumb-item"><a href="cbt_admin_home.php" class="text-decoration-none" style="color: var(--primary-blue);">CBT Dashboard</a></li>
                        <li class="breadcrumb-item"><a href="add_subject_to_exam.php" class="text-decoration-none" style="color: var(--primary-blue);">Add Subject to Exam</a></li>
                        <li class="breadcrumb-item active" aria-current="page">Edit Assignment</li>
                    </ol>
                </nav>
                
                <?php if ($error_message): ?>
                    <div class="alert alert-danger alert-dismissible fade show">
                        <i class="fas fa-exclamation-circle me-2"></i> <?= $error_message ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>
                
                <?php if ($success_message): ?>
                    <div class="alert alert-success alert-dismissible fade show">
                        <i class="fas fa-check-circle me-2"></i> <?= $success_message ?>
                        <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                    </div>
                <?php endif; ?>

                <!-- Edit Form Card -->
                <div class="card action-card">
                    <div class="card-header">
                        <h3 class="mb-0"><i class="fas fa-edit me-2"></i> Edit Exam-Subject Assignment</h3>
                    </div>
                    <div class="card-body">
                        <!-- Current Information -->
                        <div class="current-info mb-4">
                            <h6 class="mb-3"><i class="fas fa-info-circle me-2" style="color: var(--secondary-gold);"></i> Current Assignment Details</h6>
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="current-info-item">
                                        <span class="current-info-label">Exam:</span>
                                        <strong><?= htmlspecialchars($assignment['exam_name']) ?></strong>
                                    </div>
                                    <div class="current-info-item">
                                        <span class="current-info-label">Subject:</span>
                                        <strong><?= htmlspecialchars($assignment['subject']) ?></strong>
                                    </div>
                                    <div class="current-info-item">
                                        <span class="current-info-label">Assessment Type:</span>
                                        <?php 
                                        $badgeClass = '';
                                        switch($assignment['assessment_type']) {
                                            case 'CA1': $badgeClass = 'badge-ca1'; break;
                                            case 'CA2': $badgeClass = 'badge-ca2'; break;
                                            case 'CA3': $badgeClass = 'badge-ca3'; break;
                                            case 'Term Exam': $badgeClass = 'badge-term'; break;
                                            case 'Mock Exam': $badgeClass = 'badge-mock'; break;
                                            default: $badgeClass = 'badge-secondary';
                                        }
                                        ?>
                                        <span class="badge <?= $badgeClass ?>"><?= htmlspecialchars($assignment['assessment_type']) ?></span>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="current-info-item">
                                        <span class="current-info-label">Exam Date:</span>
                                        <strong><?= date('F j, Y', strtotime($assignment['exam_date'])) ?></strong>
                                    </div>
                                    <div class="current-info-item">
                                        <span class="current-info-label">Duration:</span>
                                        <strong><?= htmlspecialchars($assignment['duration_minutes']) ?> minutes</strong>
                                    </div>
                                </div>
                            </div>
                        </div>

                        <form method="POST" id="editForm">
                            <div class="mb-3">
                                <label for="exam_id" class="form-label"><i class="fas fa-book-open me-1"></i> Select Exam <span class="text-danger">*</span></label>
                                <select name="exam_id" id="exam_id" class="form-select" required>
                                    <option value="">-- Select Exam --</option>
                                    <?php foreach ($exams as $exam): ?>
                                        <option value="<?= $exam['id'] ?>" <?= $exam['id'] == $exam_id ? 'selected' : '' ?>>
                                            <?= htmlspecialchars($exam['exam_name']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="mb-3">
                                <label for="subject_id" class="form-label"><i class="fas fa-book me-1"></i> Select Subject <span class="text-danger">*</span></label>
                                <select name="subject_id" id="subject_id" class="form-select" required>
                                    <option value="">-- Select Subject --</option>
                                    <?php foreach ($subjects as $subject): ?>
                                        <option value="<?= $subject['id'] ?>" <?= $subject['id'] == $subject_id ? 'selected' : '' ?>>
                                            <?= htmlspecialchars($subject['subject']) ?>
                                        </option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="mb-3">
                                <label for="assessment_type" class="form-label"><i class="fas fa-clipboard-check me-1"></i> Assessment Type <span class="text-danger">*</span></label>
                                <select name="assessment_type" id="assessment_type" class="form-select" required>
                                    <option value="">-- Select Assessment Type --</option>
                                    <option value="CA1" <?= $assessment_type == 'CA1' ? 'selected' : '' ?>>CA1 (Test 1)</option>
                                    <option value="CA2" <?= $assessment_type == 'CA2' ? 'selected' : '' ?>>CA2 (Test 2)</option>
                                    <option value="CA3" <?= $assessment_type == 'CA3' ? 'selected' : '' ?>>CA3 (Project)</option>
                                    <option value="Term Exam" <?= $assessment_type == 'Term Exam' ? 'selected' : '' ?>>Term Exam</option>
                                    <option value="Mock Exam" <?= $assessment_type == 'Mock Exam' ? 'selected' : '' ?>>Mock Exam</option>
                                </select>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="exam_date" class="form-label"><i class="fas fa-calendar-alt me-1"></i> Exam Date <span class="text-danger">*</span></label>
                                    <input type="date" name="exam_date" id="exam_date" class="form-control" 
                                           value="<?= htmlspecialchars($exam_date) ?>" required>
                                </div>
                                
                                <div class="col-md-6 mb-3">
                                    <label for="duration_minutes" class="form-label"><i class="fas fa-clock me-1"></i> Duration (Minutes) <span class="text-danger">*</span></label>
                                    <input type="number" name="duration_minutes" id="duration_minutes" class="form-control" 
                                           value="<?= htmlspecialchars($duration_minutes) ?>" min="1" max="480" required>
                                </div>
                            </div>
                            
                            <div class="mb-4">
                                <label for="instructions" class="form-label"><i class="fas fa-info-circle me-1"></i> Exam Subject Instructions</label>
                                <textarea name="instructions" id="instructions" class="form-control" rows="4"><?= htmlspecialchars($instructions) ?></textarea>
                            </div>
                            
                            <div class="d-grid gap-2">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-save me-2"></i> Update Assignment
                                </button>
                                <a href="add_subject_to_exam.php" class="btn btn-outline-secondary">
                                    <i class="fas fa-arrow-left me-2"></i> Back to Assignments
                                </a>
                            </div>
                        </form>
                    </div>
                </div>

                <!-- Delete Option -->
                <div class="card action-card mt-4">
                    <div class="card-header" style="border-bottom-color: #dc3545;">
                        <h3 class="mb-0 text-danger"><i class="fas fa-exclamation-triangle me-2"></i> Danger Zone</h3>
                    </div>
                    <div class="card-body">
                        <p class="mb-3">Once you delete this assignment, it cannot be recovered. This will also affect any questions already set for this assignment.</p>
                        <a href="delete_exam_subject.php?id=<?= $assignment_id ?>" 
                           class="btn btn-danger" 
                           onclick="return confirm('⚠️ WARNING: Are you sure you want to delete this assignment?\n\nExam: <?= addslashes($assignment['exam_name']) ?>\nSubject: <?= addslashes($assignment['subject']) ?>\nAssessment Type: <?= addslashes($assignment['assessment_type']) ?>\n\nThis action cannot be undone!')">
                            <i class="fas fa-trash-alt me-2"></i> Delete This Assignment
                        </a>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- Footer -->
    <footer class="footer">
        <div class="container">
            <div class="row align-items-center">
                <div class="col-md-8">
                    <p class="mb-1"><i class="fas fa-crown me-2" style="color: var(--secondary-gold);"></i><strong>Henzy Royal International School</strong> - Computer Based Test System</p>
                    <p class="mb-0 small"><i class="fas fa-map-marker-alt me-1" style="color: var(--secondary-gold);"></i> <?= $schoolAddress ?></p>
                </div>
                <div class="col-md-4 text-md-end">
                    <p class="mb-0">Powered By <a href="https://dataswift.com.ng" target="_blank">DataSwift Coders</a> 
                    <img src="../datalogo.png" alt="DataSwift Logo"></p>
                    <small>&copy; <?= date('Y') ?> All Rights Reserved</small>
                </div>
            </div>
        </div>
    </footer>

    <!-- JavaScript Libraries -->
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/js/select2.min.js"></script>
    
    <script>
        $(document).ready(function() {
            // Initialize Select2 for better dropdown experience
            $('#exam_id').select2({
                theme: 'bootstrap-5',
                width: '100%',
                placeholder: '-- Select Exam --',
                allowClear: true
            });
            
            $('#subject_id').select2({
                theme: 'bootstrap-5',
                width: '100%',
                placeholder: '-- Select Subject --',
                allowClear: true
            });
            
            // Set minimum date to today
            const today = new Date().toISOString().split('T')[0];
            document.getElementById('exam_date').setAttribute('min', today);
            
            // Form validation - this runs BEFORE submission
            $('#editForm').on('submit', function(e) {
                // Get the actual values from the selects
                const examId = $('#exam_id').val();
                const subjectId = $('#subject_id').val();
                const assessmentType = $('#assessment_type').val();
                const examDate = $('#exam_date').val();
                const duration = $('#duration_minutes').val();
                
                console.log('Exam ID:', examId);
                console.log('Subject ID:', subjectId);
                console.log('Assessment Type:', assessmentType);
                
                if (!examId || examId === '') {
                    alert('Please select an exam');
                    e.preventDefault();
                    return false;
                }
                
                if (!subjectId || subjectId === '') {
                    alert('Please select a subject');
                    e.preventDefault();
                    return false;
                }
                
                if (!assessmentType || assessmentType === '') {
                    alert('Please select an assessment type');
                    e.preventDefault();
                    return false;
                }
                
                if (!examDate || examDate === '') {
                    alert('Please select an exam date');
                    e.preventDefault();
                    return false;
                }
                
                if (!duration || duration < 1) {
                    alert('Please enter a valid duration (minimum 1 minute)');
                    e.preventDefault();
                    return false;
                }
                
                return confirm('Are you sure you want to update this assignment?');
            });
        });
    </script>
</body>
</html>