<?php
// api/patient/appointments.php
require_once __DIR__ . '/../middleware.php';
require_once __DIR__ . '/../../layouts/dbconn.php';

global $API_USER;
if (!isset($API_USER)) {
    jsonError('Unauthorized', 401);
}

// Get Patient ID from User ID
$user_id = $API_USER['sub'];
$stmt = $conn->prepare("SELECT patient_id FROM patients WHERE user_id = ?");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$res = $stmt->get_result();

if ($res->num_rows === 0) {
    jsonError('Patient profile not found', 404);
}

$patient = $res->fetch_assoc();
$patient_id = $patient['patient_id'];

if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $sql = "SELECT a.appointment_id, a.appointment_date, a.status, a.reason,
                   u.full_name as doctor_name, d.department_name
            FROM appointments a
            LEFT JOIN users u ON a.doctor_id = u.user_id
            LEFT JOIN departments d ON a.department_id = d.department_id
            WHERE a.patient_id = ?
            ORDER BY a.appointment_date DESC";

    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $patient_id);
    $stmt->execute();
    $result = $stmt->get_result();

    $appointments = [];
    while ($row = $result->fetch_assoc()) {
        $appointments[] = $row;
    }

    jsonResponse($appointments);

} else {
    jsonError('Method not allowed', 405);
}
?>