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

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

$doctor_id = isset($_POST['doctor_id']) ? intval($_POST['doctor_id']) : 0;
$days_ahead = isset($_POST['days']) ? intval($_POST['days']) : 14;

if (!$doctor_id) {
    echo json_encode(['success' => false, 'error' => 'Doctor ID required']);
    exit();
}

// Get doctor information and schedule
$doctor_sql = "SELECT d.doctor_id, u.full_name, d.availability_schedule, 
                      d.appointment_duration, d.max_daily_appointments
               FROM doctors d
               JOIN users u ON d.user_id = u.user_id
               WHERE d.doctor_id = ? AND d.is_active = 1";
$stmt = $conn->prepare($doctor_sql);
$stmt->bind_param("i", $doctor_id);
$stmt->execute();
$result = $stmt->get_result();
$doctor = $result->fetch_assoc();
$stmt->close();

if (!$doctor) {
    echo json_encode(['success' => false, 'error' => 'Doctor not found']);
    exit();
}

$schedule_json = $doctor['availability_schedule'];
$appointment_duration = (int)$doctor['appointment_duration'];
$max_daily = (int)$doctor['max_daily_appointments'];

// Parse schedule
$schedule_data = json_decode($schedule_json, true);
if (!is_array($schedule_data)) {
    echo json_encode(['success' => false, 'error' => 'Invalid schedule data']);
    exit();
}

// Check if doctor_schedule_slots exists (date-specific)
$has_slots_table = false;
$tcheck = $conn->query("SHOW TABLES LIKE 'doctor_schedule_slots'");
if ($tcheck && $tcheck->num_rows > 0) {
    $has_slots_table = true;
}

// Generate availability for next N days
$availability = [];
$today = new DateTime();

for ($i = 0; $i < $days_ahead; $i++) {
    $check_date = clone $today;
    $check_date->modify("+$i days");
    
    $date_str = $check_date->format('Y-m-d');
    $day_name = strtolower($check_date->format('l'));
    
    $day_sessions = [];
    if ($has_slots_table) {
        $ds_sql = "SELECT start_time, end_time FROM doctor_schedule_slots WHERE doctor_id = ? AND schedule_date = ?";
        $ds_stmt = $conn->prepare($ds_sql);
        $ds_stmt->bind_param("is", $doctor_id, $date_str);
        $ds_stmt->execute();
        $ds_res = $ds_stmt->get_result();
        while ($r = $ds_res->fetch_assoc()) {
            $day_sessions[] = ['start' => $r['start_time'], 'end' => $r['end_time']];
        }
    }
    if (empty($day_sessions) && isset($schedule_data[$day_name]['sessions']) && !empty($schedule_data[$day_name]['sessions'])) {
        $day_sessions = $schedule_data[$day_name]['sessions'];
    }
    
    $is_working_day = !empty($day_sessions);
    
    if (!$is_working_day) {
        $availability[] = [
            'date' => $date_str,
            'date_formatted' => $check_date->format('M d'),
            'day_name' => $check_date->format('D'),
            'is_working_day' => false,
            'available_slots' => 0,
            'booked_slots' => 0,
            'total_capacity' => 0
        ];
        continue;
    }
    $total_slots = 0;
    
    foreach ($day_sessions as $session) {
        $start_time = $session['start'];
        $end_time = $session['end'];
        
        // Add seconds if missing
        if (strlen($start_time) === 5) $start_time .= ':00';
        if (strlen($end_time) === 5) $end_time .= ':00';
        
        $start = strtotime($start_time);
        $end = strtotime($end_time);
        
        // Calculate slots in this session
        $session_duration = ($end - $start) / 60; // in minutes
        $slots_in_session = floor($session_duration / $appointment_duration);
        $total_slots += $slots_in_session;
    }
    
    // Cap at max_daily
    $total_slots = min($total_slots, $max_daily);
    
    // Get booked appointments for this date
    $booked_sql = "SELECT COUNT(*) as booked_count
                   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_str);
    $booked_stmt->execute();
    $booked_result = $booked_stmt->get_result();
    $booked_data = $booked_result->fetch_assoc();
    $booked_count = (int)$booked_data['booked_count'];
    $booked_stmt->close();
    
    $available_slots = max(0, $total_slots - $booked_count);
    
    $availability[] = [
        'date' => $date_str,
        'date_formatted' => $check_date->format('M d'),
        'day_name' => $check_date->format('D'),
        'is_working_day' => true,
        'available_slots' => $available_slots,
        'booked_slots' => $booked_count,
        'total_capacity' => $total_slots
    ];
}

echo json_encode([
    'success' => true,
    'doctor_id' => $doctor_id,
    'doctor_name' => $doctor['full_name'],
    'days' => $availability
]);

$conn->close();
?>