<?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";

try {
    // Fetch all available exams
    $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
    $stmt_subjects = $DBH->query("SELECT id, subject FROM tbl_subject ORDER BY subject");
    $subjects = $stmt_subjects->fetchAll(PDO::FETCH_ASSOC);
    
    // Fetch existing exam-subject assignments to display
    $stmt_assignments = $DBH->query("
        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
        ORDER BY e.exam_name, s.subject
    ");
    $assignments = $stmt_assignments->fetchAll(PDO::FETCH_ASSOC);
    
} catch (PDOException $e) {
    $_SESSION['error'] = "Database error: " . $e->getMessage();
    $exams = [];
    $subjects = [];
    $assignments = [];
}

// Initialize form values
$selected_exam_ids = $_POST['exam_id'] ?? [];
$selected_subject_ids = $_POST['subject_id'] ?? [];
$selected_assessment_type = $_POST['assessment_type'] ?? 'Term Exam';
$exam_date = $_POST['exam_date'] ?? '';
$duration_minutes = $_POST['duration_minutes'] ?? '';
$instructions = $_POST['instructions'] ?? '';

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    $exam_ids = $_POST['exam_id'] ?? [];
    $subject_ids = $_POST['subject_id'] ?? [];
    $assessment_type = $_POST['assessment_type'] ?? '';
    $exam_date = $_POST['exam_date'] ?? '';
    $duration_minutes = $_POST['duration_minutes'] ?? '';
    $instructions = trim($_POST['instructions'] ?? '');

    // Validate required fields
    $errors = [];
    
    if (empty($exam_ids)) {
        $errors[] = "Please select at least one exam.";
    }
    
    if (empty($subject_ids)) {
        $errors[] = "Please select at least one 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 {
            $DBH->beginTransaction();
            $successCount = 0;
            $errorMessages = [];

            foreach ($exam_ids as $exam_id) {
                foreach ($subject_ids as $subject_id) {
                    // Check if record already exists with same exam, subject, and assessment type
                    $stmt = $DBH->prepare("SELECT id FROM tbl_exam_subject 
                                           WHERE exam_id = :exam_id 
                                           AND subject_id = :subject_id
                                           AND assessment_type = :assessment_type");
                    $stmt->execute([
                        'exam_id' => $exam_id,
                        'subject_id' => $subject_id,
                        'assessment_type' => $assessment_type
                    ]);
                    $existing = $stmt->fetch(PDO::FETCH_ASSOC);

                    if ($existing) {
                        // Get exam and subject names for better error message
                        $examName = getExamName($DBH, $exam_id);
                        $subjectName = getSubjectName($DBH, $subject_id);
                        $errorMessages[] = "'$subjectName' is already assigned to '$examName' for $assessment_type.";
                        continue;
                    }

                    // Insert new record
                    $stmt = $DBH->prepare("INSERT INTO tbl_exam_subject 
                                          (exam_id, subject_id, assessment_type, exam_date, duration_minutes, instructions) 
                                          VALUES 
                                          (:exam_id, :subject_id, :assessment_type, :exam_date, :duration_minutes, :instructions)");
                    $stmt->execute([
                        'exam_id' => $exam_id,
                        'subject_id' => $subject_id,
                        'assessment_type' => $assessment_type,
                        'exam_date' => $exam_date,
                        'duration_minutes' => $duration_minutes,
                        'instructions' => $instructions
                    ]);

                    $successCount++;
                }
            }

            $DBH->commit();

            if ($successCount > 0) {
                $_SESSION['success'] = "Successfully added $successCount exam-subject assignment(s) for $assessment_type!";
            }

            if (!empty($errorMessages)) {
                $_SESSION['error'] = implode("<br>", $errorMessages);
            }

            header("Location: add_subject_to_exam.php");
            exit();
            
        } catch (PDOException $e) {
            $DBH->rollBack();
            $_SESSION['error'] = "Database error: " . $e->getMessage();
            header("Location: add_subject_to_exam.php");
            exit();
        }
    } else {
        $_SESSION['error'] = implode("<br>", $errors);
        // Store form values for repopulation
        $_SESSION['form_values'] = [
            'exam_ids' => $exam_ids,
            'subject_ids' => $subject_ids,
            'assessment_type' => $assessment_type,
            'exam_date' => $exam_date,
            'duration_minutes' => $duration_minutes,
            'instructions' => $instructions
        ];
        header("Location: add_subject_to_exam.php");
        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 and form values from session
$error_message = $_SESSION['error'] ?? '';
$success_message = $_SESSION['success'] ?? '';
$form_values = $_SESSION['form_values'] ?? null;

// Clear messages from session
unset($_SESSION['error'], $_SESSION['success'], $_SESSION['form_values']);

// Use form values if available
if ($form_values) {
    $selected_exam_ids = $form_values['exam_ids'];
    $selected_subject_ids = $form_values['subject_ids'];
    $selected_assessment_type = $form_values['assessment_type'];
    $exam_date = $form_values['exam_date'];
    $duration_minutes = $form_values['duration_minutes'];
    $instructions = $form_values['instructions'];
}
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Add Subject to Exam - 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;
            margin-bottom: 2rem;
        }
        
        .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-sm {
            padding: 0.25rem 0.5rem;
            font-size: 0.85rem;
            border-radius: 5px;
        }
        
        .btn-info {
            background: linear-gradient(135deg, #17a2b8, #138496);
            border: none;
            color: white;
        }
        
        .btn-warning {
            background: linear-gradient(135deg, #ffc107, #e0a800);
            border: none;
            color: var(--dark-blue);
        }
        
        .btn-danger {
            background: linear-gradient(135deg, #dc3545, #c82333);
            border: none;
            color: white;
        }
        
        /* 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;
        }
        
        /* Table Styles */
        .table-responsive {
            border-radius: 10px;
            overflow: hidden;
        }
        
        .table {
            margin-bottom: 0;
        }
        
        .table thead {
            background: linear-gradient(135deg, var(--primary-blue), var(--dark-blue));
            color: white;
        }
        
        .table thead th {
            font-weight: 600;
            border: none;
            padding: 1rem;
        }
        
        .table tbody td {
            padding: 1rem;
            vertical-align: middle;
        }
        
        .table tbody tr:hover {
            background-color: var(--light-gold);
        }
        
        /* Select2 Customization */
        .select2-container--bootstrap-5 .select2-selection {
            border: 1px solid #ced4da;
            border-radius: 10px;
            min-height: 50px;
        }
        
        .select2-container--bootstrap-5 .select2-selection--multiple .select2-selection__rendered {
            padding: 0.5rem 0.75rem;
        }
        
        .select2-container--bootstrap-5 .select2-selection--multiple .select2-selection__choice {
            background: linear-gradient(135deg, var(--light-gold), #ffffff);
            border: 1px solid var(--secondary-gold);
            color: var(--dark-blue);
            font-weight: 500;
            padding: 0.25rem 1rem 0.25rem 0.5rem;
            margin: 0.25rem;
        }
        
        .select2-container--bootstrap-5 .select2-selection--multiple .select2-selection__choice__remove {
            color: #dc3545;
            margin-right: 0.5rem;
        }
        
        .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;
        }
        
        /* 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);
        }
        
        /* 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;
        }
        
        .info-box i {
            color: var(--primary-blue);
            margin-right: 0.5rem;
        }
        
        /* 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;
            }
            
            .table thead th {
                font-size: 0.9rem;
                padding: 0.75rem;
            }
            
            .table tbody td {
                padding: 0.75rem;
                font-size: 0.9rem;
            }
        }
    </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 - Add Subject to Exam</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="../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">
            <div class="col-12">
                <!-- 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 active" aria-current="page">Add Subject to Exam</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; ?>

                <!-- Add Subject Form Card -->
                <div class="card action-card mb-4">
                    <div class="card-header">
                        <h3 class="mb-0"><i class="fas fa-plus-circle me-2"></i> Add Subject to Exam</h3>
                    </div>
                    <div class="card-body">
                        <form method="POST" id="addSubjectForm">
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="exam_id" class="form-label"><i class="fas fa-book-open me-1"></i> Select Exam(s)</label>
                                    <select name="exam_id[]" id="exam_id" class="form-select select2-multiple" multiple required>
                                        <?php foreach ($exams as $exam): ?>
                                            <option value="<?= $exam['id'] ?>" <?= in_array($exam['id'], $selected_exam_ids) ? 'selected' : '' ?>>
                                                <?= htmlspecialchars($exam['exam_name']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <small class="text-muted">You can select multiple exams</small>
                                </div>
                                
                                <div class="col-md-6 mb-3">
                                    <label for="subject_id" class="form-label"><i class="fas fa-book me-1"></i> Select Subject(s)</label>
                                    <select name="subject_id[]" id="subject_id" class="form-select select2-multiple" multiple required>
                                        <?php foreach ($subjects as $subject): ?>
                                            <option value="<?= $subject['id'] ?>" <?= in_array($subject['id'], $selected_subject_ids) ? 'selected' : '' ?>>
                                                <?= htmlspecialchars($subject['subject']) ?>
                                            </option>
                                        <?php endforeach; ?>
                                    </select>
                                    <small class="text-muted">You can select multiple subjects</small>
                                </div>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-4 mb-3">
                                    <label for="assessment_type" class="form-label"><i class="fas fa-clipboard-check me-1"></i> Assessment Type</label>
                                    <select name="assessment_type" id="assessment_type" class="form-select" required>
                                        <option value="">-- Select Assessment Type --</option>
                                        <option value="CA1" <?= $selected_assessment_type == 'CA1' ? 'selected' : '' ?>>CA1 (Test 1)</option>
                                        <option value="CA2" <?= $selected_assessment_type == 'CA2' ? 'selected' : '' ?>>CA2 (Test 2)</option>
                                        <option value="CA3" <?= $selected_assessment_type == 'CA3' ? 'selected' : '' ?>>CA3 (Project)</option>
                                        <option value="Term Exam" <?= $selected_assessment_type == 'Term Exam' ? 'selected' : '' ?>>Term Exam</option>
                                        <option value="Mock Exam" <?= $selected_assessment_type == 'Mock Exam' ? 'selected' : '' ?>>Mock Exam</option>
                                    </select>
                                </div>
                                
                                <div class="col-md-4 mb-3">
                                    <label for="exam_date" class="form-label"><i class="fas fa-calendar-alt me-1"></i> Exam Date</label>
                                    <input type="date" name="exam_date" id="exam_date" class="form-control" value="<?= htmlspecialchars($exam_date) ?>" required>
                                </div>
                                
                                <div class="col-md-4 mb-3">
                                    <label for="duration_minutes" class="form-label"><i class="fas fa-clock me-1"></i> Duration (Minutes)</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" 
                                          placeholder="Enter any specific instructions for this subject..."><?= htmlspecialchars($instructions) ?></textarea>
                            </div>
                            
                            <!-- Assessment Type Guide -->
                            <div class="info-box mb-4">
                                <h6 class="mb-2"><i class="fas fa-info-circle"></i> Assessment Types Guide</h6>
                                <div class="row">
                                    <div class="col-md-2 mb-2">
                                        <span class="badge badge-ca1">CA1</span> = Test 1
                                    </div>
                                    <div class="col-md-2 mb-2">
                                        <span class="badge badge-ca2">CA2</span> = Test 2
                                    </div>
                                    <div class="col-md-2 mb-2">
                                        <span class="badge badge-ca3">CA3</span> = Project
                                    </div>
                                    <div class="col-md-3 mb-2">
                                        <span class="badge badge-term">Term Exam</span> = End of Term Exam
                                    </div>
                                    <div class="col-md-3 mb-2">
                                        <span class="badge badge-mock">Mock Exam</span> = Mock Examination
                                    </div>
                                </div>
                                <p class="small mt-2 mb-0">Each assessment type can be assigned separately to the same exam and subject combination.</p>
                            </div>
                            
                            <div class="d-grid gap-2">
                                <button type="submit" class="btn btn-primary">
                                    <i class="fas fa-save me-2"></i> Add Subjects to Exams
                                </button>
                                <a href="cbt_admin_home.php" class="btn btn-outline-secondary">
                                    <i class="fas fa-arrow-left me-2"></i> Back to Dashboard
                                </a>
                            </div>
                        </form>
                    </div>
                </div>
                
                <!-- Existing Assignments Card -->
                <?php if (!empty($assignments)): ?>
                <div class="card action-card">
                    <div class="card-header">
                        <h3 class="mb-0"><i class="fas fa-list me-2"></i> Existing Exam-Subject Assignments</h3>
                    </div>
                    <div class="card-body">
                        <div class="table-responsive">
                            <table class="table table-hover">
                                <thead>
                                    <tr>
                                        <th>Exam Name</th>
                                        <th>Subject</th>
                                        <th>Assessment Type</th>
                                        <th>Exam Date</th>
                                        <th>Duration</th>
                                        <th>Actions</th>
                                    </tr>
                                </thead>
                                <tbody>
                                    <?php foreach ($assignments as $assignment): 
                                        $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';
                                        }
                                    ?>
                                        <tr>
                                            <td><strong><?= htmlspecialchars($assignment['exam_name']) ?></strong></td>
                                            <td><?= htmlspecialchars($assignment['subject']) ?></td>
                                            <td>
                                                <span class="badge <?= $badgeClass ?>">
                                                    <?= htmlspecialchars($assignment['assessment_type']) ?>
                                                </span>
                                            </td>
                                            <td><?= date('M j, Y', strtotime($assignment['exam_date'])) ?></td>
                                            <td><?= htmlspecialchars($assignment['duration_minutes']) ?> mins</td>
                                            <td>
                                                <div class="btn-group" role="group">
                                                    <a href="edit_exam_subject.php?id=<?= $assignment['id'] ?>" class="btn btn-sm btn-warning" title="Edit">
                                                        <i class="fas fa-edit"></i>
                                                    </a>
                                                    <a href="delete_exam_subject.php?id=<?= $assignment['id'] ?>" class="btn btn-sm btn-danger" 
                                                       onclick="return confirm('Are you sure you want to delete this assignment?')" title="Delete">
                                                        <i class="fas fa-trash-alt"></i>
                                                    </a>
                                                </div>
                                            </td>
                                        </tr>
                                    <?php endforeach; ?>
                                </tbody>
                            </table>
                        </div>
                        
                        <div class="mt-3 text-muted small">
                            <i class="fas fa-info-circle me-1"></i> Total: <?= count($assignments) ?> assignment(s) found
                        </div>
                    </div>
                </div>
                <?php endif; ?>
            </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
            $('.select2-multiple').select2({
                theme: 'bootstrap-5',
                placeholder: "Select options",
                allowClear: true,
                width: '100%'
            });
            
            // Set minimum date to today
            const today = new Date().toISOString().split('T')[0];
            document.getElementById('exam_date').min = today;
            
            // Form validation
            $('#addSubjectForm').on('submit', function(e) {
                const examIds = $('#exam_id').val();
                const subjectIds = $('#subject_id').val();
                const assessmentType = $('#assessment_type').val();
                const examDate = $('#exam_date').val();
                const duration = $('#duration_minutes').val();
                
                if (!examIds || examIds.length === 0) {
                    alert('Please select at least one exam');
                    e.preventDefault();
                    return false;
                }
                
                if (!subjectIds || subjectIds.length === 0) {
                    alert('Please select at least one subject');
                    e.preventDefault();
                    return false;
                }
                
                if (!assessmentType) {
                    alert('Please select an assessment type');
                    e.preventDefault();
                    return false;
                }
                
                if (!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 add ${subjectIds.length} subject(s) to ${examIds.length} exam(s) for ${assessmentType}?`);
            });
        });
    </script>
</body>
</html>