<?php
session_start();
header('Content-Type: application/json');
include '../layouts/dbconn.php';

if (!isset($_SESSION['user_id'])) {
    echo json_encode([]);
    exit();
}

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

if (!$doctor_id || !$date) {
    echo json_encode([]);
    exit();
}

// Validate date format
if (!preg_match('/^\d{4}-\d{2}-\d{2}$/', $date)) {
    echo json_encode([]);
    exit();
}

// Step 1: Fetch doctor's schedule and details
$doctor_sql = "SELECT availability_schedule, appointment_duration, max_daily_appointments 
               FROM doctors WHERE doctor_id = ? AND is_active = 1 LIMIT 1";
$doctor_stmt = $conn->prepare($doctor_sql);
$doctor_stmt->bind_param("i", $doctor_id);
$doctor_stmt->execute();
$doctor_result = $doctor_stmt->get_result();
$doctor = $doctor_result->fetch_assoc();
$doctor_stmt->close();

if (!$doctor) {
    error_log("get_available_slots: Doctor $doctor_id not found or inactive");
    echo json_encode([]);
    exit();
}

$schedule_json = $doctor['availability_schedule'];
$duration = (int)($doctor['appointment_duration'] ?? 30);  // Min per slot
$max_daily = (int)($doctor['max_daily_appointments'] ?? 20);  // Cap total slots/day

// Parse JSON schedule (safe fallback if invalid)
$schedule = json_decode($schedule_json, true) ?: [];
if (!is_array($schedule)) {
    error_log("Invalid schedule JSON for doctor $doctor_id");
    echo json_encode([]);
    exit();
}

$slots = [];

// Step 2: Check for existing slots in appointment_slots table
$existing_sql = "SELECT slot_id, start_time, end_time, appointment_type, room_number, max_patients, booked_patients, is_available
                 FROM appointment_slots 
                 WHERE doctor_id = ? AND slot_date = ? AND is_available = 1 AND booked_patients < max_patients
                 ORDER BY start_time ASC";
$existing_stmt = $conn->prepare($existing_sql);
$existing_stmt->bind_param("is", $doctor_id, $date);
$existing_stmt->execute();
$existing_result = $existing_stmt->get_result();

if ($existing_result->num_rows > 0) {
    // Use existing pre-generated slots
    while ($row = $existing_result->fetch_assoc()) {
        $start_time = substr($row['start_time'], 0, 5);
        $estimated_wait = $row['booked_patients'] * ($duration / 2);  // Rough estimate
        $slots[] = [
            'slot_id' => (int)$row['slot_id'],
            'start_time' => $start_time,
            'end_time' => substr($row['end_time'], 0, 5),
            'is_available' => true,
            'booked_patients' => (int)$row['booked_patients'],
            'max_patients' => (int)$row['max_patients'],
            'room_number' => $row['room_number'] ?? null,
            'estimated_wait_time' => $estimated_wait > 0 ? $estimated_wait : null,
            'is_ai_recommended' => in_array($start_time, ['09:00', '10:00', '14:00'])
        ];
    }
    $existing_stmt->close();
    
    error_log("get_available_slots: Using " . count($slots) . " existing slots for doctor $doctor_id on $date");
} else {
    $existing_stmt->close();
    
    // Step 3: Get sessions - prefer date-specific (doctor_schedule_slots) over weekly template
    $day_sessions = [];
    $table_check = $conn->query("SHOW TABLES LIKE 'doctor_schedule_slots'");
    if ($table_check && $table_check->num_rows > 0) {
        $ds_sql = "SELECT start_time, end_time, location_type, facility_name FROM doctor_schedule_slots WHERE doctor_id = ? AND schedule_date = ? ORDER BY start_time";
        $ds_stmt = $conn->prepare($ds_sql);
        $ds_stmt->bind_param("is", $doctor_id, $date);
        $ds_stmt->execute();
        $ds_res = $ds_stmt->get_result();
        while ($r = $ds_res->fetch_assoc()) {
            $day_sessions[] = [
                'location_type' => $r['location_type'],
                'start' => $r['start_time'],
                'end' => $r['end_time'],
                'facility_name' => $r['facility_name']
            ];
        }
    }
    if (empty($day_sessions)) {
        $day_name = strtolower(date('l', strtotime($date)));
        if (!isset($schedule[$day_name]) || empty($schedule[$day_name]['sessions'])) {
            error_log("No schedule for $date (doctor $doctor_id)");
            echo json_encode([]);
            exit();
        }
        $day_sessions = $schedule[$day_name]['sessions'];
    }

    // Get existing appointments to avoid double-booking
    $booked_sql = "SELECT appointment_time FROM appointments 
                   WHERE doctor_id = ? AND appointment_date = ? 
                   AND status NOT IN ('CANCELLED', 'NO_SHOW')";
    $booked_stmt = $conn->prepare($booked_sql);
    $booked_stmt->bind_param("is", $doctor_id, $date);
    $booked_stmt->execute();
    $booked_result = $booked_stmt->get_result();
    
    $booked_times = [];
    while ($booked_row = $booked_result->fetch_assoc()) {
        $booked_times[] = $booked_row['appointment_time'];
    }
    $booked_stmt->close();

    // ✅ FIXED: Loop through all sessions for the day
    $slot_count = 0;
    foreach ($day_sessions as $session) {
        $location_type = $session['location_type'] ?? 'internal';
        $session_start = $session['start'] ?? null;
        $session_end = $session['end'] ?? null;
        
        if (!$session_start || !$session_end) {
            error_log("Session missing start/end time for $day_name: " . json_encode($session));
            continue;
        }

        // Add seconds if missing (09:00 -> 09:00:00)
        if (strlen($session_start) === 5) $session_start .= ':00';
        if (strlen($session_end) === 5) $session_end .= ':00';

        // Generate intervals (e.g., 09:00, 09:30, ..., up to end - duration)
        $current_time = strtotime($date . ' ' . $session_start);
        $end_time = strtotime($date . ' ' . $session_end);

        while ($current_time + ($duration * 60) <= $end_time && $slot_count < $max_daily) {
            $start_str = date('H:i:s', $current_time);
            $end_str = date('H:i:s', $current_time + ($duration * 60));
            
            // Check if this time is already booked
            if (in_array($start_str, $booked_times)) {
                $current_time += ($duration * 60);
                continue; // Skip booked slots
            }

            // Insert into appointment_slots table for future reference
            $insert_sql = "INSERT INTO appointment_slots 
                          (doctor_id, slot_date, start_time, end_time, appointment_type, max_patients, booked_patients, is_available) 
                          VALUES (?, ?, ?, ?, 'CONSULTATION', 1, 0, 1)";
            $insert_stmt = $conn->prepare($insert_sql);
            $insert_stmt->bind_param("isss", $doctor_id, $date, $start_str, $end_str);
            $insert_stmt->execute();
            $slot_id = $conn->insert_id;
            $insert_stmt->close();

            // Add to response
            $start_display = substr($start_str, 0, 5);
            $slots[] = [
                'slot_id' => $slot_id,
                'start_time' => $start_display,
                'end_time' => substr($end_str, 0, 5),
                'is_available' => true,
                'booked_patients' => 0,
                'max_patients' => 1,
                'room_number' => null,
                'estimated_wait_time' => null,
                'session_type' => ucfirst($location_type),
                'location' => $location_type === 'external' ? ($session['facility_name'] ?? 'External') : 'Main Hospital',
                'is_ai_recommended' => in_array($start_display, ['09:00', '10:00', '14:00'])
            ];

            $current_time += ($duration * 60);
            $slot_count++;
        }
    }

    error_log("Generated $slot_count slots for $date (doctor $doctor_id) from " . count($day_sessions) . " session(s)");
}

$conn->close();

// Debug log
error_log("get_available_slots: Doctor $doctor_id, Date $date, Returning " . count($slots) . " slots");

echo json_encode($slots);
exit();
?>