<?php
/**
 * AR / Collections — supervisor/manager VERIFY & ROUTE (ar.supervise). The AR worker tags each visit; when an
 * action routes it (action_taken 'SENT TO CODING' / 'ESCALATED TO CLIENT') the visit lands in a bucket here.
 * The supervisor reviews the visit-id accounts and confirms the hand-off (Sent to coding / Escalated to client).
 * Team-scoped: a supervisor sees their team's visits, a manager their supervisors' teams (reports_to tree).
 * No "send to billing" — AR never hands a visit to billing.
 */
require_once __DIR__ . '/../includes/config.php';
$user = require_login('internal');
$pdo  = db();
$uid  = (int) $user['id'];

// [bucketCol, label, color, icon, confirm-verb]
$BUCKETS = [
    'coding'  => ['sent_to_coding',       'Sent to coding',           'purple', 'code',          'Confirm sent'],
    'client'  => ['escalated_to_client',  'Escalated to client',      'orange', 'building-bank', 'Confirm sent'],
    'patient' => ['contact_patient',      'Need to contact patients', 'cyan',   'phone',         'Mark contacted'],
];
$q = isset($_GET['q'], $BUCKETS[$_GET['q']]) ? (string) $_GET['q'] : 'coding';
[$bucketCol] = $BUCKETS[$q];
$showSent = ($_GET['view'] ?? '') === 'sent';

$team    = ar_team_scope($pdo, $uid);                       // null = all (sysadmin)
$teamSql = $team === null ? '' : (' AND v.allocated_user IN (' . implode(',', $team ?: [0]) . ')');

/* ---- filters (apply to the DISPLAYED rows; the tab counts stay unfiltered totals) ---- */
$fProcess = (int) ($_GET['process_id'] ?? 0);
$fCarrier = trim((string) ($_GET['carrier'] ?? ''));
$fWorker  = (int) ($_GET['worker_id'] ?? 0);
if ($fWorker && $team !== null && !in_array($fWorker, $team, true)) $fWorker = 0;   // can't peek outside the team
$fw = ''; $fp = [];
if ($fProcess)        { $fw .= ' AND v.process_id=?';    $fp[] = $fProcess; }
if ($fCarrier !== '') { $fw .= ' AND v.carrier_name=?';  $fp[] = $fCarrier; }
if ($fWorker)         { $fw .= ' AND v.allocated_user=?'; $fp[] = $fWorker; }
$qpV = fn(array $o = []) => http_build_query(array_merge(array_filter(['q'=>$q==='coding'?null:$q, 'view'=>$showSent?'sent':null, 'process_id'=>$fProcess?:null, 'carrier'=>$fCarrier?:null, 'worker_id'=>$fWorker?:null]), $o));

/* ---- POST: confirm hand-off (mark the selected visits sent) ---- */
if ($_SERVER['REQUEST_METHOD'] === 'POST' && ($_POST['action'] ?? '') === 'confirm_sent') {
    csrf_check_or_die();
    if (!can('ar.supervise')) { http_response_code(403); exit('Forbidden'); }
    $ids = array_values(array_filter(array_map('intval', (array) ($_POST['ids'] ?? []))));
    $n = 0;
    if ($ids) {
        $in = implode(',', array_fill(0, count($ids), '?'));
        // only this supervisor's team rows, only still-pending, only this bucket
        $sql = "UPDATE ar_visit_work v SET v.sent_at=NOW(), v.sent_by=? WHERE v.id IN ($in) AND v.bucket=? AND v.sent_at IS NULL" . $teamSql;
        $st = $pdo->prepare($sql); $st->execute(array_merge([$uid], $ids, [$bucketCol]));
        $n = $st->rowCount();
        audit_log('ar.verify.send', 'ar_visit_work', null, null, ['bucket'=>$bucketCol, 'count'=>$n]);
    }
    flash($n ? 'success' : 'warning', $n ? "Confirmed $n visit(s) — {$BUCKETS[$q][1]}." : 'Nothing to confirm.');
    redirect('/admin/ar-verify.php?' . $qpV());
}

/* ---- counts per bucket (pending) ---- */
$cnt = [];
foreach ($BUCKETS as $k => $b) {
    $c = $pdo->prepare("SELECT COUNT(*) FROM ar_visit_work v WHERE v.bucket=? AND v.sent_at IS NULL" . $teamSql);
    $c->execute([$b[0]]); $cnt[$k] = (int) $c->fetchColumn();
}

/* ---- rows for the active bucket/view (filters applied) ---- */
$rows = $pdo->prepare("SELECT v.id, v.process_id, v.chart_number, v.visit_id, v.carrier_name, v.dos,
        v.claim_status, v.action_taken, v.notes, v.next_follow_up_date, v.insurance_balance, v.bucket_at, v.sent_at,
        u.name worker_name
    FROM ar_visit_work v LEFT JOIN users u ON u.id = v.allocated_user
    WHERE v.bucket=? AND v.sent_at IS " . ($showSent ? 'NOT NULL' : 'NULL') . $teamSql . $fw . "
    ORDER BY v.bucket_at DESC, v.chart_number, v.visit_id LIMIT 1000");
$rows->execute(array_merge([$bucketCol], $fp));
$rows = $rows->fetchAll();

/* ---- filter option lists (scoped to the team's routed visits) ---- */
$optProc = $pdo->query("SELECT DISTINCT v.process_id, p.name pname, c.name cname FROM ar_visit_work v
    JOIN processes p ON p.id=v.process_id JOIN clients c ON c.id=p.client_id
    WHERE v.bucket IS NOT NULL" . $teamSql . " ORDER BY c.name, p.name")->fetchAll();
$optCarrier = $pdo->query("SELECT DISTINCT carrier_name FROM ar_visit_work v
    WHERE v.bucket IS NOT NULL AND COALESCE(v.carrier_name,'')<>''" . $teamSql . " ORDER BY carrier_name")->fetchAll(PDO::FETCH_COLUMN);
$optWorker = $pdo->query("SELECT DISTINCT u.id, u.name FROM ar_visit_work v JOIN users u ON u.id=v.allocated_user
    WHERE v.bucket IS NOT NULL" . $teamSql . " ORDER BY u.name")->fetchAll();

$pageTitle = 'AR verify & route';
require __DIR__ . '/../includes/header.php';
?>
<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-route me-2 text-primary"></i>AR — verify &amp; route</h2>
        <div class="text-secondary small">Review the visit-id accounts your team routed and confirm the hand-off. Visits route by the AR worker's <strong>action taken</strong>.</div></div>
</div></div></div>

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

    <!-- filters (all tabs) -->
    <form method="GET" class="card mb-3"><div class="card-body py-2">
        <input type="hidden" name="q" value="<?= e($q) ?>"><?php if ($showSent): ?><input type="hidden" name="view" value="sent"><?php endif; ?>
        <div class="row g-2 align-items-end">
            <div class="col-auto"><label class="form-label small mb-1">Process</label>
                <select name="process_id" class="form-select form-select-sm" onchange="this.form.submit()">
                    <option value="0">All processes</option>
                    <?php foreach ($optProc as $p): ?><option value="<?= (int)$p['process_id'] ?>" <?= $fProcess==(int)$p['process_id']?'selected':'' ?>><?= e($p['cname'].' › '.$p['pname']) ?></option><?php endforeach; ?>
                </select></div>
            <div class="col-auto"><label class="form-label small mb-1">Carrier</label>
                <select name="carrier" class="form-select form-select-sm" onchange="this.form.submit()">
                    <option value="">All carriers</option>
                    <?php foreach ($optCarrier as $cn): ?><option value="<?= e($cn) ?>" <?= $fCarrier===(string)$cn?'selected':'' ?>><?= e($cn) ?></option><?php endforeach; ?>
                </select></div>
            <div class="col-auto"><label class="form-label small mb-1">AR worker</label>
                <select name="worker_id" class="form-select form-select-sm" onchange="this.form.submit()">
                    <option value="0">All team</option>
                    <?php foreach ($optWorker as $wu): ?><option value="<?= (int)$wu['id'] ?>" <?= $fWorker==(int)$wu['id']?'selected':'' ?>><?= e($wu['name']) ?></option><?php endforeach; ?>
                </select></div>
            <?php if ($fProcess || $fCarrier!=='' || $fWorker): ?><div class="col-auto"><a href="<?= e(url('/admin/ar-verify.php?q='.$q.($showSent?'&view=sent':''))) ?>" class="btn btn-sm btn-link text-secondary">Clear</a></div><?php endif; ?>
        </div>
    </div></form>

    <ul class="nav nav-tabs mb-3">
        <?php foreach ($BUCKETS as $k => $b): ?>
            <li class="nav-item"><a class="nav-link <?= $q===$k?'active':'' ?>" href="<?= e(url('/admin/ar-verify.php?' . $qpV(['q'=>$k]))) ?>">
                <i class="ti ti-<?= e($b[3]) ?> me-1"></i><?= e($b[1]) ?>
                <?php if ($cnt[$k]): ?><span class="badge bg-<?= $b[2] ?> ms-1"><?= $cnt[$k] ?></span><?php endif; ?></a></li>
        <?php endforeach; ?>
        <li class="nav-item ms-auto"><a class="nav-link <?= $showSent?'active':'' ?>" href="<?= e(url('/admin/ar-verify.php?' . $qpV(['view'=>$showSent?null:'sent']))) ?>">
            <i class="ti ti-history me-1"></i><?= $showSent ? 'Showing: done' : 'View done' ?></a></li>
    </ul>

    <div class="card">
        <form method="POST" action="<?= e(url('/admin/ar-verify.php?' . $qpV())) ?>">
            <?= csrf_field() ?><input type="hidden" name="action" value="confirm_sent">
            <?php if (!$showSent): ?>
            <div class="card-body border-bottom py-2 d-flex flex-wrap align-items-center gap-2">
                <button class="btn btn-sm btn-primary"><i class="ti ti-send me-1"></i><?= e($BUCKETS[$q][4]) ?> — selected</button>
                <span class="text-secondary small">Marks the selected visits handled (records who &amp; when).</span>
            </div>
            <?php endif; ?>
            <div class="table-responsive"><table class="table table-vcenter card-table table-sm">
                <thead><tr>
                    <?php if (!$showSent): ?><th class="w-1"><input type="checkbox" class="form-check-input m-0" onclick="document.querySelectorAll('.arv-cb').forEach(c=>c.checked=this.checked)"></th><?php endif; ?>
                    <th>Patient Account #</th><th>Visit ID</th><th>AR worker</th><th>Carrier</th><th>DOS</th>
                    <th class="text-end">Ins. bal</th><th>Claim status</th><th>Action taken</th><th>Notes</th><th><?= $showSent ? 'Sent' : 'Routed' ?></th>
                </tr></thead>
                <tbody>
                <?php $cols = $showSent ? 10 : 11; if (!$rows): ?>
                    <tr><td colspan="<?= $cols ?>" class="text-center text-secondary py-4">Nothing <?= $showSent ? 'sent yet' : 'waiting in this bucket' ?>. 🎉</td></tr>
                <?php else: foreach ($rows as $r): ?>
                    <tr>
                        <?php if (!$showSent): ?><td><input type="checkbox" class="form-check-input m-0 arv-cb" name="ids[]" value="<?= (int)$r['id'] ?>"></td><?php endif; ?>
                        <td class="font-mono"><?= e($r['chart_number']) ?></td>
                        <td class="font-mono small"><?= e($r['visit_id']) ?></td>
                        <td class="small"><?= e($r['worker_name'] ?? '—') ?></td>
                        <td class="small"><?= e($r['carrier_name'] ?? '—') ?></td>
                        <td class="small"><?= e(fmt_date($r['dos'])) ?></td>
                        <td class="text-end small"><?= $r['insurance_balance']!==null?number_format((float)$r['insurance_balance'],2):'—' ?></td>
                        <td class="small text-secondary"><?= e($r['claim_status'] ?? '—') ?></td>
                        <td class="small"><?= e($r['action_taken'] ?? '—') ?></td>
                        <td class="small text-secondary" style="max-width:220px"><?= e($r['notes'] ?? '') ?></td>
                        <td class="small text-nowrap"><?= e(fmt_dt($showSent ? $r['sent_at'] : $r['bucket_at'])) ?></td>
                    </tr>
                <?php endforeach; endif; ?>
                </tbody>
            </table></div>
        </form>
    </div>

</div></div>
<?php require __DIR__ . '/../includes/footer.php'; ?>
