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

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

// Get doctor information
$doctor_sql = "SELECT d.doctor_id, u.full_name, d.specialization, 
                      d.appointment_duration, d.max_daily_appointments,
                      d.availability_schedule
               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();
}

$today = date('Y-m-d');
$day_name = strtolower(date('l')); // e.g., 'wednesday'

// Parse doctor's schedule to get today's capacity
$schedule_json = $doctor['availability_schedule'];
$schedule_data = json_decode($schedule_json, true);
$appointment_duration = (int)$doctor['appointment_duration'];
$max_daily = (int)$doctor['max_daily_appointments'];

// Calculate total slots for today
$total_capacity = 0;
$is_available_today = false;

if (is_array($schedule_data) && isset($schedule_data[$day_name]) && !empty($schedule_data[$day_name]['sessions'])) {
    $is_available_today = true;
    $day_sessions = $schedule_data[$day_name]['sessions'];
    
    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_capacity += $slots_in_session;
    }
    
    // Cap at max_daily
    $total_capacity = min($total_capacity, $max_daily);
}

// Get today's appointments breakdown
$stats_sql = "SELECT 
    COUNT(*) as total,
    SUM(CASE WHEN status = 'SCHEDULED' THEN 1 ELSE 0 END) as scheduled,
    SUM(CASE WHEN status = 'CONFIRMED' THEN 1 ELSE 0 END) as confirmed,
    SUM(CASE WHEN status = 'CHECKED_IN' THEN 1 ELSE 0 END) as checked_in,
    SUM(CASE WHEN status = 'IN_PROGRESS' THEN 1 ELSE 0 END) as in_progress,
    SUM(CASE WHEN status = 'COMPLETED' THEN 1 ELSE 0 END) as completed,
    SUM(CASE WHEN status = 'NO_SHOW' THEN 1 ELSE 0 END) as no_show,
    SUM(CASE WHEN status IN ('SCHEDULED', 'CONFIRMED', 'CHECKED_IN', 'IN_PROGRESS') THEN 1 ELSE 0 END) as waiting
FROM appointments
WHERE doctor_id = ? 
  AND appointment_date = ?
  AND status NOT IN ('CANCELLED')";

$stats_stmt = $conn->prepare($stats_sql);
$stats_stmt->bind_param("is", $doctor_id, $today);
$stats_stmt->execute();
$stats_result = $stats_stmt->get_result();
$stats = $stats_result->fetch_assoc();
$stats_stmt->close();

$scheduled_today = (int)$stats['total'];
$checked_in_today = (int)$stats['checked_in'];
$completed_today = (int)$stats['completed'];
$waiting_today = (int)$stats['waiting'];

// Calculate available slots
$available_slots = max(0, $total_capacity - $scheduled_today);

// Calculate capacity percentage
$capacity_percent = $total_capacity > 0 ? round(($scheduled_today / $total_capacity) * 100, 1) : 0;

// Determine status
$status = 'available';
$status_color = 'success';
$is_busy = false;
$is_fully_booked = false;

if ($capacity_percent >= 100) {
    $status = 'fully_booked';
    $status_color = 'danger';
    $is_fully_booked = true;
} elseif ($capacity_percent >= 80) {
    $status = 'busy';
    $status_color = 'warning';
    $is_busy = true;
}

// Calculate rates
$completion_rate = $scheduled_today > 0 ? round(($completed_today / $scheduled_today) * 100, 1) : 0;
$utilization_rate = $total_capacity > 0 ? round(($scheduled_today / $total_capacity) * 100, 1) : 0;

$response = [
    'success' => true,
    'doctor_id' => $doctor_id,
    'doctor_name' => $doctor['full_name'],
    'specialization' => $doctor['specialization'],
    'today' => $today,
    'day_name' => ucfirst($day_name),
    'timestamp' => date('Y-m-d H:i:s'),
    
    // Capacity metrics
    'total_capacity' => $total_capacity,
    'scheduled_today' => $scheduled_today,
    'available_slots' => $available_slots,
    'capacity_percent' => $capacity_percent,
    
    // Status breakdown
    'checked_in_today' => $checked_in_today,
    'completed_today' => $completed_today,
    'waiting_today' => $waiting_today,
    
    // Status indicators
    'is_available' => $is_available_today,
    'is_busy' => $is_busy,
    'is_fully_booked' => $is_fully_booked,
    'status' => $status,
    'status_color' => $status_color,
    
    // Rates
    'completion_rate' => $completion_rate,
    'utilization_rate' => $utilization_rate . '%',
    
    // Message
    'message' => $is_fully_booked 
        ? "Doctor is fully booked today" 
        : ($is_busy 
            ? "Doctor is busy with limited slots" 
            : "Doctor has $available_slots available slots today")
];

echo json_encode($response);

$conn->close();
?>