<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
header("Access-Control-Allow-Headers: Content-Type");
header("Content-Type: application/json; charset=UTF-8");

include_once 'db_connect.php'; 

// المفتاح هنا يجب أن يطابق ما يرسله التطبيق بالضبط (doctor_id)
$user_id = isset($_GET['doctor_id']) ? $_GET['doctor_id'] : (isset($_POST['doctor_id']) ? $_POST['doctor_id'] : null);

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

try {
    $conn->exec("SET NAMES utf8mb4");

    // الاستعلام الأساسي مع ضمان جلب p.*
    $sql = "SELECT 
                b.id AS booking_id, b.appointment_time, b.appointment_date, b.is_pay, 
                u.full_name, u.address, u.phone,
                p.* FROM bookings b
            JOIN users u ON b.patient_id = u.id
            JOIN doctors d ON b.doctor_id = d.id
            LEFT JOIN patients p ON b.patient_id = p.user_id
            WHERE d.user_id = :user_id 
            AND b.appointment_date > CURDATE()
            ORDER BY b.appointment_date ASC, b.appointment_time ASC";

    $stmt = $conn->prepare($sql);
    $stmt->execute([':user_id' => $user_id]);
    $appointments = $stmt->fetchAll(PDO::FETCH_ASSOC);

    echo json_encode([
        "status" => "success", 
        "data" => $appointments
    ]);

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