<?php
/**
 * Coding reference data (coding.reference): browse ICD-10-CM, CPT master and
 * modifiers; re-run the bundled imports if the data files are refreshed.
 */
require_once __DIR__ . '/../includes/config.php';
$user = require_login('internal');
$pdo  = db();

$tab = $_GET['tab'] ?? 'icd';
$q   = trim((string) input('q'));

/* ----------------------------------------------------------- POST: re-import */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_check_or_die();
    $act = $_POST['action'] ?? '';
    try {
        if ($act === 'reimport_icd') {
            // force a re-read even if already present
            $pdo->exec("DELETE FROM coding_icd_codes");
            $n = coding_import_icd($pdo, __DIR__ . '/../data/coding/icd10cm_codes_2026.txt');
            audit_log('coding.reference.reimport', 'coding_icd_codes', null, null, ['rows'=>$n]);
            flash('success', "ICD re-imported: " . number_format($n) . " codes.");
        } elseif ($act === 'resync_hierarchy') {
            $c = coding_seed_hierarchy_and_cpt($pdo, __DIR__ . '/../data/coding/cpt-mapping.xlsx');
            audit_log('coding.reference.resync', 'coding_cpt_validation', null, null, $c);
            flash('success', 'Hierarchy/CPT re-synced from workbook (new: ' . $c['validation'] . ' validation, ' . $c['facilities'] . ' facilities).'
                . (!empty($c['scribes_skipped']) ? ' Skipped ' . $c['scribes_skipped'] . ' scribe row(s) — a scribe is global and cannot be linked to a facility.' : ''));
        }
    } catch (Throwable $e) {
        flash('error', 'Import failed: ' . $e->getMessage());
    }
    redirect('/admin/coding-reference.php?tab=' . $tab);
}

$counts = [
    'icd' => (int) $pdo->query("SELECT COUNT(*) FROM coding_icd_codes")->fetchColumn(),
    'cpt' => (int) $pdo->query("SELECT COUNT(*) FROM coding_cpt_codes")->fetchColumn(),
    'mod' => (int) $pdo->query("SELECT COUNT(*) FROM coding_modifiers")->fetchColumn(),
];

$pageTitle = 'Coding reference';
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-database me-2 text-primary"></i>Coding reference data</h2></div>
</div></div></div>
<div class="page-body"><div class="container-xl">

    <ul class="nav nav-tabs mb-3">
        <li class="nav-item"><a class="nav-link <?= $tab==='icd'?'active':'' ?>" href="<?= e(url('/admin/coding-reference.php?tab=icd')) ?>">ICD-10-CM <span class="badge bg-blue-lt ms-1"><?= number_format($counts['icd']) ?></span></a></li>
        <li class="nav-item"><a class="nav-link <?= $tab==='cpt'?'active':'' ?>" href="<?= e(url('/admin/coding-reference.php?tab=cpt')) ?>">CPT master <span class="badge bg-blue-lt ms-1"><?= number_format($counts['cpt']) ?></span></a></li>
        <li class="nav-item"><a class="nav-link <?= $tab==='mod'?'active':'' ?>" href="<?= e(url('/admin/coding-reference.php?tab=mod')) ?>">Modifiers <span class="badge bg-blue-lt ms-1"><?= $counts['mod'] ?></span></a></li>
    </ul>

<?php if ($tab === 'icd'):
    $rows = [];
    if ($q !== '') {
        $st = $pdo->prepare("SELECT code, code_dotted, description FROM coding_icd_codes
                             WHERE code LIKE ? OR code_dotted LIKE ? OR description LIKE ?
                             ORDER BY code LIMIT 200");
        $st->execute([$q . '%', $q . '%', '%' . $q . '%']);
        $rows = $st->fetchAll();
    }
?>
    <div class="card">
        <div class="card-header">
            <form method="GET" class="d-flex w-100 gap-2"><input type="hidden" name="tab" value="icd">
                <input name="q" class="form-control" placeholder="Search ICD by code (A00) or description (cholera)…" value="<?= e($q) ?>" autofocus>
                <button class="btn btn-primary"><i class="ti ti-search"></i></button>
            </form>
        </div>
        <div class="table-responsive"><table class="table table-vcenter card-table">
            <thead><tr><th>Code</th><th>Dotted</th><th>Description</th></tr></thead>
            <tbody>
            <?php if ($q === ''): ?>
                <tr><td colspan="3" class="text-center text-secondary py-4">Type at least one character to search <?= number_format($counts['icd']) ?> ICD-10-CM codes.</td></tr>
            <?php elseif (!$rows): ?>
                <tr><td colspan="3" class="text-center text-secondary py-4">No ICD codes match “<?= e($q) ?>”.</td></tr>
            <?php else: foreach ($rows as $r): ?>
                <tr><td><code><?= e($r['code']) ?></code></td><td><code class="text-blue"><?= e($r['code_dotted']) ?></code></td><td><?= e($r['description']) ?></td></tr>
            <?php endforeach; endif; ?>
            </tbody>
        </table></div>
        <?php if ($q !== '' && count($rows) >= 200): ?><div class="card-footer text-secondary small">Showing first 200 matches — refine your search.</div><?php endif; ?>
    </div>

<?php elseif ($tab === 'cpt'):
    $rows = $pdo->query("SELECT code, description, is_addon FROM coding_cpt_codes ORDER BY code")->fetchAll();
?>
    <div class="card">
        <div class="table-responsive"><table class="table table-vcenter card-table" id="dt">
            <thead><tr><th>CPT</th><th>Description</th><th>Origin</th></tr></thead>
            <tbody>
            <?php foreach ($rows as $r): ?>
                <tr><td><code class="fw-bold"><?= e($r['code']) ?></code></td><td><?= e($r['description']) ?></td>
                    <td><?= $r['is_addon'] ? '<span class="badge bg-orange-lt">coder add-on</span>' : '<span class="badge bg-secondary-lt">seed</span>' ?></td></tr>
            <?php endforeach; ?>
            </tbody>
        </table></div>
    </div>
    <script>document.addEventListener('DOMContentLoaded',function(){ if(window.jQuery&&jQuery.fn.DataTable) jQuery('#dt').DataTable({pageLength:25,order:[[0,'asc']]}); });</script>

<?php else:
    $rows = $pdo->query("SELECT code, description, status, sort_order FROM coding_modifiers ORDER BY sort_order, code")->fetchAll();
?>
    <div class="card">
        <?php if (can('coding.supervise')): ?>
        <div class="card-header py-2"><div class="text-secondary small">Read-only view. <a href="<?= e(url('/admin/coding-modifiers.php')) ?>">Manage modifiers</a> to add, edit, hide or delete.</div>
            <div class="card-actions"><a href="<?= e(url('/admin/coding-modifiers.php')) ?>" class="btn btn-sm btn-primary"><i class="ti ti-adjustments-alt me-1"></i>Manage modifiers</a></div></div>
        <?php endif; ?>
        <div class="table-responsive"><table class="table table-vcenter card-table">
            <thead><tr><th>Modifier</th><th>Description</th><th>Status</th></tr></thead>
            <tbody>
            <?php foreach ($rows as $r): ?>
                <tr><td><code class="fw-bold"><?= e($r['code']) ?></code></td><td><?= e($r['description']) ?></td>
                    <td><span class="badge bg-<?= $r['status']==='active'?'success':'secondary' ?>-lt"><?= e($r['status']) ?></span></td></tr>
            <?php endforeach; ?>
            </tbody>
        </table></div>
    </div>
<?php endif; ?>

    <?php if (can('coding.reference')): ?>
    <div class="card mt-3 border-warning">
        <div class="card-header"><h3 class="card-title text-warning"><i class="ti ti-refresh me-1"></i>Re-import from bundled files</h3></div>
        <div class="card-body d-flex flex-wrap gap-2 align-items-center">
            <div class="text-secondary small flex-grow-1">Re-runs the importer against <code>data/coding/</code>. Use after refreshing the source files. Hierarchy re-sync is additive (find-or-create); ICD re-import replaces the ICD table.</div>
            <form method="POST" onsubmit="return confirm('Re-import ICD codes? This replaces the ICD reference table.');">
                <?= csrf_field() ?><input type="hidden" name="action" value="reimport_icd"><input type="hidden" name="tab" value="<?= e($tab) ?>">
                <button class="btn btn-outline-warning"><i class="ti ti-file-import me-1"></i>Re-import ICD</button>
            </form>
            <form method="POST" onsubmit="return confirm('Re-sync hierarchy &amp; CPT validation from the workbook?');">
                <?= csrf_field() ?><input type="hidden" name="action" value="resync_hierarchy"><input type="hidden" name="tab" value="<?= e($tab) ?>">
                <button class="btn btn-outline-warning"><i class="ti ti-sitemap me-1"></i>Re-sync hierarchy/CPT</button>
            </form>
        </div>
    </div>
    <?php endif; ?>
</div></div>
<?php require __DIR__ . '/../includes/footer.php'; ?>
