<?php
require 'db.php';

// Get all instructor availability entries
$sql = "SELECT id, instructor_id, available_date, start_time, end_time FROM InstructorAvailability";
$result = $conn->query($sql);

// Define slot duration (in minutes)
$slotDuration = 40;

while ($row = $result->fetch_assoc()) {
    $instructor_id = $row['instructor_id'];
    $date = $row['available_date'];
    $start = new DateTime($date . ' ' . $row['start_time']);
    $end = new DateTime($date . ' ' . $row['end_time']);

    // Loop through the available window in slot-sized increments
    while ($start < $end) {
        $slotStart = clone $start;
        $slotEnd = clone $start;
        $slotEnd->modify("+$slotDuration minutes");

        if ($slotEnd > $end) {
            break; // don’t go past availability
        }

        $slotDatetime = $slotStart->format('Y-m-d H:i:s');

        // Avoid duplicates: check if this slot already exists
        $check = $conn->prepare("SELECT id FROM DriveSlots WHERE instructor_id = ? AND slot_datetime = ?");
        $check->bind_param("is", $instructor_id, $slotDatetime);
        $check->execute();
        $check->store_result();

        if ($check->num_rows === 0) {
            $insert = $conn->prepare("INSERT INTO DriveSlots (instructor_id, slot_datetime) VALUES (?, ?)");
            $insert->bind_param("is", $instructor_id, $slotDatetime);
            $insert->execute();
            $insert->close();
        }

        $check->close();
        $start->modify("+$slotDuration minutes");
    }
}

$conn->close();

echo "Drive slots generated successfully.";
?>
