<?php
session_start();
include 'layouts/dbconn.php';

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Unauthorized']);
    exit();
}

$doctor_id = isset($_POST['doctor_id']) ? (int)$_POST['doctor_id'] : 0;
$date = isset($_POST['date']) ? $_POST['date'] : '';

if (!$doctor_id || !$date) {
    echo json_encode(['success' => false, 'message' => 'Missing required fields']);
    exit();
}

// Fetch slots from appointment_slots table
$slots_sql = "SELECT 
                slot_id,
                start_time,
                end_time,
                is_available,
                booked_patients,
                max_patients,
                room_number
              FROM appointment_slots
              WHERE doctor_id = ?
              AND slot_date = ?
              AND is_available = 1
              ORDER BY start_time ASC";

$stmt = $conn->prepare($slots_sql);
$stmt->bind_param('is', $doctor_id, $date);
$stmt->execute();
$result = $stmt->get_result();

if ($result->num_rows > 0) {
    // Use existing slots from the table
    $slots = [];
    while ($row = $result->fetch_assoc()) {
        $slots[] = $row;
    }
    
    echo json_encode([
        'success' => true,
        'slots' => $slots
    ]);
} else {
    // Generate slots dynamically from doctor's availability_schedule
    $doctor_sql = "SELECT 
                    availability_schedule,
                    appointment_duration
                   FROM doctors
                   WHERE doctor_id = ?";
    
    $stmt = $conn->prepare($doctor_sql);
    $stmt->bind_param('i', $doctor_id);
    $stmt->execute();
    $doctor_result = $stmt->get_result();
    
    if ($doctor_result->num_rows === 0) {
        echo json_encode(['success' => false, 'message' => 'Doctor not found']);
        exit();
    }
    
    $doctor = $doctor_result->fetch_assoc();
    $availability = json_decode($doctor['availability_schedule'], true);
    $duration = $doctor['appointment_duration'];
    
    // Get day of week (monday, tuesday, etc.)
    $day_of_week = strtolower(date('l', strtotime($date)));
    
    $slots = [];
    
    // Check if doctor has schedule for this day
    if (isset($availability[$day_of_week]) && isset($availability[$day_of_week]['sessions'])) {
        $sessions = $availability[$day_of_week]['sessions'];
        
        foreach ($sessions as $session) {
            // Only process internal sessions
            if ($session['location_type'] === 'internal') {
                $start_time = $session['start'];
                $end_time = $session['end'];
                
                // Generate time slots
                $current_time = strtotime($start_time);
                $end_timestamp = strtotime($end_time);
                
                while ($current_time < $end_timestamp) {
                    $slot_time = date('H:i:s', $current_time);
                    $slot_end = date('H:i:s', strtotime("+$duration minutes", $current_time));
                    
                    // Check if this slot is already booked
                    $check_booking_sql = "SELECT COUNT(*) as count 
                                         FROM appointments 
                                         WHERE doctor_id = ? 
                                         AND appointment_date = ? 
                                         AND appointment_time = ?
                                         AND status NOT IN ('CANCELLED', 'NO_SHOW')";
                    $check_stmt = $conn->prepare($check_booking_sql);
                    $check_stmt->bind_param('iss', $doctor_id, $date, $slot_time);
                    $check_stmt->execute();
                    $booking_result = $check_stmt->get_result()->fetch_assoc();
                    
                    $is_available = ($booking_result['count'] == 0) ? 1 : 0;
                    
                    // Check if slot is in the past
                    $slot_datetime = strtotime($date . ' ' . $slot_time);
                    if ($slot_datetime < time()) {
                        $is_available = 0;
                    }
                    
                    $slots[] = [
                        'slot_id' => 0, // Dynamic slot, no ID
                        'start_time' => $slot_time,
                        'end_time' => $slot_end,
                        'is_available' => $is_available,
                        'booked_patients' => $is_available ? 0 : 1,
                        'max_patients' => 1,
                        'room_number' => null
                    ];
                    
                    $current_time = strtotime("+$duration minutes", $current_time);
                }
            }
        }
    }
    
    echo json_encode([
        'success' => true,
        'slots' => $slots
    ]);
}
?>