<?php
// api/patient/invoices.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') {
    $result_data = [];

    // Get Total Outstanding
    $bal_sql = "SELECT SUM(balance) as total_outstanding FROM invoices WHERE patient_id = ? AND status != 'CANCELLED'";
    $stmt = $conn->prepare($bal_sql);
    $stmt->bind_param("i", $patient_id);
    $stmt->execute();
    $result_data['total_outstanding'] = $stmt->get_result()->fetch_assoc()['total_outstanding'] ?? 0;

    // Get Invoices
    $sql = "SELECT invoice_id, invoice_number, invoice_date, total_amount, amount_paid, balance, status 
            FROM invoices WHERE patient_id = ? ORDER BY invoice_date DESC";
    $stmt = $conn->prepare($sql);
    $stmt->bind_param("i", $patient_id);
    $stmt->execute();
    $res = $stmt->get_result();

    $invoices = [];
    $base_download_url = "http://" . $_SERVER['HTTP_HOST'] . "/patient_download_records.php";

    while ($row = $res->fetch_assoc()) {
        $row['download_url'] = $base_download_url . "?type=invoice&id=" . $row['invoice_id'];
        $invoices[] = $row;
    }

    $result_data['invoices'] = $invoices;

    jsonResponse($result_data);

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