<?php
require_once 'config.php';

$chamber_id = intval($_POST['chamber_id']);
$date = $_POST['date'];
$day_of_week = date('w', strtotime($date));

// Get the schedule for the selected chamber on that day
$schedule = $conn->query("SELECT start_time, end_time, slot_duration 
                          FROM chamber_schedules 
                          WHERE chamber_id = $chamber_id AND day_of_week = $day_of_week AND status='active'");

if ($schedule->num_rows == 0) {
    echo '<option value="">No working hours on this day</option>';
    exit;
}

$row = $schedule->fetch_assoc();
$start = new DateTime($row['start_time']);
$end = new DateTime($row['end_time']);
$duration = (int)$row['slot_duration'];

// Get already booked slots from the time_slots table
$booked = [];
$booked_res = $conn->query("SELECT start_time FROM time_slots 
                            WHERE chamber_id = $chamber_id AND slot_date = '$date' AND is_booked = 1");
while ($b = $booked_res->fetch_assoc()) {
    $booked[] = $b['start_time'];
}

// Generate and output available slots
$current = clone $start;
$has_slots = false;
while ($current < $end) {
    $slot_start = $current->format('H:i:s');
    $slot_end = clone $current;
    $slot_end->modify("+$duration minutes");
    if ($slot_end <= $end && !in_array($slot_start, $booked)) {
        $display = date('h:i A', strtotime($slot_start)) . ' - ' . date('h:i A', strtotime($slot_end->format('H:i:s')));
        echo "<option value='" . htmlspecialchars($slot_start) . "'>$display</option>";
        $has_slots = true;
    }
    $current->modify("+$duration minutes");
}

if (!$has_slots) {
    echo '<option value="">No available slots for this day</option>';
}
?>