<?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');

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);
} catch (PDOException $e) {
    die("Database error: " . $e->getMessage());
}

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

    // Validate required fields
    if (empty($exam_ids) || empty($subject_ids) || empty($exam_date) || empty($duration_minutes)) {
        $_SESSION['error'] = "All fields are required.";
        header("Location: add_subject_to_exam.php");
        exit();
    }

    try {
        $DBH->beginTransaction();
        $successCount = 0;
        $errorMessages = [];

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

                if ($existing) {
                    $errorMessages[] = "Subject ID $subject_id is already assigned to Exam ID $exam_id.";
                    continue;
                }

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

                $successCount++;
            }
        }

        $DBH->commit();

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

        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();
    }
}
?>

<!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 - VERBUM DEI INT'L COLLEGE CBT Management</title>
    
    <!-- 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">
    
    <!-- Select2 CSS -->
    <link href="https://cdn.jsdelivr.net/npm/select2@4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
    
    <!-- Custom CSS -->
    <style>
        :root {
            --light-green: #e8f5e9;
            --primary-green: #2e7d32;
            --dark-green: #1b5e20;
            --accent-red: #A10A3F;
        }
        
        body {
            background-color: var(--light-green);
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
        }
        
        .admin-header {
            background-color: white;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        .action-card {
            border: none;
            border-radius: 10px;
            box-shadow: 0 2px 15px rgba(0,0,0,0.1);
            transition: all 0.3s ease;
        }
        
        .action-card:hover {
            transform: translateY(-5px);
            box-shadow: 0 5px 20px rgba(0,0,0,0.15);
        }
        
        .btn-primary {
            background-color: var(--primary-green);
            border-color: var(--primary-green);
        }
        
        .btn-primary:hover {
            background-color: var(--dark-green);
            border-color: var(--dark-green);
        }
        
        .form-control:focus, .select2-container--default .select2-selection--multiple:focus {
            border-color: var(--primary-green);
            box-shadow: 0 0 0 0.25rem rgba(46, 125, 50, 0.25);
        }
        
        .img-fluid {
            width: 100px;
            height: 100px;
        }
        
        /* Select2 customization */
        .select2-container--default .select2-selection--multiple {
            border: 1px solid #ced4da;
            min-height: calc(1.5em + 1rem + 2px);
            padding: 0.5rem 0.75rem;
        }
        
        .select2-container--default .select2-selection--multiple .select2-selection__choice {
            background-color: var(--primary-green);
            border-color: var(--dark-green);
            color: white;
        }
        
        .select2-container--default .select2-results__option--highlighted[aria-selected] {
            background-color: var(--primary-green);
            color: white;
        }
    </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="assets/images/coll_logo.jpg" alt="VDA Logo" class="img-fluid">
                    </div>
                    <div>
                        <h1 class="h4 mb-0">VERBUM DEI INT'L COLLEGE CBT Management</h1>
                        <small class="text-muted">Add Subject to Exam</small>
                    </div>
                </div>
                <div class="dropdown">
                    <button class="btn btn-outline-secondary dropdown-toggle" type="button" id="adminDropdown" data-bs-toggle="dropdown" aria-expanded="false">
                        <i class="fas fa-user-circle me-1"></i> <?= htmlspecialchars($_SESSION['SESS_FULLNAME_ADMIN']) ?>
                    </button>
                    <ul class="dropdown-menu" aria-labelledby="adminDropdown">
                        <li><a class="dropdown-item" href="cbt_admin_home.php"><i class="fas fa-tachometer-alt me-2"></i> Dashboard</a></li>
                        <li><hr class="dropdown-divider"></li>
                        <li><a class="dropdown-item" href="../admin/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">
                <div class="card action-card">
                    <div class="card-header bg-white">
                        <h3 class="mb-0"><i class="fas fa-book me-2"></i> Add Subject to Exam</h3>
                    </div>
                    <div class="card-body">
                        <?php if (isset($_SESSION['error'])): ?>
                            <div class="alert alert-danger alert-dismissible fade show">
                                <?= $_SESSION['error'] ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                            </div>
                            <?php unset($_SESSION['error']); ?>
                        <?php endif; ?>
                        
                        <?php if (isset($_SESSION['success'])): ?>
                            <div class="alert alert-success alert-dismissible fade show">
                                <?= $_SESSION['success'] ?>
                                <button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>
                            </div>
                            <?php unset($_SESSION['success']); ?>
                        <?php endif; ?>

                        <form method="POST">
                            <div class="mb-3">
                                <label for="exam_id" class="form-label">Select Exam(s)</label>
                                <select name="exam_id[]" id="exam_id" class="form-select select2-multiple" multiple="multiple" required>
                                    <?php foreach ($exams as $exam): ?>
                                        <option value="<?= $exam['id'] ?>"><?= $exam['exam_name'] ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="mb-3">
                                <label for="subject_id" class="form-label">Select Subject(s)</label>
                                <select name="subject_id[]" id="subject_id" class="form-select select2-multiple" multiple="multiple" required>
                                    <?php foreach ($subjects as $subject): ?>
                                        <option value="<?= $subject['id'] ?>"><?= $subject['subject'] ?></option>
                                    <?php endforeach; ?>
                                </select>
                            </div>
                            
                            <div class="row">
                                <div class="col-md-6 mb-3">
                                    <label for="exam_date" class="form-label">Exam Date</label>
                                    <input type="date" name="exam_date" id="exam_date" class="form-control" required>
                                </div>
                                <div class="col-md-6 mb-3">
                                    <label for="duration_minutes" class="form-label">Duration (Minutes)</label>
                                    <input type="number" name="duration_minutes" id="duration_minutes" class="form-control" min="1" required>
                                </div>
                            </div>
                            
                            <div class="mb-4">
                                <label for="instructions" class="form-label">Exam Subject Instructions</label>
                                <textarea name="instructions" id="instructions" class="form-control" rows="4"></textarea>
                            </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>
            </div>
        </div>
    </div>

    <!-- Footer -->
    <footer class="footer mt-5 py-3 bg-dark text-white">
        <div class="container">
            <div class="row">
                <div class="col-md-8">
                    <p class="mb-1">VERBUM DEI INT'L COLLEGE, OWERRI</p>
                    <p class="mb-0">Powered By <a href="https://dataswift.com.ng" target="_blank" class="text-white">DataSwift</a> 
                    <img src="assets/images/dataswift_logo.png" alt="DataSwift Logo" style="height: 20px; margin-left: 5px;"></p>
                </div>
                <div class="col-md-4 text-md-end">
                    <p class="mb-0">&copy; <?= date('Y') ?> All Rights Reserved</p>
                </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>
        // Initialize Select2
        $(document).ready(function() {
            $('.select2-multiple').select2({
                placeholder: "Select options",
                allowClear: true
            });
            
            // Set minimum date to today
            const today = new Date().toISOString().split('T')[0];
            document.getElementById('exam_date').min = today;
        });
    </script>
</body>
</html>