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

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

$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') {
    $documents = [];
    $base_download_url = "http://" . $_SERVER['HTTP_HOST'] . "/patient_download_records.php";

    // 1. Visit Reports
    $sql = "SELECT c.consultation_id, c.consultation_date, u.full_name as doctor_name
            FROM consultations c
            JOIN doctors d ON c.doctor_id = d.user_id 
            JOIN users u ON d.user_id = u.user_id
            WHERE c.patient_id = ?
            ORDER BY c.consultation_date DESC";

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

    while ($row = $res->fetch_assoc()) {
        $documents[] = [
            'type' => 'Visit Report',
            'date' => $row['consultation_date'],
            'description' => 'Consultation with Dr. ' . $row['doctor_name'],
            'download_url' => $base_download_url . "?type=visit&id=" . $row['consultation_id']
        ];
    }

    // 2. Prescriptions (Future: if implement PDF download)
    // ...

    jsonResponse($documents);

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