<?php
// ajax/get_insurance_invoice.php
session_start();
include '../layouts/dbconn.php';
include '../layouts/session.php';

header('Content-Type: application/json');

if (!isset($_SESSION['user_id'])) {
    echo json_encode(['success' => false, 'message' => 'Not authenticated.']);
    exit();
}

$invoice_id = isset($_GET['id']) ? (int)$_GET['id'] : 0;
if ($invoice_id <= 0) {
    echo json_encode(['success' => false, 'message' => 'Invalid invoice ID.']);
    exit();
}

// ── Fetch invoice (must be bill_to = INSURANCE) ───────────────────────────────
$sql = "SELECT
    i.invoice_id,
    i.invoice_number,
    i.invoice_date,
    i.due_date,
    i.status,
    i.bill_to,
    i.subtotal,
    i.tax_amount,
    i.discount_amount,
    i.insurance_covered,
    i.copay_percentage,
    i.total_amount,
    i.patient_portion,
    i.amount_paid,
    i.balance,
    i.payment_terms,
    i.insurance_claim_number,
    i.smart_claim_submitted,
    i.smart_claim_code,
    i.etims_submitted,
    i.etims_invoice_number,
    i.notes,
    u.full_name      AS patient_name,
    p.patient_number,
    ip.provider_name AS insurance_provider,
    ip.provider_code,
    ip.coverage_percentage,
    pv.visit_number
FROM invoices i
JOIN patients p          ON i.patient_id             = p.patient_id
JOIN users u             ON p.user_id                = u.user_id
JOIN patient_visits pv   ON i.visit_id               = pv.visit_id
LEFT JOIN insurance_providers ip ON i.insurance_provider_id = ip.provider_id
WHERE i.invoice_id = ?
  AND i.bill_to = 'INSURANCE'
LIMIT 1";

$stmt = $conn->prepare($sql);
$stmt->bind_param('i', $invoice_id);
$stmt->execute();
$invoice = $stmt->get_result()->fetch_assoc();
$stmt->close();

if (!$invoice) {
    echo json_encode(['success' => false, 'message' => 'Insurance invoice not found.']);
    exit();
}

// ── Fetch line items ──────────────────────────────────────────────────────────
$istmt = $conn->prepare("SELECT item_id, item_type, description, quantity, unit_price, total_price,
                                 date_of_service, commission_rate, commission_amount
                          FROM invoice_items
                          WHERE invoice_id = ?
                          ORDER BY item_id");
$istmt->bind_param('i', $invoice_id);
$istmt->execute();
$items = $istmt->get_result()->fetch_all(MYSQLI_ASSOC);
$istmt->close();

// Force numeric types for clean JSON
$num_fields = ['subtotal','tax_amount','discount_amount','insurance_covered','copay_percentage',
               'total_amount','patient_portion','amount_paid','balance'];
foreach ($num_fields as $f) {
    $invoice[$f] = (float)($invoice[$f] ?? 0);
}
foreach ($items as &$it) {
    $it['quantity']          = (int)$it['quantity'];
    $it['unit_price']        = (float)$it['unit_price'];
    $it['total_price']       = (float)$it['total_price'];
    $it['commission_rate']   = (float)$it['commission_rate'];
    $it['commission_amount'] = (float)$it['commission_amount'];
}
unset($it);

echo json_encode([
    'success' => true,
    'invoice' => $invoice,
    'items'   => $items,
]);
$conn->close();
?>