<?php
/**
 * Pre-audit review (coding.supervise) — a supervisor / manager edits their TEAM's COMPLETED charts BEFORE the
 * auditor picks them up: status='completed' AND audit_status IS NULL AND not yet released to billing. Editing
 * reuses the coder screen (coding-chart.php), whose $editable gate allows this case for supervisors. Once an
 * auditor starts (audit_status set) the chart drops off this list and can no longer be edited here.
 */
require_once __DIR__ . '/../includes/config.php';
$user = require_login('internal');                 // route gate: coding.supervise
$pdo  = db();
$uid  = (int) $user['id'];
if (!can('coding.supervise')) { flash('error', 'Supervisor / manager access only.'); redirect('/admin/coding-home.php'); }

$team   = coding_team_scope($pdo, $uid);           // null = sysadmin (everyone)
$teamIn = ($team === null) ? '' : (' AND ci.coder_id IN (' . implode(',', array_map('intval', $team ?: [0])) . ')');

$fClient   = (int) ($_GET['client_id'] ?? 0);
$fFacility = (int) ($_GET['facility_id'] ?? 0);
$fCoder    = (int) ($_GET['coder_id'] ?? 0);

$base = "ci.status='completed' AND ci.audit_status IS NULL AND ci.released_to_billing_at IS NULL";
$w = [$base]; $pa = [];
if ($fClient)   { $w[] = 'ci.client_id=?';   $pa[] = $fClient; }
if ($fFacility) { $w[] = 'ci.facility_id=?'; $pa[] = $fFacility; }
if ($fCoder)    { $w[] = 'ci.coder_id=?';    $pa[] = $fCoder; }
$wsql = 'WHERE ' . implode(' AND ', $w) . $teamIn;

$rows = $pdo->prepare("SELECT ci.*, c.name cn, f.name fn, pr.name prn, bp.name billing_prov, u.name coder
    FROM coding_inventory ci JOIN clients c ON c.id=ci.client_id
    JOIN coding_facilities f ON f.id=ci.facility_id JOIN coding_providers pr ON pr.id=ci.provider_id
    LEFT JOIN coding_providers bp ON bp.id=ci.billing_provider_id
    LEFT JOIN users u ON u.id=ci.coder_id
    $wsql ORDER BY ci.submitted_at DESC, ci.id DESC LIMIT 1000");
$rows->execute($pa); $rows = $rows->fetchAll();
$linesByChart = coding_effective_lines_bulk($pdo, array_column($rows, 'id'));

/* filter option sources — same team scope, completed-not-audited only */
$optWhere = 'WHERE ' . $base . $teamIn;
$clients = $pdo->query("SELECT DISTINCT c.id,c.name FROM coding_inventory ci JOIN clients c ON c.id=ci.client_id $optWhere ORDER BY c.name")->fetchAll();
$facils  = $pdo->query("SELECT DISTINCT f.id,f.name FROM coding_inventory ci JOIN coding_facilities f ON f.id=ci.facility_id $optWhere ORDER BY f.name")->fetchAll();
$coders  = $pdo->query("SELECT DISTINCT u.id,u.name FROM coding_inventory ci JOIN users u ON u.id=ci.coder_id $optWhere ORDER BY u.name")->fetchAll();

$pageTitle = 'Pre-audit review';
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-edit-circle me-2 text-primary"></i>Pre-audit review</h2>
        <div class="text-secondary small">Your team's <strong>completed</strong> charts that have <strong>not yet been audited</strong> — fix codes or demographics here before the auditor picks them up. Once an audit starts, a chart drops off this list.</div>
    </div>
</div></div></div>
<div class="page-body"><div class="container-xl">

    <div class="card mb-3"><div class="card-body py-2"><form method="GET" class="row g-2 align-items-end">
        <?php $selOpt = function ($name, $opts, $cur, $all) { $h = '<select name="'.e($name).'" class="form-select form-select-sm"><option value="">'.e($all).'</option>';
            foreach ($opts as $o) $h .= '<option value="'.(int)$o['id'].'"'.($cur===(int)$o['id']?' selected':'').'>'.e($o['name']).'</option>'; return $h.'</select>'; }; ?>
        <div class="col-6 col-md-3"><label class="form-label mb-1 small">Client</label><?= $selOpt('client_id', $clients, $fClient, 'All clients') ?></div>
        <div class="col-6 col-md-3"><label class="form-label mb-1 small">Facility</label><?= $selOpt('facility_id', $facils, $fFacility, 'All facilities') ?></div>
        <div class="col-6 col-md-3"><label class="form-label mb-1 small">Coder</label><?= $selOpt('coder_id', $coders, $fCoder, 'All coders') ?></div>
        <div class="col-6 col-md-3"><button class="btn btn-sm btn-primary"><i class="ti ti-filter me-1"></i>Filter</button>
            <a href="<?= e(url('/admin/coding-review-editable.php')) ?>" class="btn btn-sm btn-ghost-secondary">Clear</a></div>
    </form></div></div>

    <div class="card">
        <div class="card-header py-2"><h3 class="card-title mb-0"><i class="ti ti-list-check me-1"></i><?= count($rows) ?> chart(s) awaiting audit</h3></div>
        <div class="table-responsive"><table class="table table-vcenter card-table table-sm" style="font-size:.8rem">
            <thead><tr><th>Patient</th><th>MRN/PRN</th><th>DOB</th><th>Client</th><th>Facility</th><th>Billing prov</th><th>DOS</th><th>CPT</th><th class="text-center">Units</th><th>Modifier(s)</th><th>ICD(s)</th><th>Coder</th><th>Submitted</th><th class="w-1"></th></tr></thead>
            <tbody>
            <?php if (!$rows): ?><tr><td colspan="14" class="text-center text-secondary py-4">No completed-but-unaudited charts for your team. 🎉</td></tr>
            <?php else: foreach ($rows as $r): $l = $linesByChart[(int)$r['id']] ?? []; ?>
                <tr>
                    <td><strong><?= e($r['patient_name']) ?></strong></td>
                    <td class="small"><?= e($r['patient_mrn'] ?: '—') ?></td>
                    <td class="small text-nowrap"><?= e(fmt_date($r['patient_dob'])) ?></td>
                    <td class="small text-secondary"><?= e($r['cn']) ?></td>
                    <td class="small"><?= e($r['fn']) ?></td>
                    <td class="small"><?= e($r['billing_prov'] ?: '—') ?></td>
                    <td class="small text-nowrap"><?= coding_lines_cell($l, 'dos') ?></td>
                    <td class="small"><?= coding_lines_cell($l, 'cpt') ?></td>
                    <td class="small text-center"><?= coding_lines_cell($l, 'units') ?></td>
                    <td class="small"><?= coding_lines_cell($l, 'mods') ?></td>
                    <td class="small"><?= coding_lines_cell($l, 'icds') ?></td>
                    <td class="small"><?= e($r['coder'] ?? '—') ?></td>
                    <td class="small text-secondary text-nowrap"><?= e(fmt_dt($r['submitted_at'])) ?></td>
                    <td><a href="<?= e(url('/admin/coding-chart.php?id='.(int)$r['id'])) ?>" class="btn btn-sm btn-primary"><i class="ti ti-edit me-1"></i>Edit</a></td>
                </tr>
            <?php endforeach; endif; ?>
            </tbody>
        </table></div>
        <?php if (count($rows) >= 1000): ?><div class="card-footer text-secondary small">Showing first 1000 — narrow with filters.</div><?php endif; ?>
    </div>
</div></div>
<?php require __DIR__ . '/../includes/footer.php'; ?>
