<?php
// api/patient/reports.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
$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') {
    // Logic from patient_visit_reports.php
    // Include lab tests aggregation if possible, or simplifed
    $sql = "SELECT c.consultation_id, c.consultation_date, c.diagnosis, c.treatment_plan, 
                   u.full_name as doctor_name, d.specialization,
                   (SELECT GROUP_CONCAT(test_name SEPARATOR ', ') FROM lab_orders lo JOIN lab_tests lt ON lo.test_id = lt.test_id WHERE lo.visit_id = c.visit_id) as lab_tests
            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();
    $result = $stmt->get_result();

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

    jsonResponse($reports);

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