<?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) {
    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
$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();
$existing_count = $existing_result->num_rows;
$existing_stmt->close();

if ($existing_count > 0) {
    // Use existing 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'])
        ];
    }
} else {
    // Step 3: Generate slots dynamically if none exist
    $day_name = strtolower(date('l', strtotime($date)));  // e.g., 'monday'
    if (!isset($schedule[$day_name]) || !$schedule[$day_name]['available']) {
        // No availability for this day
        error_log("No schedule for $day_name on $date for doctor $doctor_id");
        echo json_encode([]);
        exit();
    }

    $day_slots = $schedule[$day_name]['slots'] ?? [];
    if (empty($day_slots)) {
        echo json_encode([]);
        exit();
    }

    // Use first slot config (assuming one per day; extend if multiple)
    $day_start = $day_slots[0]['start'] ?? null;
    $day_end = $day_slots[0]['end'] ?? null;
    if (!$day_start || !$day_end) {
        echo json_encode([]);
        exit();
    }

    // Generate intervals (e.g., 09:00, 09:30, ..., up to end - duration)
    $current_time = strtotime($day_start);
    $end_time = strtotime($day_end);
    $slot_count = 0;

    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));

        // Insert into DB (max_patients=1 for now; adjust if multi-patient)
        $insert_sql = "INSERT INTO appointment_slots (doctor_id, slot_date, start_time, end_time, max_patients, booked_patients, is_available) 
                       VALUES (?, ?, ?, ?, 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,
            '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)");
}

$conn->close();

// Debug log (remove after testing)
error_log("get_available_slots: Doctor $doctor_id, Date $date, Found " . count($slots) . " slots");

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