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

include_once 'db_connect.php'; 

// التأكد من وصول معرف المريض
if (!isset($_GET['patient_id'])) {
    echo json_encode(["status" => "error", "message" => "ID المريض مفقود"]);
    exit;
}

$patient_id = $_GET['patient_id'];

try {
    $conn->exec("set names utf8mb4");

    // استعلام يجلب بيانات الحجز + اسم الطبيب من جدول المستخدمين المرتبط بالأطباء
    $sql = "SELECT 
                b.*, 
                u.full_name as doctor_name
            FROM bookings b
            JOIN doctors d ON b.doctor_id = d.id
            JOIN users u ON d.user_id = u.id
            WHERE b.patient_id = :pat_id
            ORDER BY b.appointment_date DESC";

    $stmt = $conn->prepare($sql);
    $stmt->bindParam(':pat_id', $patient_id);
    $stmt->execute();

    $bookings = $stmt->fetchAll(PDO::FETCH_ASSOC);

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

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