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

if ($_POST) {
    $id = $_POST['id'];
    $title = $_POST['title'];
    $exam_date = $_POST['exam_date'];
    $time_start = $_POST['time_start'];
    $time_end = $_POST['time_end'];
    $status = $_POST['status'];
    $class = $_POST['class'];
    $section = $_POST['section'];
    $subject = $_POST['subject'];
    $term = $_POST['term'];

    // Recalculate duration
    $start_time = strtotime($exam_date . ' ' . $time_start);
    $end_time = strtotime($exam_date . ' ' . $time_end);
    $duration = ($end_time - $start_time) / 60;

    if ($duration <= 0) {
        echo "
              Error: The end time must be later than the start time.";
        exit;
    }

    $sql = "UPDATE cbt_exams SET title=:title, exam_date=:exam_date,
     time_start=:time_start, time_end=:time_end, duration=:duration,
     class_id=:class, subject_id=:subject, term_id =:term, section_id =:section,
     status=:status WHERE id=:id";
    $conn->query($sql);
    $conn->bind(':id', $id);
    $conn->bind(':title', $title);
    $conn->bind(':exam_date', $exam_date);
    $conn->bind(':time_start', $time_start);
    $conn->bind(':time_end', $time_end);
    $conn->bind(':class', $class);
    $conn->bind(':subject', $subject);
    $conn->bind(':term', $term);
    $conn->bind(':section', $section);
    $conn->bind(':duration', $duration);
    $conn->bind(':status', $status);


    try {
        $conn->execute();
        echo "Exam Updated Successfully";
    } catch (PDOException $e) {
        $error = $e->getMessage();
        echo "'Error: " . $error . "'";
    }
}



