<?php
/**
 * Get Scheduling Statistics Endpoint
 * 
 * Purpose: Comprehensive scheduling analytics and statistics
 * Returns: Today's stats, weekly trends, top doctors, and performance metrics
 */

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 {
    $today = date('Y-m-d');
    $current_time = date('H:i:s');
    $week_start = date('Y-m-d', strtotime('-6 days'));
    
    // Total appointments today
    $total_sql = "SELECT COUNT(*) as total 
                  FROM appointments 
                  WHERE appointment_date = ?";
    
    $stmt = $conn->prepare($total_sql);
    $stmt->bind_param("s", $today);
    $stmt->execute();
    $total_result = $stmt->get_result();
    $total_data = $total_result->fetch_assoc();
    $total_today = (int)$total_data['total'];
    $stmt->close();
    
    // Scheduled appointments
    $scheduled_sql = "SELECT COUNT(*) as count 
                     FROM appointments 
                     WHERE appointment_date = ? 
                     AND status = 'SCHEDULED'";
    
    $stmt = $conn->prepare($scheduled_sql);
    $stmt->bind_param("s", $today);
    $stmt->execute();
    $result = $stmt->get_result();
    $scheduled_count = (int)$result->fetch_assoc()['count'];
    $stmt->close();
    
    // Confirmed appointments
    $confirmed_sql = "SELECT COUNT(*) as count 
                     FROM appointments 
                     WHERE appointment_date = ? 
                     AND status = 'CONFIRMED'";
    
    $stmt = $conn->prepare($confirmed_sql);
    $stmt->bind_param("s", $today);
    $stmt->execute();
    $result = $stmt->get_result();
    $confirmed_count = (int)$result->fetch_assoc()['count'];
    $stmt->close();
    
    // Checked-in appointments
    $checkedin_sql = "SELECT COUNT(*) as count 
                     FROM appointments 
                     WHERE appointment_date = ? 
                     AND status = 'CHECKED_IN'";
    
    $stmt = $conn->prepare($checkedin_sql);
    $stmt->bind_param("s", $today);
    $stmt->execute();
    $result = $stmt->get_result();
    $checked_in = (int)$result->fetch_assoc()['count'];
    $stmt->close();
    
    // In progress appointments
    $inprogress_sql = "SELECT COUNT(*) as count 
                      FROM appointments 
                      WHERE appointment_date = ? 
                      AND status = 'IN_PROGRESS'";
    
    $stmt = $conn->prepare($inprogress_sql);
    $stmt->bind_param("s", $today);
    $stmt->execute();
    $result = $stmt->get_result();
    $in_progress = (int)$result->fetch_assoc()['count'];
    $stmt->close();
    
    // Completed appointments
    $completed_sql = "SELECT COUNT(*) as count 
                     FROM appointments 
                     WHERE appointment_date = ? 
                     AND status = 'COMPLETED'";
    
    $stmt = $conn->prepare($completed_sql);
    $stmt->bind_param("s", $today);
    $stmt->execute();
    $result = $stmt->get_result();
    $completed = (int)$result->fetch_assoc()['count'];
    $stmt->close();
    
    // No shows
    $noshow_sql = "SELECT COUNT(*) as count 
                  FROM appointments 
                  WHERE appointment_date = ? 
                  AND status = 'NO_SHOW'";
    
    $stmt = $conn->prepare($noshow_sql);
    $stmt->bind_param("s", $today);
    $stmt->execute();
    $result = $stmt->get_result();
    $no_shows = (int)$result->fetch_assoc()['count'];
    $stmt->close();
    
    // Cancelled appointments
    $cancelled_sql = "SELECT COUNT(*) as count 
                     FROM appointments 
                     WHERE appointment_date = ? 
                     AND status = 'CANCELLED'";
    
    $stmt = $conn->prepare($cancelled_sql);
    $stmt->bind_param("s", $today);
    $stmt->execute();
    $result = $stmt->get_result();
    $cancelled = (int)$result->fetch_assoc()['count'];
    $stmt->close();
    
    // Appointment types breakdown
    $types_sql = "SELECT 
                    appointment_type,
                    COUNT(*) as count
                  FROM appointments
                  WHERE appointment_date = ?
                  GROUP BY appointment_type";
    
    $stmt = $conn->prepare($types_sql);
    $stmt->bind_param("s", $today);
    $stmt->execute();
    $types_result = $stmt->get_result();
    
    $appointment_types = [];
    while ($type_row = $types_result->fetch_assoc()) {
        $appointment_types[] = [
            'type' => $type_row['appointment_type'],
            'count' => (int)$type_row['count']
        ];
    }
    $stmt->close();
    
    // Weekly trend
    $weekly_sql = "SELECT 
                     appointment_date,
                     COUNT(*) as count
                   FROM appointments
                   WHERE appointment_date BETWEEN ? AND ?
                   GROUP BY appointment_date
                   ORDER BY appointment_date";
    
    $stmt = $conn->prepare($weekly_sql);
    $stmt->bind_param("ss", $week_start, $today);
    $stmt->execute();
    $weekly_result = $stmt->get_result();
    
    $weekly_trend = [];
    while ($week_row = $weekly_result->fetch_assoc()) {
        $weekly_trend[] = [
            'date' => $week_row['appointment_date'],
            'count' => (int)$week_row['count']
        ];
    }
    $stmt->close();
    
    // Top 5 busiest doctors today
    $doctors_sql = "SELECT 
                      d.doctor_id,
                      u.full_name,
                      d.specialization,
                      COUNT(a.appointment_id) as appointments_count,
                      d.max_daily_appointments,
                      ROUND((COUNT(a.appointment_id) / d.max_daily_appointments * 100), 1) as utilization_percent
                    FROM doctors d
                    JOIN users u ON d.user_id = u.user_id
                    LEFT JOIN appointments a ON d.doctor_id = a.doctor_id 
                      AND a.appointment_date = ?
                      AND a.status NOT IN ('CANCELLED', 'NO_SHOW')
                    WHERE d.is_active = 1
                    GROUP BY d.doctor_id, u.full_name, d.specialization, d.max_daily_appointments
                    ORDER BY appointments_count DESC
                    LIMIT 5";
    
    $stmt = $conn->prepare($doctors_sql);
    $stmt->bind_param("s", $today);
    $stmt->execute();
    $doctors_result = $stmt->get_result();
    
    $top_doctors = [];
    while ($doctor_row = $doctors_result->fetch_assoc()) {
        $top_doctors[] = [
            'doctor_id' => (int)$doctor_row['doctor_id'],
            'name' => $doctor_row['full_name'],
            'specialization' => $doctor_row['specialization'],
            'appointments_today' => (int)$doctor_row['appointments_count'],
            'capacity' => (int)$doctor_row['max_daily_appointments'],
            'utilization_percent' => (float)$doctor_row['utilization_percent']
        ];
    }
    $stmt->close();
    
    // Calculate rates
    $no_show_rate = $total_today > 0 
        ? round(($no_shows / $total_today) * 100, 1) 
        : 0;
    
    $completion_rate = $total_today > 0 
        ? round(($completed / $total_today) * 100, 1) 
        : 0;
    
    $cancellation_rate = $total_today > 0 
        ? round(($cancelled / $total_today) * 100, 1) 
        : 0;
    
    // Mock AI metrics (can be improved with actual tracking)
    $ai_acceptance_rate = 85;
    $wait_time_improvement = 12;
    $efficiency_score = max(0, min(100, 100 - ($no_show_rate * 2) - ($cancellation_rate * 1.5)));
    
    // Build response
    $response = [
        'success' => true,
        'date' => $today,
        'time' => $current_time,
        'total_today' => $total_today,
        'scheduled' => $scheduled_count,
        'confirmed' => $confirmed_count,
        'checked_in' => $checked_in,
        'in_progress' => $in_progress,
        'completed' => $completed,
        'no_shows' => $no_shows,
        'cancelled' => $cancelled,
        'no_show_rate' => $no_show_rate,
        'completion_rate' => $completion_rate,
        'cancellation_rate' => $cancellation_rate,
        'appointment_types' => $appointment_types,
        'weekly_trend' => $weekly_trend,
        'top_doctors' => $top_doctors,
        'ai_acceptance_rate' => $ai_acceptance_rate,
        'wait_time_improvement' => $wait_time_improvement,
        'efficiency_score' => round($efficiency_score, 1),
        'insights' => [
            'busiest_time' => 'Morning (9 AM - 12 PM)',
            'average_appointment_duration' => 30,
            'peak_day_this_week' => count($weekly_trend) > 0 ? $weekly_trend[0]['date'] : $today
        ]
    ];
    
} catch (Exception $e) {
    error_log("Get scheduling stats error: " . $e->getMessage());
    
    $response = [
        'success' => false,
        'error' => $e->getMessage(),
        'total_today' => 0,
        'scheduled' => 0,
        'confirmed' => 0,
        'checked_in' => 0,
        'in_progress' => 0,
        'completed' => 0,
        'no_shows' => 0,
        'cancelled' => 0,
        'no_show_rate' => 0,
        'completion_rate' => 0,
        'cancellation_rate' => 0,
        'ai_acceptance_rate' => 0,
        'wait_time_improvement' => 0,
        'efficiency_score' => 0,
        'appointment_types' => [],
        'weekly_trend' => [],
        'top_doctors' => []
    ];
}

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

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