<?php
/**
 * AR / Collections — per-VISIT work view (ar.work). Two levels:
 *   LEVEL 1 (?process&account)        — patient demographics + a ROW LIST of this account's visits (DOS, carrier,
 *                                        CPTs, balance, status). Click a visit to open it.
 *   LEVEL 2 (?process&account&visit)  — that visit's full detail: demographics + provider + carrier(s) + the CPT
 *                                        charge lines + balances + a WORKED HISTORY (who worked it before, when,
 *                                        with what claim status / action / follow-up / notes), and the tag form
 *                                        where the AR user sets claim_status · action_taken · follow-up(≤45d) · notes.
 * A worked visit moves to its own bucket (action_taken 'SENT TO CODING' / 'ESCALATED TO CLIENT'); the account is
 * not held until every visit is worked — each visit settles on its own.
 */
require_once __DIR__ . '/../includes/config.php';
$user = require_login('internal');
$pdo  = db();
$uid  = (int) $user['id'];

$pid       = (int) ($_GET['process'] ?? $_POST['process'] ?? 0);
$chart     = (string) ($_GET['account'] ?? $_POST['account'] ?? '');
$selVisit  = (string) ($_GET['visit'] ?? '');
$acctUrl   = '/admin/ar-work.php?process=' . $pid . '&account=' . rawurlencode($chart);
$visitUrl  = fn(string $v) => $acctUrl . '&visit=' . rawurlencode($v);

/* ---- POST: save one visit's work ---- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'save_visit') {
    csrf_check_or_die();
    if (!can('ar.work')) { http_response_code(403); exit('Forbidden'); }
    $vid         = (int) input('visit_work_id');
    $vKey        = (string) input('visit_id');
    $claimStatus = trim((string) input('claim_status'));
    $actionTaken = trim((string) input('action_taken'));
    $followUp    = trim((string) input('next_follow_up_date'));
    $notes       = trim((string) input('notes'));
    $backV = $vKey !== '' ? $visitUrl($vKey) : $acctUrl;
    $validS = ar_dropdowns($pdo, 'claim_status'); $validA = ar_dropdowns($pdo, 'action_taken');
    if ($claimStatus === '' || $actionTaken === '')           { flash('error', 'Pick a claim status and an action taken.'); redirect($backV); }
    if (!in_array($claimStatus, $validS, true))               { flash('error', 'Pick a valid claim status from the list.'); redirect($backV); }
    if (!in_array($actionTaken, $validA, true))               { flash('error', 'Pick a valid action taken from the list.'); redirect($backV); }
    if ($followUp === '' && ar_action_requires_followup($actionTaken)) { flash('error', 'A next follow-up date is required for this action.'); redirect($backV); }
    if ($followUp !== '' && !ar_followup_within_cap($followUp)) { flash('error', 'Next follow-up cannot be more than ' . AR_MAX_FOLLOWUP_DAYS . ' days from today.'); redirect($backV); }
    if (ar_save_visit_work($pdo, $vid, $uid, $claimStatus, $actionTaken, $followUp ?: null, $notes)) {
        $b = ar_visit_bucket_for_action($actionTaken);
        flash('success', 'Visit worked.' . ($b === 'sent_to_coding' ? ' Routed to Coding for supervisor verification.' : ($b === 'escalated_to_client' ? ' Routed to Client escalation.' : '')));
        // Two ways to leave: "Save & back to queue" exits now; "Save & next visit" (default) flows on.
        if ((string) input('after') === 'queue') redirect('/admin/ar-queue.php');
        // Stay in the patient: open the NEXT unworked visit of THIS account. Only when the account is finished do
        // we fall through to GetNext account (then the queue).
        $nextV = ar_next_unworked_visit($pdo, $uid, $pid, $chart, $vKey);
        if ($nextV !== null) redirect($visitUrl($nextV));
        $nx = ar_next_account($pdo, $uid);
        if ($nx) { flash('info', 'Account complete — loaded your next account.');
            redirect('/admin/ar-work.php?process=' . (int) $nx['process_id'] . '&account=' . rawurlencode((string) $nx['chart_number'])); }
        flash('info', 'All caught up — your queue is clear. 🎉');
        redirect('/admin/ar-queue.php');
    }
    flash('error', 'That visit is not allocated to you, or it has been audited and is locked.');
    redirect($backV);
}

/* ---- POST: bulk-apply one disposition to several selected visits at once ---- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'save_visits_bulk') {
    csrf_check_or_die();
    if (!can('ar.work')) { http_response_code(403); exit('Forbidden'); }
    $ids         = array_map('intval', (array) ($_POST['visit_work_ids'] ?? []));
    $claimStatus = trim((string) input('claim_status'));
    $actionTaken = trim((string) input('action_taken'));
    $followUp    = trim((string) input('next_follow_up_date'));
    $notes       = trim((string) input('notes'));
    $validS = ar_dropdowns($pdo, 'claim_status'); $validA = ar_dropdowns($pdo, 'action_taken');
    if (!array_filter($ids, fn($i) => $i > 0))                  { flash('error', 'Select at least one visit to apply to.'); redirect($acctUrl); }
    if ($claimStatus === '' || $actionTaken === '')            { flash('error', 'Pick a claim status and an action taken.'); redirect($acctUrl); }
    if (!in_array($claimStatus, $validS, true))                { flash('error', 'Pick a valid claim status from the list.'); redirect($acctUrl); }
    if (!in_array($actionTaken, $validA, true))                { flash('error', 'Pick a valid action taken from the list.'); redirect($acctUrl); }
    if ($followUp === '' && ar_action_requires_followup($actionTaken)) { flash('error', 'A next follow-up date is required for this action.'); redirect($acctUrl); }
    if ($followUp !== '' && !ar_followup_within_cap($followUp)) { flash('error', 'Next follow-up cannot be more than ' . AR_MAX_FOLLOWUP_DAYS . ' days from today.'); redirect($acctUrl); }
    // PHI / ownership fence: only act on STILL-PENDING visits the worker owns on THIS account (ar_save_visit_work
    // re-checks each row too — this just gives a clean message and avoids touching other accounts' rows).
    $ownedPending = [];
    foreach (ar_account_work_visits($pdo, $uid, $pid, $chart) as $v)
        if (($v['inventory_status'] ?? '') !== 'worked') $ownedPending[(int) $v['id']] = true;
    $apply = array_values(array_filter($ids, fn($i) => isset($ownedPending[$i])));
    if (!$apply) { flash('error', 'None of the selected visits are open and allocated to you.'); redirect($acctUrl); }
    $res = ar_save_visits_bulk($pdo, $apply, $uid, $claimStatus, $actionTaken, $followUp ?: null, $notes);
    if ($res['ok']) {
        $b = ar_visit_bucket_for_action($actionTaken);
        $route = $b === 'sent_to_coding' ? ' Routed to Coding for supervisor verification.' : ($b === 'escalated_to_client' ? ' Routed to Client escalation.' : '');
        flash('success', $res['ok'] . ' visit' . ($res['ok'] === 1 ? '' : 's') . ' worked.' . ($res['skipped'] ? ' ' . $res['skipped'] . ' skipped (already worked or locked).' : '') . $route);
    } else {
        flash('error', 'Nothing was saved — the selected visits are already worked or locked.');
    }
    redirect($acctUrl);   // stay on the account; the To-work tab refreshes to show what's left
}

/* ---- GetNext: jump to the next account that still has unworked visits ---- */
if (($_GET['next'] ?? '') === '1') {
    $nx = ar_next_account($pdo, $uid);
    if ($nx) redirect('/admin/ar-work.php?process=' . (int) $nx['process_id'] . '&account=' . rawurlencode((string) $nx['chart_number']));
    flash('info', 'Nothing left to work — your queue is clear. 🎉');
    redirect('/admin/ar-queue.php');
}

/* ---- view data (PHI fence: demographics only for an account the worker OWNS a visit on, in the AR vertical) ---- */
$demo = null; $visits = []; $snapName = ''; $snapProvider = '';
if ($pid && $chart !== '' && ar_process_in_ar_vertical($pdo, $pid)) {
    $visits = ar_account_work_visits($pdo, $uid, $pid, $chart);
    if ($visits) $demo = ar_account_demographics($pdo, $pid, $chart);
    // Name/provider snapshotted at allocation time — the fallback when collection_raw no longer holds this account
    // (it's replaced on every collection upload, so the live demographics lookup can come back empty).
    $sq = $pdo->prepare("SELECT patient_name, provider_name FROM ar_allocation WHERE process_id=? AND chart_number=? LIMIT 1");
    $sq->execute([$pid, $chart]); $sn = $sq->fetch() ?: [];
    $snapName = trim((string) ($sn['patient_name'] ?? '')); $snapProvider = trim((string) ($sn['provider_name'] ?? ''));
}
$pending     = count(array_filter($visits, fn($v) => ($v['inventory_status'] ?? '') !== 'worked'));
/* Card carrier/provider derived from THIS worker's visits (same source as the table) so the header never
 * disagrees with the rows — the account-level demographics aggregate over ALL collection_raw and can differ. */
$visCarriers  = array_values(array_unique(array_filter(array_map(fn($v) => (string) ($v['live_carrier'] ?? ''), $visits), fn($s) => $s !== '')));
$visProviders = array_values(array_unique(array_filter(array_map(fn($v) => (string) ($v['live_provider'] ?? ''), $visits), fn($s) => $s !== '')));
$cardCarrier  = count($visCarriers) === 1 ? $visCarriers[0] : (count($visCarriers) > 1 ? count($visCarriers) . ' carriers (see table)' : '—');
$cardProvider = count($visProviders) === 1 ? $visProviders[0] : (count($visProviders) > 1 ? count($visProviders) . ' providers (see table)' : (($demo['provider'] ?? '') ?: $snapProvider ?: '—'));
$bucketBadge = ['sent_to_coding' => ['Sent to coding', 'purple'], 'escalated_to_client' => ['Escalated to client', 'orange']];

/* the open visit (Level 2) must be one the worker owns */
$visit = null;
if ($selVisit !== '') foreach ($visits as $v) if ((string) $v['visit_id'] === $selVisit) { $visit = $v; break; }
/* the next UNWORKED visit of THIS account — powers the in-account "Next visit" flow on the detail view */
$nextVisitId = $visit ? ar_next_unworked_visit($pdo, $uid, $pid, $chart, $selVisit) : null;

$pageTitle = 'AR work';
require __DIR__ . '/../includes/header.php';
?>
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/tom-select@2.3.1/dist/css/tom-select.bootstrap5.min.css">
<script src="https://cdn.jsdelivr.net/npm/tom-select@2.3.1/dist/js/tom-select.complete.min.js"></script>

<div class="page-header"><div class="container-xl"><div class="row align-items-center">
    <div class="col"><h2 class="page-title"><i class="ti ti-user-dollar me-2 text-primary"></i>AR — work account</h2>
        <div class="text-secondary small">Open a <strong>visit</strong> to see its full detail &amp; history, then tag it. Each visit settles on its own — the account isn't held for the others.</div></div>
    <div class="col-auto d-flex gap-2">
        <a href="<?= e(url('/admin/ar-queue.php')) ?>" class="btn btn-outline-secondary"><i class="ti ti-list me-1"></i>My queue</a>
        <?php if ($visit && $nextVisitId !== null): /* inside a patient with more visits → advance within the account first */ ?>
            <a href="<?= e(url($visitUrl($nextVisitId))) ?>" class="btn btn-primary"><i class="ti ti-player-track-next me-1"></i>Next visit</a>
            <a href="<?= e(url('/admin/ar-work.php?next=1')) ?>" class="btn btn-outline-primary"><i class="ti ti-user-plus me-1"></i>Next account</a>
        <?php else: ?>
            <a href="<?= e(url('/admin/ar-work.php?next=1')) ?>" class="btn btn-primary"><i class="ti ti-player-track-next me-1"></i>Get next account</a>
        <?php endif; ?>
    </div>
</div></div></div>

<div class="page-body"><div class="container-xl">

<?php if (!$pid || $chart === '' || !$demo): ?>
    <div class="card"><div class="card-body text-center text-secondary py-5">
        <i class="ti ti-folder-open" style="font-size:2.2rem"></i>
        <div class="mt-2">No account open. Click <strong>Get next account</strong>, or pick one from <a href="<?= e(url('/admin/ar-queue.php')) ?>">My queue</a>.</div>
    </div></div>
<?php else: ?>

    <!-- ============================== PATIENT DEMOGRAPHICS (shown on both levels) ============================== -->
    <div class="card mb-3"><div class="card-body d-flex flex-wrap gap-4 align-items-center">
        <div><div class="h3 mb-0"><?= e(trim(($demo['first_name'] ?? '') . ' ' . ($demo['last_name'] ?? '')) ?: $snapName ?: '—') ?></div>
            <div class="text-secondary small">Patient Account # <span class="font-mono"><?= e($chart) ?></span></div></div>
        <div><div class="text-secondary small">Carrier <span class="text-secondary">(my visits)</span></div><?= e($cardCarrier) ?></div>
        <div><div class="text-secondary small">Financial class</div><?= e($demo['financial_class'] ?? '—') ?></div>
        <div><div class="text-secondary small">Provider <span class="text-secondary">(my visits)</span></div><?= e($cardProvider) ?></div>
        <div><div class="text-secondary small">DOS range</div><?= e(fmt_date($demo['min_dos'])) ?> – <?= e(fmt_date($demo['max_dos'])) ?></div>
        <div><div class="text-secondary small">Insurance balance</div><strong><?= number_format((float)($demo['ins_bal'] ?? 0), 2) ?></strong></div>
        <div><div class="text-secondary small">Visits (mine)</div><span class="badge bg-blue-lt"><?= count($visits) ?></span> <span class="text-secondary small"><?= $pending ?> pending</span></div>
    </div></div>

    <?php if ($visit): /* ===================================== LEVEL 2: VISIT DETAIL ===================================== */
        $detail  = ar_visit_detail($pdo, $pid, $chart, (string) $visit['visit_id']);
        $history = ar_visit_work_history($pdo, $pid, $chart, (string) $visit['visit_id']);
        $worked  = ($visit['inventory_status'] ?? '') === 'worked';
        $auditChk = $pdo->prepare("SELECT 1 FROM ar_visit_audit WHERE visit_work_id=?"); $auditChk->execute([(int) $visit['id']]);
        $audited  = (bool) $auditChk->fetchColumn();
        $bk = $visit['bucket'] ?? '';
        $claimOpts  = ar_dropdowns($pdo, 'claim_status');
        $actionOpts = ar_dropdowns($pdo, 'action_taken');
        $maxFollow  = date('Y-m-d', strtotime('+' . AR_MAX_FOLLOWUP_DAYS . ' days'));
    ?>
        <div class="d-flex align-items-center mb-3">
            <a href="<?= e(url($acctUrl)) ?>" class="btn btn-outline-secondary btn-sm"><i class="ti ti-arrow-left me-1"></i>All visits</a>
            <h3 class="ms-3 mb-0">Visit <span class="font-mono"><?= e($visit['visit_id']) ?></span></h3>
            <span class="ms-2">
                <?php if ($worked): ?><span class="badge bg-green-lt"><i class="ti ti-check me-1"></i>worked</span>
                    <?php if ($bk && isset($bucketBadge[$bk])): ?> <span class="badge bg-<?= $bucketBadge[$bk][1] ?>-lt"><?= e($bucketBadge[$bk][0]) ?></span><?php endif; ?>
                <?php else: ?><span class="badge bg-yellow-lt">pending</span><?php endif; ?>
                <?php if ($audited): ?> <span class="badge bg-azure-lt"><i class="ti ti-lock me-1"></i>audited</span><?php endif; ?>
            </span>
        </div>

        <div class="row">
            <div class="col-lg-8">
                <!-- visit / provider / carrier info -->
                <div class="card mb-3"><div class="card-body d-flex flex-wrap gap-4">
                    <div><div class="text-secondary small">DOS</div><?= e(fmt_date($detail['dos'] ?? $visit['dos'])) ?></div>
                    <div><div class="text-secondary small">Provider</div><?= e(($detail['provider'] ?? '') ?: ($demo['provider'] ?? '') ?: $snapProvider ?: '—') ?></div>
                    <div><div class="text-secondary small">Financial class</div><?= e($detail['financial_class'] ?? '—') ?></div>
                    <div><div class="text-secondary small">Primary carrier</div><?= e($detail['carrier1'] ?? '—') ?></div>
                    <?php if (!empty($detail['carrier2'])): ?><div><div class="text-secondary small">Secondary</div><?= e($detail['carrier2']) ?></div><?php endif; ?>
                    <?php if (!empty($detail['carrier3'])): ?><div><div class="text-secondary small">Tertiary</div><?= e($detail['carrier3']) ?></div><?php endif; ?>
                </div></div>

                <!-- CPT charge lines -->
                <div class="card mb-3"><div class="card-header py-2"><h3 class="card-title small"><i class="ti ti-receipt me-1"></i>CPT charges</h3>
                    <div class="card-actions text-secondary small">Ins. balance <strong><?= number_format((float)$detail['ins_bal'], 2) ?></strong> · Pat. balance <?= number_format((float)$detail['pat_bal'], 2) ?></div></div>
                    <div class="table-responsive"><table class="table table-vcenter card-table table-sm">
                        <thead><tr><th>CPT</th><th class="text-end">Units</th><th class="text-end">Charge</th>
                            <th class="text-end">Pri</th><th class="text-end">Sec</th><th class="text-end">Ter</th>
                            <th class="text-end">Write-off</th><th class="text-end">Ins. paid</th><th class="text-end">Ins. bal</th><th class="text-end">Pat. bal</th></tr></thead>
                        <tbody>
                        <?php if (!$detail['lines']): ?><tr><td colspan="10" class="text-center text-secondary py-3">No charge lines for this visit in the current inventory.</td></tr>
                        <?php else: foreach ($detail['lines'] as $l):
                            $insPaid = (float)($l['primary_ins_paid'] ?? 0) + (float)($l['secondary_ins_paid'] ?? 0) + (float)($l['tertiary_ins_paid'] ?? 0); ?>
                            <tr>
                                <td class="font-mono"><?= e($l['charge_code'] ?? '—') ?><?php if (!empty($l['charge_code_desc'])): ?> <i class="ti ti-info-circle text-secondary" title="<?= e($l['charge_code_desc']) ?>"></i><?php endif; ?></td>
                                <td class="text-end small"><?= e(rtrim(rtrim(number_format((float)($l['units'] ?? 0), 2), '0'), '.')) ?: '—' ?></td>
                                <td class="text-end font-mono"><?= number_format((float)($l['charge_amount'] ?? 0), 2) ?></td>
                                <td class="text-end font-mono small"><?= number_format((float)($l['primary_ins_paid'] ?? 0), 2) ?></td>
                                <td class="text-end font-mono small"><?= number_format((float)($l['secondary_ins_paid'] ?? 0), 2) ?></td>
                                <td class="text-end font-mono small"><?= number_format((float)($l['tertiary_ins_paid'] ?? 0), 2) ?></td>
                                <td class="text-end font-mono small"><?= number_format((float)($l['wo_amount'] ?? 0), 2) ?></td>
                                <td class="text-end font-mono"><?= number_format($insPaid, 2) ?></td>
                                <td class="text-end font-mono fw-medium <?= (float)($l['insurance_balance'] ?? 0) < 0 ? 'text-danger' : '' ?>"><?= number_format((float)($l['insurance_balance'] ?? 0), 2) ?></td>
                                <td class="text-end font-mono small"><?= number_format((float)($l['patient_balance'] ?? 0), 2) ?></td>
                            </tr>
                        <?php endforeach; endif; ?>
                        </tbody>
                        <?php if ($detail['lines']): ?><tfoot><tr class="fw-bold">
                            <td colspan="2">Total</td>
                            <td class="text-end font-mono"><?= number_format((float)$detail['charges'], 2) ?></td>
                            <td class="text-end font-mono small"><?= number_format((float)$detail['ppaid'], 2) ?></td>
                            <td class="text-end font-mono small"><?= number_format((float)$detail['spaid'], 2) ?></td>
                            <td class="text-end font-mono small"><?= number_format((float)$detail['tpaid'], 2) ?></td>
                            <td class="text-end font-mono small"><?= number_format((float)$detail['wo'], 2) ?></td>
                            <td class="text-end font-mono"><?= number_format((float)$detail['paid'], 2) ?></td>
                            <td class="text-end font-mono"><?= number_format((float)$detail['ins_bal'], 2) ?></td>
                            <td class="text-end font-mono small"><?= number_format((float)$detail['pat_bal'], 2) ?></td>
                        </tr></tfoot><?php endif; ?>
                    </table></div>
                </div>

                <!-- worked history -->
                <div class="card mb-3"><div class="card-header py-2"><h3 class="card-title small"><i class="ti ti-history me-1"></i>Worked history</h3>
                    <div class="card-actions"><span class="badge bg-secondary-lt"><?= count($history) ?></span></div></div>
                    <div class="table-responsive"><table class="table table-vcenter card-table table-sm">
                        <thead><tr><th>When</th><th>Worked by</th><th>Claim status</th><th>Action taken</th><th>Next follow-up</th><th>Notes</th></tr></thead>
                        <tbody>
                        <?php if (!$history): ?><tr><td colspan="6" class="text-center text-secondary py-3">No prior work on this visit yet — you'll be the first.</td></tr>
                        <?php else: foreach ($history as $h): ?>
                            <tr>
                                <td class="small text-nowrap"><?= e(fmt_date($h['created_at'])) ?> <span class="text-secondary"><?= e(date('H:i', strtotime($h['created_at']))) ?></span></td>
                                <td class="small"><?= e($h['worker_name'] ?? '—') ?></td>
                                <td class="small"><?= e($h['claim_status'] ?? '—') ?></td>
                                <td class="small"><?= e($h['action_taken'] ?? '—') ?></td>
                                <td class="small text-nowrap"><?= e(fmt_date($h['next_follow_up_date'])) ?></td>
                                <td class="small text-secondary"><?= e($h['notes'] ?? '') ?: '—' ?></td>
                            </tr>
                        <?php endforeach; endif; ?>
                        </tbody>
                    </table></div>
                </div>
            </div>

            <!-- tag form (sticky side) -->
            <div class="col-lg-4">
                <div class="card"><div class="card-header py-2"><h3 class="card-title small"><i class="ti ti-tag me-1"></i>Tag this visit</h3></div>
                    <div class="card-body">
                        <?php if ($audited): ?>
                            <div class="alert alert-azure py-2 small mb-0"><i class="ti ti-lock me-1"></i>This visit has been audited and is locked. To dispute the audit, use <a href="<?= e(url('/admin/ar-rebuttals.php')) ?>">My audit rebuttals</a>.</div>
                        <?php elseif ($worked): /* worked = READ-ONLY; reopens only via supervisor rework */ ?>
                            <div class="alert alert-green py-2 small"><i class="ti ti-check me-1"></i>This visit has been <strong>worked</strong> — read-only. It reopens automatically when its follow-up date arrives (supervisor rework).</div>
                            <div class="mb-2"><div class="text-secondary small">Claim status</div><div class="fw-medium"><?= e($visit['claim_status'] ?? '—') ?></div></div>
                            <div class="mb-2"><div class="text-secondary small">Action taken</div><div class="fw-medium"><?= e($visit['action_taken'] ?? '—') ?>
                                <?php if ($bk && isset($bucketBadge[$bk])): ?> <span class="badge bg-<?= $bucketBadge[$bk][1] ?>-lt"><?= e($bucketBadge[$bk][0]) ?></span><?php endif; ?></div></div>
                            <div class="mb-2"><div class="text-secondary small">Next follow-up</div><div class="fw-medium"><?= e(fmt_date($visit['next_follow_up_date'])) ?: '—' ?></div></div>
                            <div class="mb-2"><div class="text-secondary small">Notes</div><div class="small"><?= e($visit['notes'] ?? '') ?: '—' ?></div></div>
                            <a href="<?= e(url($nextVisitId !== null ? $visitUrl($nextVisitId) : '/admin/ar-work.php?next=1')) ?>" class="btn btn-primary w-100"><i class="ti ti-player-track-next me-1"></i><?= $nextVisitId !== null ? 'Next visit' : 'Get next account' ?></a>
                        <?php else: ?>
                        <form method="POST" action="<?= e(url('/admin/ar-work.php')) ?>">
                            <?= csrf_field() ?>
                            <input type="hidden" name="action" value="save_visit">
                            <input type="hidden" name="process" value="<?= $pid ?>"><input type="hidden" name="account" value="<?= e($chart) ?>">
                            <input type="hidden" name="visit_work_id" value="<?= (int)$visit['id'] ?>"><input type="hidden" name="visit_id" value="<?= e($visit['visit_id']) ?>">
                            <label class="form-label required mb-1 small">Claim status</label>
                            <select name="claim_status" class="form-select form-select-sm ar-search mb-2" required>
                                <option value="">— claim status —</option>
                                <?php foreach ($claimOpts as $o): ?><option <?= ($visit['claim_status'] ?? '')===$o?'selected':'' ?>><?= e($o) ?></option><?php endforeach; ?>
                            </select>
                            <label class="form-label required mb-1 small">Action taken</label>
                            <select name="action_taken" id="ar_action" class="form-select form-select-sm ar-search mb-2" required>
                                <option value="">— action taken —</option>
                                <?php foreach ($actionOpts as $o): ?><option <?= ($visit['action_taken'] ?? '')===$o?'selected':'' ?>><?= e($o) ?></option><?php endforeach; ?>
                            </select>
                            <label class="form-label mb-1 small" id="ar_fu_label">Next follow-up <span class="text-secondary">(≤<?= AR_MAX_FOLLOWUP_DAYS ?>d)</span></label>
                            <input type="date" name="next_follow_up_date" id="ar_fu" class="form-control form-control-sm mb-2" max="<?= $maxFollow ?>" value="<?= e($visit['next_follow_up_date'] ?? '') ?>">
                            <script>
                            (function(){
                                var NOFU = <?= json_encode(array_values(AR_NO_FOLLOWUP_ACTIONS)) ?>;   // actions where follow-up is NOT required
                                var act=document.getElementById('ar_action'), fu=document.getElementById('ar_fu'), lbl=document.getElementById('ar_fu_label');
                                function sync(){ var v=(act.value||'').trim().toUpperCase(); var req=v!=='' && NOFU.indexOf(v)===-1;
                                    fu.required=req; lbl.classList.toggle('required', req);
                                    lbl.querySelector('.opt')&&lbl.querySelector('.opt').remove();
                                    if(!req && v!==''){ var s=document.createElement('span'); s.className='opt text-secondary'; s.textContent=' (optional)'; lbl.appendChild(s); }
                                }
                                act.addEventListener('change', sync); sync();
                            })();
                            </script>
                            <label class="form-label mb-1 small">Notes</label>
                            <textarea name="notes" class="form-control form-control-sm mb-2" rows="3" placeholder="optional"><?= e($visit['notes'] ?? '') ?></textarea>
                            <button class="btn btn-primary w-100" name="after" value="next"><i class="ti ti-player-track-next me-1"></i>Save &amp; next visit</button>
                            <button class="btn btn-outline-secondary w-100 mt-2" name="after" value="queue"><i class="ti ti-logout me-1"></i>Save &amp; back to queue</button>
                            <div class="text-secondary small mt-1">'SENT TO CODING' / 'ESCALATED TO CLIENT' route the visit for supervisor verification. <strong>Save &amp; next visit</strong> opens this patient's next visit; once the patient is done it loads your next account.</div>
                        </form>
                        <?php endif; ?>
                    </div>
                </div>
            </div>
        </div>

    <?php else: /* ===================================== LEVEL 1: VISIT LIST ===================================== */
        $showWorked    = (($_GET['show'] ?? '') === 'worked');
        $pendingVisits = array_values(array_filter($visits, fn($v) => ($v['inventory_status'] ?? '') !== 'worked'));
        $workedVisits  = array_values(array_filter($visits, fn($v) => ($v['inventory_status'] ?? '') === 'worked'));
        $listVisits = $showWorked ? $workedVisits : $pendingVisits;   // default = still-to-work; worked moved to its own tab
        $num = fn($x) => $x !== null ? number_format((float)$x, 2) : '—';
        $tot = ['charge'=>0,'allowed'=>0,'ppaid'=>0,'spaid'=>0,'tpaid'=>0,'wo'=>0,'ins'=>0,'pat'=>0];
        foreach ($listVisits as $v) { $tot['charge']+=(float)$v['charge']; $tot['allowed']+=(float)$v['allowed']; $tot['ppaid']+=(float)$v['ppaid'];
            $tot['spaid']+=(float)$v['spaid']; $tot['tpaid']+=(float)$v['tpaid']; $tot['wo']+=(float)$v['wo']; $tot['ins']+=(float)$v['live_ins_bal']; $tot['pat']+=(float)$v['live_pat_bal']; }
        $cbCol      = !$showWorked && (bool) $listVisits;             // checkbox + bulk-apply only on a non-empty still-to-work list
        $claimOpts  = ar_dropdowns($pdo, 'claim_status');
        $actionOpts = ar_dropdowns($pdo, 'action_taken');
        $maxFollow  = date('Y-m-d', strtotime('+' . AR_MAX_FOLLOWUP_DAYS . ' days'));
        $colCount   = $cbCol ? 16 : 15;
    ?>
        <ul class="nav nav-tabs mb-2">
            <li class="nav-item"><a class="nav-link <?= !$showWorked?'active':'' ?>" href="<?= e(url($acctUrl)) ?>"><i class="ti ti-clock me-1"></i>To work <span class="badge bg-yellow-lt ms-1"><?= count($pendingVisits) ?></span></a></li>
            <li class="nav-item"><a class="nav-link <?= $showWorked?'active':'' ?>" href="<?= e(url($acctUrl . '&show=worked')) ?>"><i class="ti ti-check me-1"></i>Worked <span class="badge bg-green-lt ms-1"><?= count($workedVisits) ?></span></a></li>
        </ul>

        <?php if ($cbCol): ?>
        <form method="POST" id="ar-bulk-form" action="<?= e(url('/admin/ar-work.php')) ?>">
        <!-- Bulk-apply bar: shows once ≥1 visit is ticked; one disposition applied to every selected visit. -->
        <div id="ar-bulk-bar" class="card mb-2 border-primary" style="display:none">
            <div class="card-body py-2">
                <input type="hidden" name="action" value="save_visits_bulk">
                <input type="hidden" name="process" value="<?= $pid ?>">
                <input type="hidden" name="account" value="<?= e($chart) ?>">
                <?= csrf_field() ?>
                <div class="row g-2 align-items-end">
                    <div class="col-12"><span class="badge bg-primary"><span id="ar-bulk-count">0</span> selected</span>
                        <span class="text-secondary small ms-1">Apply the same disposition to every selected visit in one go.</span></div>
                    <div class="col-sm-6 col-lg-3">
                        <label class="form-label required mb-1 small">Claim status</label>
                        <select name="claim_status" class="form-select form-select-sm ar-search" required>
                            <option value="">— claim status —</option>
                            <?php foreach ($claimOpts as $o): ?><option><?= e($o) ?></option><?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-sm-6 col-lg-3">
                        <label class="form-label required mb-1 small">Action taken</label>
                        <select name="action_taken" id="ar_bulk_action" class="form-select form-select-sm ar-search" required>
                            <option value="">— action taken —</option>
                            <?php foreach ($actionOpts as $o): ?><option><?= e($o) ?></option><?php endforeach; ?>
                        </select>
                    </div>
                    <div class="col-sm-6 col-lg-2">
                        <label class="form-label mb-1 small" id="ar_bulk_fu_label">Next follow-up <span class="text-secondary">(≤<?= AR_MAX_FOLLOWUP_DAYS ?>d)</span></label>
                        <input type="date" name="next_follow_up_date" id="ar_bulk_fu" class="form-control form-control-sm" max="<?= $maxFollow ?>">
                    </div>
                    <div class="col-sm-6 col-lg-2">
                        <label class="form-label mb-1 small">Notes</label>
                        <input type="text" name="notes" class="form-control form-control-sm" placeholder="optional">
                    </div>
                    <div class="col-lg-2">
                        <button class="btn btn-primary btn-sm w-100" type="submit"><i class="ti ti-checks me-1"></i>Apply to <span class="ar-bulk-count2">0</span></button>
                    </div>
                </div>
            </div>
        </div>
        <?php endif; ?>

        <div class="card">
            <div class="card-header py-2"><h3 class="card-title"><i class="ti ti-list-details me-2"></i><?= $showWorked ? 'Worked visits (read-only)' : 'Visits to work' ?></h3>
                <div class="card-actions text-secondary small"><?= $cbCol ? 'Tick visits to bulk-tag them in one go, or click a row to open one. ' : '' ?>A visit may have more than one CPT — figures are summed across its CPTs.</div></div>
            <div class="table-responsive"><table class="table table-vcenter card-table table-hover table-sm">
                <thead><tr>
                    <?php if ($cbCol): ?><th class="w-1"><input type="checkbox" id="ar-check-all" class="form-check-input m-0" title="Select all"></th><?php endif; ?>
                    <th>Visit ID</th><th>DOS</th><th>Provider</th><th>Carrier</th><th>CPT(s)</th>
                    <th class="text-end">Charge</th><th class="text-end">Allowed</th><th class="text-end">Pri paid</th><th class="text-end">Sec paid</th><th class="text-end">Ter paid</th>
                    <th class="text-end">Write-off</th><th class="text-end">Ins. bal</th><th class="text-end">Pat. bal</th><th>Status</th><th class="w-1"></th>
                </tr></thead>
                <tbody>
                <?php if (!$listVisits): ?>
                    <tr><td colspan="<?= $colCount ?>" class="text-center text-secondary py-4"><?= $showWorked ? 'No worked visits yet.' : 'All visits worked — nothing left to do here. 🎉' ?></td></tr>
                <?php else: foreach ($listVisits as $v): $w = ($v['inventory_status'] ?? '') === 'worked'; $bk = $v['bucket'] ?? ''; ?>
                    <tr style="cursor:pointer" onclick="location.href='<?= e(url($visitUrl((string)$v['visit_id']))) ?>'">
                        <?php if ($cbCol): ?><td onclick="event.stopPropagation()"><input type="checkbox" class="form-check-input m-0 ar-row-check" name="visit_work_ids[]" value="<?= (int)$v['id'] ?>"></td><?php endif; ?>
                        <td class="font-mono fw-bold"><?= e($v['visit_id']) ?></td>
                        <td class="small text-nowrap"><?= e(fmt_date($v['dos'])) ?></td>
                        <td class="small"><?= e($v['live_provider'] ?? '—') ?></td>
                        <td class="small"><?= e($v['live_carrier'] ?? '—') ?></td>
                        <td class="small font-mono"><?= e($v['cpts'] ?: '—') ?></td>
                        <td class="text-end font-mono small"><?= $num($v['charge']) ?></td>
                        <td class="text-end font-mono small"><?= $num($v['allowed']) ?></td>
                        <td class="text-end font-mono small"><?= $num($v['ppaid']) ?></td>
                        <td class="text-end font-mono small"><?= $num($v['spaid']) ?></td>
                        <td class="text-end font-mono small"><?= $num($v['tpaid']) ?></td>
                        <td class="text-end font-mono small"><?= $num($v['wo']) ?></td>
                        <td class="text-end font-mono fw-medium <?= (float)$v['live_ins_bal']<0?'text-danger':'' ?>"><?= $num($v['live_ins_bal']) ?></td>
                        <td class="text-end font-mono small"><?= $num($v['live_pat_bal']) ?></td>
                        <td><?php if ($w): ?><span class="badge bg-green-lt">worked</span><?php if ($bk && isset($bucketBadge[$bk])): ?> <span class="badge bg-<?= $bucketBadge[$bk][1] ?>-lt"><?= e($bucketBadge[$bk][0]) ?></span><?php endif; ?><?php else: ?><span class="badge bg-yellow-lt">pending</span><?php endif; ?></td>
                        <td><a href="<?= e(url($visitUrl((string)$v['visit_id']))) ?>" class="btn btn-sm btn-<?= $w?'outline-secondary':'primary' ?>"><i class="ti ti-folder-open me-1"></i><?= $w ? 'View' : 'Work' ?></a></td>
                    </tr>
                <?php endforeach; endif; ?>
                </tbody>
                <?php if ($listVisits): ?>
                <tfoot><tr class="fw-bold"><td colspan="<?= $cbCol ? 6 : 5 ?>">Total (<?= count($listVisits) ?> visit<?= count($listVisits)==1?'':'s' ?>)</td>
                    <td class="text-end font-mono small"><?= number_format($tot['charge'],2) ?></td>
                    <td class="text-end font-mono small"><?= number_format($tot['allowed'],2) ?></td>
                    <td class="text-end font-mono small"><?= number_format($tot['ppaid'],2) ?></td>
                    <td class="text-end font-mono small"><?= number_format($tot['spaid'],2) ?></td>
                    <td class="text-end font-mono small"><?= number_format($tot['tpaid'],2) ?></td>
                    <td class="text-end font-mono small"><?= number_format($tot['wo'],2) ?></td>
                    <td class="text-end font-mono"><?= number_format($tot['ins'],2) ?></td>
                    <td class="text-end font-mono small"><?= number_format($tot['pat'],2) ?></td>
                    <td colspan="2"></td></tr></tfoot>
                <?php endif; ?>
            </table></div>
        </div>
        <?php if ($cbCol): ?>
        </form>
        <script>
        (function(){
            var bar = document.getElementById('ar-bulk-bar'); if (!bar) return;
            var all = document.getElementById('ar-check-all');
            var boxes = Array.prototype.slice.call(document.querySelectorAll('.ar-row-check'));
            var counts = [document.getElementById('ar-bulk-count')].concat(Array.prototype.slice.call(document.querySelectorAll('.ar-bulk-count2')));
            function picked(){ return boxes.filter(function(b){ return b.checked; }); }
            function refresh(){
                var n = picked().length;
                counts.forEach(function(el){ if (el) el.textContent = n; });
                bar.style.display = n > 0 ? '' : 'none';
                if (all){ all.checked = n > 0 && n === boxes.length; all.indeterminate = n > 0 && n < boxes.length; }
            }
            boxes.forEach(function(b){ b.addEventListener('change', refresh); });
            if (all) all.addEventListener('change', function(){ boxes.forEach(function(b){ b.checked = all.checked; }); refresh(); });

            // Follow-up required unless the action is a no-follow-up action (mirror the single-visit form).
            var NOFU = <?= json_encode(array_values(AR_NO_FOLLOWUP_ACTIONS)) ?>;
            var act = document.getElementById('ar_bulk_action'), fu = document.getElementById('ar_bulk_fu'), lbl = document.getElementById('ar_bulk_fu_label');
            function sync(){ if (!act) return; var v = (act.value || '').trim().toUpperCase(); var req = v !== '' && NOFU.indexOf(v) === -1; if (fu) fu.required = req; if (lbl) lbl.classList.toggle('required', req); }
            if (act) act.addEventListener('change', sync); sync();

            var form = document.getElementById('ar-bulk-form');
            if (form) form.addEventListener('submit', function(e){
                var n = picked().length;
                if (n === 0){ e.preventDefault(); return; }
                if (!confirm('Apply this disposition to ' + n + ' selected visit' + (n === 1 ? '' : 's') + '?')) e.preventDefault();
            });
            refresh();
        })();
        </script>
        <?php endif; ?>
        <div class="mt-3"><a href="<?= e(url('/admin/ar-work.php?next=1')) ?>" class="btn btn-primary"><i class="ti ti-player-track-next me-1"></i><?= $pending ? 'Skip — get next account' : 'Done — get next account' ?></a></div>
    <?php endif; ?>

<?php endif; ?>

</div></div>
<script>
(function(){ if (typeof TomSelect === 'undefined') return;
    document.querySelectorAll('.ar-search').forEach(function(el){ if (el.tomselect) return;
        new TomSelect(el, { maxOptions: 2000, persist: false, placeholder: el.options[0] ? el.options[0].text : 'Search…' }); });
})();
</script>
<?php require __DIR__ . '/../includes/footer.php'; ?>
