<?php
/**
 * Get Capacity Metrics Endpoint
 * 
 * Purpose: Real-time capacity monitoring for a specific doctor
 * Returns: Today's scheduled appointments, capacity utilization, and availability
 */

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

include '../layouts/dbconn.php';

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

$response = [];

try {
    // Get and validate parameters
    $doctor_id = isset($_POST['doctor_id']) ? (int)$_POST['doctor_id'] : 0;
    
    if (!$doctor_id || $doctor_id <= 0) {
        throw new Exception('Valid Doctor ID is required');
    }
    
    $today = date('Y-m-d');
    
    // Get doctor information
    $doctor_sql = "SELECT 
                      d.doctor_id,
                      d.max_daily_appointments,
                      d.appointment_duration,
                      d.specialization,
                      u.full_name
                   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);
    if (!$stmt) {
        throw new Exception('Database error: ' . $conn->error);
    }
    
    $stmt->bind_param("i", $doctor_id);
    $stmt->execute();
    $doctor_result = $stmt->get_result();
    $doctor = $doctor_result->fetch_assoc();
    
    if (!$doctor) {
        throw new Exception('Doctor not found or inactive');
    }
    
    $total_capacity = (int)$doctor['max_daily_appointments'];
    $stmt->close();
    
    // Count today's scheduled appointments (excluding cancelled and no-show)
    $scheduled_sql = "SELECT COUNT(*) as scheduled
                     FROM appointments
                     WHERE doctor_id = ?
                     AND appointment_date = ?
                     AND status NOT IN ('CANCELLED', 'NO_SHOW')";
    
    $stmt = $conn->prepare($scheduled_sql);
    $stmt->bind_param("is", $doctor_id, $today);
    $stmt->execute();
    $scheduled_result = $stmt->get_result();
    $scheduled_data = $scheduled_result->fetch_assoc();
    $scheduled_today = (int)$scheduled_data['scheduled'];
    $stmt->close();
    
    // Count checked-in appointments
    $checkedin_sql = "SELECT COUNT(*) as checked_in
                     FROM appointments
                     WHERE doctor_id = ?
                     AND appointment_date = ?
                     AND status IN ('CHECKED_IN', 'IN_PROGRESS')";
    
    $stmt = $conn->prepare($checkedin_sql);
    $stmt->bind_param("is", $doctor_id, $today);
    $stmt->execute();
    $checkedin_result = $stmt->get_result();
    $checkedin_data = $checkedin_result->fetch_assoc();
    $checked_in_today = (int)$checkedin_data['checked_in'];
    $stmt->close();
    
    // Count completed appointments
    $completed_sql = "SELECT COUNT(*) as completed
                     FROM appointments
                     WHERE doctor_id = ?
                     AND appointment_date = ?
                     AND status = 'COMPLETED'";
    
    $stmt = $conn->prepare($completed_sql);
    $stmt->bind_param("is", $doctor_id, $today);
    $stmt->execute();
    $completed_result = $stmt->get_result();
    $completed_data = $completed_result->fetch_assoc();
    $completed_today = (int)$completed_data['completed'];
    $stmt->close();
    
    // Count waiting appointments
    $waiting_sql = "SELECT COUNT(*) as waiting
                   FROM appointments
                   WHERE doctor_id = ?
                   AND appointment_date = ?
                   AND status IN ('SCHEDULED', 'CONFIRMED')";
    
    $stmt = $conn->prepare($waiting_sql);
    $stmt->bind_param("is", $doctor_id, $today);
    $stmt->execute();
    $waiting_result = $stmt->get_result();
    $waiting_data = $waiting_result->fetch_assoc();
    $waiting_today = (int)$waiting_data['waiting'];
    $stmt->close();
    
    // Calculate metrics
    $available_slots = max(0, $total_capacity - $scheduled_today);
    $capacity_percent = $total_capacity > 0 
        ? min(100, round(($scheduled_today / $total_capacity) * 100, 1))
        : 0;
    
    // Determine status
    if ($capacity_percent >= 95) {
        $status = 'full';
        $status_color = 'danger';
    } elseif ($capacity_percent >= 80) {
        $status = 'busy';
        $status_color = 'warning';
    } elseif ($capacity_percent >= 50) {
        $status = 'moderate';
        $status_color = 'info';
    } else {
        $status = 'available';
        $status_color = 'success';
    }
    
    $completion_rate = $scheduled_today > 0
        ? round(($completed_today / $scheduled_today) * 100, 1)
        : 0;
    
    // Build response
    $response = [
        'success' => true,
        'timestamp' => date('Y-m-d H:i:s'),
        'doctor_id' => (int)$doctor['doctor_id'],
        'doctor_name' => $doctor['full_name'],
        'specialization' => $doctor['specialization'],
        'today' => $today,
        'day_name' => date('l'),
        'scheduled_today' => $scheduled_today,
        'checked_in_today' => $checked_in_today,
        'completed_today' => $completed_today,
        'waiting_today' => $waiting_today,
        'total_capacity' => $total_capacity,
        'available_slots' => $available_slots,
        'capacity_percent' => $capacity_percent,
        'status' => $status,
        'status_color' => $status_color,
        'utilization_rate' => $capacity_percent . '%',
        'completion_rate' => $completion_rate,
        'appointment_duration' => (int)$doctor['appointment_duration'],
        'is_available' => $available_slots > 0,
        'is_fully_booked' => $available_slots === 0,
        'is_busy' => $capacity_percent >= 70,
        'message' => $available_slots > 0 
            ? "Doctor has {$available_slots} available slot" . ($available_slots !== 1 ? 's' : '') . " today"
            : "Doctor is fully booked today"
    ];
    
} catch (Exception $e) {
    error_log("Get capacity metrics error: " . $e->getMessage());
    
    $response = [
        'success' => false,
        'error' => $e->getMessage(),
        'timestamp' => date('Y-m-d H:i:s'),
        'scheduled_today' => 0,
        'checked_in_today' => 0,
        'completed_today' => 0,
        'waiting_today' => 0,
        'total_capacity' => 0,
        'available_slots' => 0,
        'capacity_percent' => 0,
        'status' => 'unknown',
        'status_color' => 'secondary',
        'is_available' => false
    ];
}

if (isset($conn) && $conn instanceof mysqli) {
    $conn->close();
}

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