<?php
session_start();
ob_start();
$userlogin=$_SESSION['email'];
include "../include/config.php";

// Include PHPMailer


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

$programs = $conn->query("SELECT id, program FROM programs");
$intakes  = $conn->query("SELECT id, intake FROM intake");

// Fetch all questions
$questions_sql = "SELECT id, course, question FROM exam_questions ORDER BY course, question";
$questions_result = $conn->query($questions_sql);
$questions_array = [];
while($q = $questions_result->fetch_assoc()){
    $questions_array[] = $q;
}

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

// Handle form submission
if (isset($_POST['schedule_exam'])) {
    $program = $conn->real_escape_string($_POST['program']);
    $intake  = $conn->real_escape_string($_POST['intake']);
    $course  = $conn->real_escape_string($_POST['course']);
    $exam_date = $conn->real_escape_string($_POST['exam_date']);
    $start_time = $conn->real_escape_string($_POST['start_time']);
    $end_time = $conn->real_escape_string($_POST['end_time']);
    $period = $conn->real_escape_string($_POST['period']);
    $year = $conn->real_escape_string($_POST['year']);
    $questions = $_POST['questions'] ?? [];
    $email = $_SESSION['email'];

    if (empty($questions)) {
        $error = "Please select at least one question!";
    } else {

    $ca_check = $conn->query("SELECT * FROM results WHERE course='$course' AND term='$period' AND intake='$intake' AND (ca='' OR ca IS NULL OR ca1='' OR ca1 IS NULL OR ca2='' OR ca2 IS NULL) LIMIT 1");

        if ($ca_check && $ca_check->num_rows > 0) {

            $questions_json = json_encode($questions);
            $sql = "INSERT INTO exam_schedule (program,intake,course,period,year,exam_date,start_time,end_time,question_ids,created_at,email)
                    VALUES ('$program','$intake','$course','$period','$year','$exam_date','$start_time','$end_time','$questions_json', NOW(),'$email')";
            if ($conn->query($sql)) {
                $success = "Exam scheduled successfully!";

                

                // Fetch students in this program + intake
                $students = $conn->query("SELECT email, studentname 
                                          FROM students 
                                          WHERE program='$program' AND intake='$intake' AND status='active'");
                
                if ($students && $students->num_rows > 0) {
                    while ($row = $students->fetch_assoc()) {
                        $studentEmail = $row['email'];
                        $studentName  = $row['studentname'];

                        $mail = new PHPMailer(true);
                        try {
                                 $mail->isSMTP();
                $mail->Host       = 'unicohsuniversity.com';
                $mail->SMTPAuth   = true;
                $mail->Username   = 'contact@unicohsuniversity.com';
                $mail->Password   = '@mypass1996';
                $mail->SMTPSecure = 'tls';
                $mail->Port       = 587;

                $mail->setFrom('contact@unicohsuniversity.com', 'Unicohs University');
                $mail->addAddress($studentEmail, $studentName);

                            $mail->isHTML(true);
                            $mail->Subject = "New Exam Scheduled: $course";
                            $mail->Body    = "
                                Dear $studentName,<br><br>
                                A new exam has been scheduled for your course.<br>
                                <strong>Program:</strong> $program <br>
                                <strong>Intake:</strong> $intake <br>
                                <strong>Course:</strong> $course <br>
                                <strong>Year:</strong> $year <br>
                                <strong>Semester:</strong> $period <br>
                                <strong>Date:</strong> $exam_date <br>
                                <strong>Start Time:</strong> $start_time <br>
                                <strong>End Time:</strong> $end_time <br><br>
                                Please log in to the student portal for more details.<br><br>
                                Regards,<br>
                                $sname
                            ";

                            $mail->send();
                        } catch (Exception $e) {
                            error_log("Mail error to $studentEmail: " . $mail->ErrorInfo);
                        }
                    }
                }
            } else {
                $error = "Error scheduling exam: " . $conn->error;
            }
        } else {
            // All CA, CA1, CA2 are filled
            $error = "Cannot schedule exam: All CAs for this course are already filled.";
        }
    }
}
?>


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Schedule Exam - Admin Portal</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/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">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;500;600;700&family=Source+Sans+Pro:wght@300;400;600&display=swap" rel="stylesheet">
    <style>
        :root {
            --primary-color: var(--primary);
            --primary-hover: #1a6b4f;
            --secondary-color: #f8f9fa;
            --text-color: #333;
            --border-color: #dee2e6;
            --success-color: #28a745;
            --danger-color: #dc3545;
        }
        
        * {
            box-sizing: border-box;
            margin: 0;
            padding: 0;
        }
        
        body {
            font-family: 'Source Sans Pro', sans-serif;
            background: linear-gradient(135deg, #f5f7fa 0%, #e4efe9 100%);
            color: var(--text-color);
            min-height: 100vh;
        }
        
        .container-main {
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
        }
        
        .header {
            background: var(--primary-color);
            color: white;
            padding: 15px 20px;
            border-radius: 10px;
            margin-bottom: 25px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.1);
        }
        
        .header h1 {
            font-family: 'Montserrat', sans-serif;
            font-weight: 600;
            margin: 0;
            font-size: 28px;
        }
        
        .header p {
            opacity: 0.9;
            margin: 5px 0 0;
        }
        
        .card {
            border: none;
            border-radius: 12px;
            box-shadow: 0 5px 20px rgba(0,0,0,0.08);
            margin-bottom: 25px;
            overflow: hidden;
        }
        
        .card-header {
            background: var(--primary-color);
            color: white;
            padding: 15px 20px;
            font-family: 'Montserrat', sans-serif;
            font-weight: 600;
            font-size: 20px;
            border: none;
        }
        
        .card-body {
            padding: 25px;
        }
        
        .form-label {
            font-weight: 600;
            margin-bottom: 8px;
            color: #444;
        }
        
        .form-control, .form-select {
            border: 2px solid var(--border-color);
            border-radius: 8px;
            padding: 12px 15px;
            font-size: 16px;
            transition: all 0.3s;
        }
        
        .form-control:focus, .form-select:focus {
            border-color: var(--primary-color);
            box-shadow: 0 0 0 0.25rem rgba(35, 134, 101, 0.25);
        }
        
        .btn-primary {
            background: var(--primary-color);
            border: none;
            padding: 12px 25px;
            font-weight: 600;
            border-radius: 8px;
            transition: all 0.3s;
        }
        
        .btn-primary:hover {
            background: var(--primary-hover);
            transform: translateY(-2px);
            box-shadow: 0 4px 8px rgba(0,0,0,0.15);
        }
        
        .btn-outline-primary {
            color: var(--primary-color);
            border: 2px solid var(--primary-color);
            padding: 10px 20px;
            font-weight: 600;
            border-radius: 8px;
            transition: all 0.3s;
        }
        
        .btn-outline-primary:hover {
            background: var(--primary-color);
            color: white;
        }
        
        .questions-container {
            max-height: 300px;
            overflow-y: auto;
            border: 2px solid var(--border-color);
            border-radius: 8px;
            padding: 15px;
        }
        
        .question-item {
            padding: 12px 15px;
            margin-bottom: 10px;
            border-radius: 8px;
            background: white;
            border: 1px solid var(--border-color);
            transition: all 0.3s;
        }
        
        .question-item:hover {
            border-color: var(--primary-color);
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
        }
        
        .question-checkbox {
            margin-right: 10px;
            transform: scale(1.2);
        }
        
        .alert {
            border-radius: 10px;
            padding: 15px 20px;
            margin-bottom: 20px;
            border: none;
            font-weight: 500;
        }
        
        .alert-success {
            background: #d4edda;
            color: #155724;
        }
        
        .alert-danger {
            background: #f8d7da;
            color: #721c24;
        }
        
        .action-buttons {
            display: flex;
            gap: 15px;
            margin-bottom: 20px;
        }
        
        /* Responsive adjustments */
        @media (max-width: 768px) {
            .container-main {
                padding: 15px;
            }
            
            .header h1 {
                font-size: 24px;
            }
            
            .card-body {
                padding: 20px;
            }
            
            .action-buttons {
                flex-direction: column;
            }
            
            .btn-primary, .btn-outline-primary {
                width: 100%;
                margin-bottom: 10px;
            }
        }
        
        @media (max-width: 576px) {
            .header {
                padding: 12px 15px;
            }
            
            .header h1 {
                font-size: 20px;
            }
            
            .card-header {
                font-size: 18px;
                padding: 12px 15px;
            }
            
            .card-body {
                padding: 15px;
            }
            
            .form-control, .form-select {
                padding: 10px 12px;
                font-size: 14px;
            }
        }
        
        /* Custom checkbox styling */
        .form-check-input:checked {
            background-color: var(--primary-color);
            border-color: var(--primary-color);
        }
        
        /* Scrollbar styling */
        .questions-container::-webkit-scrollbar {
            width: 8px;
        }
        
        .questions-container::-webkit-scrollbar-track {
            background: #f1f1f1;
            border-radius: 10px;
        }
        
        .questions-container::-webkit-scrollbar-thumb {
            background: var(--primary-color);
            border-radius: 10px;
        }
        
        .questions-container::-webkit-scrollbar-thumb:hover {
            background: var(--primary-hover);
        }
    </style>
</head>
<body>
    <?php include "../include/nav.php"; ?>
    <div class="content" style="padding:10px">
    <div class="container-main" style="margin-top: px;">
        <div class="header">
            <h1><i class="fas fa-calendar-alt me-2"></i>Exam Scheduling</h1>
            <p>Schedule exams and notify students automatically</p>
        </div>
        
        <div class="action-buttons">
            <a class="btn btn-outline-success" href="scheduledexam.php">
                <i class="fas fa-list-alt me-2"></i>View Scheduled Exams
            </a>
             <a class="btn btn-outline-success" href="add_exam_question.php">
                <i class="fas fa-list-alt me-2"></i>Add Question
            </a>
        
        </div>
  <script>
$(document).ready(function() {
    function load() {
        var program = $("#programs").val();
        var semester = $("#terms").val();

        if (program && semester) {
            $.ajax({
                url: "fetch_courses_staff.php", // Updated to use staff-specific file
                type: "POST",
                data: { 
                    program: program, 
                    semester: semester,
                    staff_id: '<?php echo $userlogin; ?>' // Pass staff ID
                },
                success: function(data) {
                    $("#courses").html(data); // replace options inside course dropdown
                }
            });
        } else {
            $("#courses").html('<option value="">Select Program & Semester first</option>');
        }
    }

    // Run loadCourses() whenever program or semester changes
    $("#programs, #terms").change(load);
});
</script>

  
        <div class="card">
            <div class="card-header">
                <i class="fas fa-calendar-plus me-2"></i>Schedule New Exam
            </div>
            <div class="card-body">
                <?php if($success): ?>
                <div class="alert alert-success">
                    <i class="fas fa-check-circle me-2"></i> <?= $success ?>
                </div>
                <?php endif; ?>
                
                <?php if($error): ?>
                <div class="alert alert-danger">
                    <i class="fas fa-exclamation-triangle me-2"></i> <?= $error ?>
                </div>
                <?php endif; ?>
                
                <form method="post">
                    <div class="row g-4">
                       <div class="col-6 mb-3">
                            <label for="program" class="form-label">Program <span class="text-danger">*</span></label>
                            <select name="program" id="programs" class="form-select" required>
                                <option value="">Select Program</option>
                                <?php
                                $query = mysqli_query($conn, "SELECT * FROM programs ORDER BY id DESC");
                                while ($row = mysqli_fetch_array($query)) {
                                    echo "<option value='" . $row['program'] . "'>" . $row['program'] . "</option>";
                                }
                                ?>
                            </select>
                        </div>
                        
                                                <div class="col-md-6 mb-3">
                            <label for="term" class="form-label">Semester <span class="text-danger">*</span></label>
                            <select name="period" id="terms" class="form-select" required>
                                <option value="">Select Semester</option>
                                <option value="1">Semester 1</option>
                                <option value="2">Semester 2</option>
                            </select>
                        </div>
                        
                        
                        
                        <div class="col-md-6 mb-3">
                    <label for="course" class="form-label">Course <span class="text-danger">*</span></label>
                    <select name="course" id="courses" class="form-select" required>
                        <option value="">Select Program & Semester first</option>
                    </select>
                </div>
                        

                        <div class="col-md-6">
                            <label class="form-label">Intake</label>
                            <select name="intake" required class="form-select">
                                <option value="">-- Select Intake --</option>
                                <?php while($row = $intakes->fetch_assoc()) { ?>
                                    <option value="<?= $row['intake']; ?>"><?= $row['intake']; ?></option>
                                <?php } ?>
                            </select>
                        </div>

                        

                       
                        <div class="col-md-6">
                            <label class="form-label">Year</label>
                            <select name="year" class="form-select" required>
                                <option value="">-- Select Year --</option>
                                <?php
                                $currentYear = date('Y');
                                for($y = $currentYear; $y <= $currentYear + 5; $y++){
                                    echo "<option value=\"$y\">$y</option>";
                                }
                                ?>
                            </select>
                        </div>

                        <div class="col-md-6">
                            <label class="form-label">Exam Date</label>
                            <input type="date" name="exam_date" class="form-control" required>
                        </div>
                        
                        <div class="col-md-6">
                            <label class="form-label">Start Time</label>
                            <input type="time" name="start_time" class="form-control" required>
                        </div>
                        
                        <div class="col-md-6">
                            <label class="form-label">End Time</label>
                            <input type="time" name="end_time" class="form-control" required>
                        </div>

                        <div class="col-12">
                            <label class="form-label">Select Questions</label>
                            <div class="questions-container" id="questionsList">
                                <?php foreach($questions_array as $q): ?>
                                    <div class="question-item" data-course="<?= $q['course'] ?>">
                                        <div class="form-check">
                                            <input class="form-check-input questionItem" type="checkbox" name="questions[]" value="<?= $q['id'] ?>" id="q<?= $q['id'] ?>">
                                            <label class="form-check-label" for="q<?= $q['id'] ?>">
                                                <strong>[<?= $q['course'] ?>]</strong> <?= $q['question'] ?>
                                            </label>
                                        </div>
                                    </div>
                                <?php endforeach; ?>
                            </div>
                        </div>

                        <div class="col-12  mt-4">
                            <button type="submit" name="schedule_exam" class="btn btn-dark btn-lg">
                                <i class="fas fa-calendar-check me-2"></i> Schedule Exam
                            </button>
                        </div>
                    </div>
                </form>
            </div>
        </div>
    </div>

    <script>
        // Filter questions by course select
        const courseSelect = document.getElementById('courses');
        const questionItems = document.querySelectorAll('.question-item');

        courseSelect.addEventListener('change', function(){
            const selectedCourse = this.value;
            questionItems.forEach(function(item){
                if(selectedCourse === "" || item.getAttribute('data-course') === selectedCourse){
                    item.style.display = 'block';
                } else {
                    item.style.display = 'none';
                    item.querySelector('input').checked = false; // uncheck hidden
                }
            });
        });
        
        // Set minimum date to today
        const today = new Date().toISOString().split('T')[0];
        document.querySelector('input[type="date"]').setAttribute('min', today);
    </script>
</body>
</html>