<?php
// get_stats.php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
include_once 'db_connect.php'; 

// استلام الـ ID القادم من فلاتر (والذي هو في الحقيقة user_id من البروفايدر)
$user_id = isset($_GET['doctor_id']) ? $_GET['doctor_id'] : null;

if (!$user_id) {
    echo json_encode(["status" => "error", "message" => "User ID is required"]);
    exit;
}

try {
    $today = date('Y-m-d');

    // استعلام ذكي: 
    // 1. يبحث عن الطبيب المرتبط بـ user_id
    // 2. يحسب حجوزاته لليوم وحجوزاته المستقبلية
    $sql = "SELECT 
                d.id as real_doctor_id,
                (SELECT COUNT(*) FROM bookings WHERE doctor_id = d.id AND appointment_date = :today) as today_count,
                (SELECT COUNT(*) FROM bookings WHERE doctor_id = d.id AND appointment_date > :today) as future_count
            FROM doctors d 
            WHERE d.user_id = :user_id LIMIT 1";

    $stmt = $conn->prepare($sql);
    $stmt->execute([
        ':user_id' => $user_id,
        ':today'   => $today
    ]);
    
    $result = $stmt->fetch(PDO::FETCH_ASSOC);

    if ($result) {
        echo json_encode([
            "status" => "success",
            "data" => [
                "today" => (int)$result['today_count'],
                "future" => (int)$result['future_count'],
                "info" => [
                    "sent_user_id" => $user_id,
                    "found_doctor_id" => $result['real_doctor_id']
                ]
            ]
        ]);
    } else {
        // إذا لم يجد طبيباً مرتباً بهذا المستخدم
        echo json_encode([
            "status" => "error", 
            "message" => "No doctor profile found for this user ID",
            "received_id" => $user_id
        ]);
    }

} catch (PDOException $e) {
    echo json_encode(["status" => "error", "message" => $e->getMessage()]);
}
?>