<?php
session_start();
include '../admin/includes/database.php';
include '../admin/includes/functions.php';
$conn= new Functions();


function generateExamCode(){
    return bin2hex(random_bytes(4));
}

$exam_code = generateExamCode();

if (!empty($_POST['title'])) {
    $title = $_POST['title'];
    $subject_id = $_POST['subject_id'];
    $class_id = $_POST['class_id'];
    $section_id = $_POST['section_id'];
    $term_id = $_POST['term_id'];
    $academic_session = $_POST['academic_session'];
    $exam_date = $_POST['exam_date'];
    $time_start = $_POST['time_start'];
    $time_end = $_POST['time_end'];
    $instruction = $_POST['instruction'];
    $minimum_percentage = $_POST['minimum_percentage'];
    $status = $_POST['status'];

    

    // Calculate duration (in minutes)
    $start_time = strtotime($exam_date . ' ' . $time_start);
    $end_time = strtotime($exam_date . ' ' . $time_end);
    $duration = ($end_time - $start_time) / 60; // Convert seconds to minutes

    if ($duration <= 0) {
        echo "<script>

              toastr['error']('Error: The end time must be later than the start time.');

        </script>";
        exit;
    }

    $sql = "INSERT INTO cbt_exams (exam_code, title, subject_id, class_id, section_id, term_id, 
                       academic_session, exam_date, time_start, time_end, duration, instruction, 
                       minimum_percentage, status) 
            VALUES (:exam_code, :title, :subject_id, :class_id, :section_id, :term_id, :academic_session,
                    :exam_date, :time_start, :time_end, :duration, :instruction, 
                    :minimum_percentage, :status)";

    $conn->query($sql);
    $conn->bind(':exam_code', $exam_code);
    $conn->bind(':title', $title);
    $conn->bind(':subject_id', $subject_id);
    $conn->bind(':class_id', $class_id);
    $conn->bind(':section_id', $section_id);
    $conn->bind(':term_id', $term_id);
    $conn->bind(':academic_session', $academic_session);
    $conn->bind(':exam_date', $exam_date);
    $conn->bind(':time_start', $time_start);
    $conn->bind(':time_end', $time_end);
    $conn->bind(':duration', $duration);
    $conn->bind(':instruction', $instruction);
    $conn->bind(':minimum_percentage', $minimum_percentage);
    $conn->bind(':status', $status);

    try {
        $conn->execute();
        echo "<script>

              toastr['success']('Exam Created Successfully');

        </script>";
    } catch (PDOException $e) {
        $error = $e->getMessage();
        echo "<script>
              toastr['error']('Error: " . $error . "');
        </script>";
    }


}



