<?php
session_start();
error_reporting(0); // Prevent PHP warnings from corrupting the JSON output
ob_start();

require_once '../db.php';
header('Content-Type: application/json');

$invoice_no = isset($_GET['invoice_no']) ? $conn->real_escape_string($_GET['invoice_no']) : '';

if (empty($invoice_no)) {
    ob_end_clean(); echo json_encode(['status' => 'error', 'message' => 'No invoice reference provided.']); exit;
}

$response = [];

try {
    // 1. Fetch Facility Profile (Hospital Details)
    $qFac = $conn->query("SELECT hospital_name, primary_phone, secondary_phone, primary_email, address, postal_address, primary_hex FROM facility_profile LIMIT 1");
    $response['facility'] = $qFac ? $qFac->fetch_assoc() : [
        'hospital_name' => 'Hospital Name Not Configured', 'primary_phone' => '', 'primary_email' => '', 'address' => '', 'postal_address' => '', 'primary_hex' => '#0f172a'
    ];

    // 2. Fetch System Workflow Rules
    $qSys = $conn->query("SELECT currency_symbol, date_format, time_format FROM system_workflow_rules LIMIT 1");
    $sys = $qSys ? $qSys->fetch_assoc() : [];
    $response['system'] = [
        'currency' => $sys['currency_symbol'] ?? 'GHS',
        'date_format' => $sys['date_format'] ?? 'd-M-Y',
        'time_format' => ($sys['time_format'] == '24') ? 'H:i' : 'h:i A'
    ];

    // 3. Fetch Invoice Header
    $stmtInv = $conn->prepare("SELECT * FROM patient_invoices WHERE invoice_no = ? LIMIT 1");
    $stmtInv->bind_param("s", $invoice_no);
    $stmtInv->execute();
    $invoice = $stmtInv->get_result()->fetch_assoc();
    $stmtInv->close();

    if (!$invoice) throw new Exception("Invoice not found in the database.");
    
    $response['invoice'] = $invoice;
    $response['invoice']['date_fmt'] = date($response['system']['date_format'] . ' ' . $response['system']['time_format'], strtotime($invoice['created_at']));

    $patient_no = $invoice['patient_no'];
    $inv_time = $invoice['created_at'];
    $dept = strtolower($invoice['department_origin'] ?? '');

    // 4. Fetch Patient Bio-Data Dynamically
    if ($patient_no === 'WALK-IN' || strpos($patient_no, 'WALK-IN') !== false) {
        preg_match('/\((.*?)\)/', $patient_no, $match);
        $w_name = $match[1] ?? 'Walk-In Client';
        $response['patient'] = ['name' => $w_name, 'patient_no' => 'WALK-IN', 'mobile' => 'Not Provided', 'address' => 'Not Provided'];
    } else {
        $qPat = $conn->query("SELECT first_name, last_name, patient_no, mobile, patient_address FROM patient WHERE patient_no = '$patient_no' LIMIT 1");
        if ($qPat && $pat = $qPat->fetch_assoc()) {
            $response['patient'] = [
                'name' => trim($pat['first_name'] . ' ' . $pat['last_name']),
                'patient_no' => $pat['patient_no'],
                'mobile' => !empty($pat['mobile']) ? $pat['mobile'] : 'Not Provided',
                'address' => !empty($pat['patient_address']) ? $pat['patient_address'] : 'Not Provided'
            ];
        } else {
            $response['patient'] = ['name' => 'Unknown Patient', 'patient_no' => $patient_no, 'mobile' => 'N/A', 'address' => 'N/A'];
        }
    }

    // 5. Fetch Payment Ledger
    $payments = [];
    $qPay = $conn->query("SELECT p.*, s.first_name as s_fname, s.last_name as s_lname FROM patient_payments p LEFT JOIN staff s ON p.processed_by = s.staff_id WHERE p.invoice_no = '$invoice_no' ORDER BY p.created_at ASC");
    if ($qPay) {
        while ($p = $qPay->fetch_assoc()) {
            $p['date_fmt'] = date($response['system']['date_format'] . ' ' . $response['system']['time_format'], strtotime($p['created_at']));
            $p['cashier'] = trim(($p['s_fname'] ?? 'System') . ' ' . ($p['s_lname'] ?? ''));
            $payments[] = $p;
        }
    }
    $response['payments'] = $payments;

    // =========================================================================================
    // 6. DYNAMIC EXACT ITEM FETCHER (Scans Pharmacy, Labs, Wards for the exact items billed)
    // =========================================================================================
    $items = [];

    if (strpos($patient_no, 'WALK-IN') !== false) {
        // OTC Walk-In Extraction
        $qOTC = $conn->query("SELECT sc.service_name as item_name, ABS(it.quantity_changed) as qty, sc.cash_price_adult as unit_price, (ABS(it.quantity_changed) * sc.cash_price_adult) as total_price FROM inventory_transactions it JOIN service_catalog sc ON it.service_id = sc.id WHERE it.transaction_type = 'Dispense' AND ABS(TIMESTAMPDIFF(MINUTE, it.created_at, '$inv_time')) <= 15");
        if ($qOTC) while ($row = $qOTC->fetch_assoc()) $items[] = $row;
    } 
    elseif (strpos($dept, 'pharma') !== false || strpos($dept, 'otc') !== false) {
        // Pharmacy Extraction (Looks back 30 days to catch previously written prescriptions billed today)
        $qPharma = $conn->query("SELECT cp.drug_name as item_name, cp.quantity as qty, COALESCE(sc.cash_price_adult, 0) as unit_price, (cp.quantity * COALESCE(sc.cash_price_adult, 0)) as total_price FROM clinical_prescriptions cp LEFT JOIN service_catalog sc ON cp.service_id = sc.id WHERE cp.patient_no = '$patient_no' AND cp.status IN ('Billed', 'Dispensed') AND cp.created_at >= DATE_SUB('$inv_time', INTERVAL 30 DAY)");
        if ($qPharma) while ($row = $qPharma->fetch_assoc()) $items[] = $row;
    } 
    else {
        // Lab, OPD, and General Services Extraction
        $qSvc = $conn->query("SELECT sc.service_name as item_name, vd.quantity as qty, vd.billed_amount as total_price, (vd.billed_amount / vd.quantity) as unit_price FROM visit_details vd JOIN visit_master vm ON vd.visit_master_id = vm.id JOIN service_catalog sc ON vd.service_id = sc.id WHERE vm.patient_no = '$patient_no' AND vm.visit_date >= DATE_SUB('$inv_time', INTERVAL 30 DAY) AND vd.status IN ('Pending', 'Completed', 'Billed', 'Paid')");
        if ($qSvc) while ($row = $qSvc->fetch_assoc()) $items[] = $row;

        // IPD Ward Services Extraction
        $qIpd = $conn->query("SELECT sc.service_name as item_name, 1 as qty, r.billed_amount as total_price, r.billed_amount as unit_price FROM ipd_patient_service_requests r JOIN service_catalog sc ON r.ipd_service_id = sc.id WHERE r.patient_no = '$patient_no' AND r.requested_at >= DATE_SUB('$inv_time', INTERVAL 30 DAY)");
        if ($qIpd) while ($row = $qIpd->fetch_assoc()) $items[] = $row;
    }
    
    // Fail-safe (Only triggers if the legacy database linking completely failed)
    if (empty($items)) {
        $items[] = ['item_name' => 'General Billed Services (' . $invoice['department_origin'] . ')', 'qty' => 1, 'unit_price' => $invoice['total_amount'], 'total_price' => $invoice['total_amount']];
    }
    
    $response['items'] = $items;
    $response['status'] = 'success';

    ob_end_clean(); echo json_encode($response); exit;

} catch (Exception $e) {
    ob_end_clean(); echo json_encode(['status' => 'error', 'message' => $e->getMessage()]); exit;
}
?>