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

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

if (!isset($_SESSION['user_id'])) { echo json_encode([]); exit(); }

$provider_id = (int)($_GET['provider_id'] ?? 0);
$q           = trim($_GET['q'] ?? '');

if (!$provider_id) { echo json_encode([]); exit(); }

$where = "i.insurance_provider_id = ? AND i.bill_to = 'INSURANCE' AND i.status IN ('SENT','PARTIAL_PAYMENT','OVERDUE') AND i.balance > 0";
$types = 'i';
$vals  = [$provider_id];

if ($q !== '') {
    $where .= ' AND (i.invoice_number LIKE ? OR u.full_name LIKE ? OR i.insurance_claim_number LIKE ?)';
    $types .= 'sss';
    $like = '%' . $q . '%';
    $vals[] = $like; $vals[] = $like; $vals[] = $like;
}

$stmt = $conn->prepare(
    "SELECT i.invoice_id, i.invoice_number, i.invoice_date,
            i.total_amount, i.amount_paid, i.balance,
            i.insurance_claim_number, u.full_name AS patient_name
     FROM invoices i
     JOIN patients p ON i.patient_id = p.patient_id
     JOIN users u    ON p.user_id = u.user_id
     WHERE $where
     ORDER BY i.invoice_date DESC
     LIMIT 100"
);
$stmt->bind_param($types, ...$vals);
$stmt->execute();
$rows = $stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$stmt->close();

echo json_encode($rows);
