<?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' => 'Unauthorized']); exit(); }

$allowed_roles = ['SUPER_ADMIN', 'HOSPITAL_ADMIN', 'ACCOUNTANT', 'BILLING_CLERK'];
if (!in_array($_SESSION['role_code'], $allowed_roles)) { echo json_encode(['success' => false, 'message' => 'Access denied']); exit(); }

if ($_SERVER['REQUEST_METHOD'] !== 'POST') { echo json_encode(['success' => false, 'message' => 'Invalid method']); exit(); }

$remittance_id = (int)($_POST['remittance_id'] ?? 0);
if (!$remittance_id) { echo json_encode(['success' => false, 'message' => 'Invalid remittance ID']); exit(); }

// Load remittance header
$rem_stmt = $conn->prepare("SELECT * FROM insurance_remittances WHERE remittance_id = ?");
$rem_stmt->bind_param('i', $remittance_id);
$rem_stmt->execute();
$rem = $rem_stmt->get_result()->fetch_assoc();
$rem_stmt->close();

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

// Load all UNMATCHED items for this remittance
$items_stmt = $conn->prepare("SELECT * FROM insurance_remittance_items WHERE remittance_id = ? AND match_status = 'UNMATCHED'");
$items_stmt->bind_param('i', $remittance_id);
$items_stmt->execute();
$items = $items_stmt->get_result()->fetch_all(MYSQLI_ASSOC);
$items_stmt->close();

$matched   = 0;
$unmatched = 0;

foreach ($items as $item) {
    $matched_invoice_id = null;

    // Strategy 1: Match by exact claim number
    if (!empty($item['claim_number'])) {
        $s1 = $conn->prepare(
            "SELECT invoice_id FROM invoices
             WHERE insurance_claim_number = ?
               AND insurance_provider_id = ?
               AND bill_to = 'INSURANCE'
               AND status NOT IN ('CANCELLED','VOID','PAID')
             LIMIT 1"
        );
        $s1->bind_param('si', $item['claim_number'], $rem['insurance_provider_id']);
        $s1->execute();
        $r1 = $s1->get_result()->fetch_assoc();
        $s1->close();
        if ($r1) $matched_invoice_id = (int)$r1['invoice_id'];
    }

    // Strategy 2: Match by patient name + amount within 10% tolerance
    if (!$matched_invoice_id && !empty($item['patient_name']) && $item['amount_paid'] > 0) {
        $tolerance = $item['amount_paid'] * 0.10;
        $min_amt   = $item['amount_paid'] - $tolerance;
        $max_amt   = $item['amount_paid'] + $tolerance;
        $pat_like  = '%' . $item['patient_name'] . '%';

        $s2 = $conn->prepare(
            "SELECT i.invoice_id
             FROM invoices i
             JOIN patients p ON i.patient_id = p.patient_id
             JOIN users u    ON p.user_id = u.user_id
             WHERE i.insurance_provider_id = ?
               AND i.bill_to = 'INSURANCE'
               AND i.status NOT IN ('CANCELLED','VOID','PAID')
               AND i.balance BETWEEN ? AND ?
               AND u.full_name LIKE ?
             ORDER BY ABS(i.balance - ?) ASC
             LIMIT 1"
        );
        $s2->bind_param('iddsd', $rem['insurance_provider_id'], $min_amt, $max_amt, $pat_like, $item['amount_paid']);
        $s2->execute();
        $r2 = $s2->get_result()->fetch_assoc();
        $s2->close();
        if ($r2) $matched_invoice_id = (int)$r2['invoice_id'];
    }

    if ($matched_invoice_id) {
        // Update item with AUTO_MATCHED status
        $upd = $conn->prepare(
            "UPDATE insurance_remittance_items
             SET invoice_id = ?, match_status = 'AUTO_MATCHED'
             WHERE item_id = ?"
        );
        $upd->bind_param('ii', $matched_invoice_id, $item['item_id']);
        $upd->execute();
        $upd->close();
        $matched++;
    } else {
        $unmatched++;
    }
}

// Update remittance status if some matched
if ($matched > 0 && $rem['status'] === 'DRAFT') {
    $conn->query("UPDATE insurance_remittances SET status='SUBMITTED', updated_at=NOW() WHERE remittance_id = $remittance_id AND status='DRAFT'");
}

echo json_encode([
    'success'   => true,
    'matched'   => $matched,
    'unmatched' => $unmatched,
    'message'   => "Auto-match complete: {$matched} matched, {$unmatched} unmatched.",
]);
