<?php
require_once 'config.php';

$chamber_id = mysqli_real_escape_string($conn, $_POST['chamber_id']);
$appointment_date = mysqli_real_escape_string($conn, $_POST['date']);
$day_of_week = date('w', strtotime($appointment_date)); // 0=Sunday to 6=Saturday

// Get schedule for the chamber on this day
$schedule_query = "SELECT start_time, end_time, slot_duration, is_free_for_poor 
                   FROM chamber_schedules 
                   WHERE chamber_id = '$chamber_id' AND day_of_week = '$day_of_week'";
$schedule_result = mysqli_query($conn, $schedule_query);
$schedule = mysqli_fetch_assoc($schedule_result);

if($schedule) {
    $start_time = new DateTime($schedule['start_time']);
    $end_time = new DateTime($schedule['end_time']);
    $slot_duration = $schedule['slot_duration']; // in minutes
    
    // Get already booked slots
    $booked_slots = [];
    $booked_query = "SELECT start_time FROM time_slots 
                     WHERE chamber_id = '$chamber_id' 
                     AND slot_date = '$appointment_date' 
                     AND is_booked = 1";
    $booked_result = mysqli_query($conn, $booked_query);
    while($row = mysqli_fetch_assoc($booked_result)) {
        $booked_slots[] = $row['start_time'];
    }
    
    // Generate available slots
    while($start_time < $end_time) {
        $slot_start = $start_time->format('H:i:s');
        $slot_end = clone $start_time;
        $slot_end->modify("+$slot_duration minutes");
        
        // Check if slot is not already booked
        if(!in_array($slot_start, $booked_slots)) {
            echo "<option value='$slot_start'>" . date('h:i A', strtotime($slot_start)) . 
                 " - " . date('h:i A', strtotime($slot_end->format('H:i:s'))) . "</option>";
        }
        
        $start_time->modify("+$slot_duration minutes");
    }
} else {
    echo "<option value=''>No schedule available for this day</option>";
}
?>