<?php
include 'db_connection.php';
include '../includes/functions.php';

/* =========================
   CONFIGURATION
========================= */
$days = ['Monday','Tuesday','Wednesday','Thursday','Friday'];

$periods = [
    1 => ['08:30','09:15'],
    2 => ['09:15','10:00'],
    3 => ['10:00','10:45'],
    4 => ['10:45','11:30'],
    5 => ['11:30','12:00'],
    6 => ['12:00','12:45'],
    7 => ['12:45','13:30'],
    8 => ['13:30','14:15'],
    9 => ['14:15','15:00']
];

/* =========================
   CLEAR OLD TIMETABLE
========================= */
$conn->query("DELETE FROM timetable");

/* =========================
   CHECK BREAK
========================= */
function isBreak($conn, $day, $period){
    $stmt = $conn->prepare("SELECT id FROM break_periods WHERE day=? AND period=?");
    $stmt->bind_param("si", $day, $period);
    $stmt->execute();
    return $stmt->get_result()->num_rows > 0;
}

/* =========================
   CHECK SLOT
========================= */
function isSlotFree($conn, $class_id, $teacher_id, $day, $period){
    $stmt = $conn->prepare("
        SELECT timetable_id 
        FROM timetable
        WHERE (class_id=? OR teacher_id=?)
        AND day=? AND period=?
    ");
    $stmt->bind_param("iisi", $class_id, $teacher_id, $day, $period);
    $stmt->execute();
    return $stmt->get_result()->num_rows === 0;
}

/* =========================
   CHECK TEACHER AVAILABILITY (NEW)
========================= */
function isTeacherAvailable($conn, $teacher_id, $day, $start, $end){

    $stmt = $conn->prepare("
        SELECT * FROM teacher_availability
        WHERE teacher_id = ?
        AND day = ?
        AND start_time <= ?
        AND end_time >= ?
    ");

    $stmt->bind_param("isss", $teacher_id, $day, $start, $end);
    $stmt->execute();

    return $stmt->get_result()->num_rows > 0;
}

/* =========================
   FETCH CLASSES
========================= */
$classes = $conn->query("SELECT class_id FROM classes");

foreach ($classes as $class){

    $class_id = $class['class_id'];

    /* =========================
       SUBJECTS WITH FREQUENCY
    ========================= */
    $subjects = $conn->query("
        SELECT subject_id, frequency
        FROM class_subject
        WHERE class_id = $class_id
    ");

    foreach ($subjects as $sub){

        $subject_id = $sub['subject_id'];
        $frequency  = (int)$sub['frequency'];

        $teacher = getTeacherForSubject($conn, $subject_id);
        if (!$teacher) continue;

        $teacher_id = $teacher['teacher_id'];

        $availableDays = $days;
        shuffle($availableDays);

        $usedDays = [];

        for ($i = 0; $i < $frequency; $i++){

            $assigned = false;

            if (empty($availableDays)){
                $availableDays = $days;
                shuffle($availableDays);
            }

            foreach ($availableDays as $day){

                if (in_array($day, $usedDays)) continue;

                foreach ($periods as $period => $time){

                    $start = $time[0];
                    $end   = $time[1];

                    if (isBreak($conn, $day, $period)) continue;

                    if (!isTeacherAvailable($conn, $teacher_id, $day, $start, $end)) continue;

                    if (isSlotFree($conn, $class_id, $teacher_id, $day, $period)){

                        $stmt = $conn->prepare("
                            INSERT INTO timetable
                            (class_id, subject_id, teacher_id, day, period, start_time, end_time, location)
                            VALUES (?, ?, ?, ?, ?, ?, ?, ?)
                        ");

                        $location = "Classroom";

                        $stmt->bind_param(
                            "iiisisss",
                            $class_id,
                            $subject_id,
                            $teacher_id,
                            $day,
                            $period,
                            $start,
                            $end,
                            $location
                        );

                        $stmt->execute();

                        $usedDays[] = $day;
                        $assigned = true;
                        break 2;
                    }
                }
            }

            if (!$assigned){
                echo "<p style='color:red;text-align:center'>
                    ⚠ Could not assign Subject {$subject_id} (Session ".($i+1).")
                </p>";
            }
        }
    }
}

echo "<h3 style='text-align:center;color:green'>
✅ Smart Timetable Generated Successfully
</h3>";
?>