<?php
/**
 * CPT validation management (coding.cpt.manage).
 *   - Per (facility, provider): list / add / edit / delete the valid CPT set.
 *   - Monitoring: every coder-added CPT (source='coder') — who added what, where.
 *
 * Navigation (no JS needed):
 *   no params                         -> monitoring + facility picker
 *   ?facility_id=X                    -> pick a provider at that facility
 *   ?facility_id=X&provider_id=Y      -> edit that pair's CPT set
 */
require_once __DIR__ . '/../includes/config.php';
$user = require_login('internal');
$pdo  = db();

$facilityId = (int) ($_GET['facility_id'] ?? $_POST['facility_id'] ?? 0);
$providerId = (int) ($_GET['provider_id'] ?? $_POST['provider_id'] ?? 0);

/* Bulk-upload template (.xlsx) — sheet 1 is the blank template to fill in; sheet 2 lists every existing link. */
if (($_GET['bulk_template'] ?? '') === 'xlsx') {
    require_once __DIR__ . '/../includes/xlsx.php';
    $x = new SimpleXlsx();
    $cols = ['Client', 'Process', 'Facility', 'Provider', 'CPT', 'Description (optional)'];
    // Sheet 1 — the upload template (exactly the columns the importer reads), with example rows to copy.
    $x->addSheet('CPT links', $cols,
        [['01 Maximize', '01 Peyman Younesi', 'ABC - Main Hospital', 'Smith, John MD', '99213', 'Office visit'],
         ['01 Maximize', '01 Peyman Younesi', 'ABC - Main Hospital', 'Smith, John MD', '99214', '']]);
    // Sheet 2 — EVERY facility»provider link the manager can code for (via coding_facility_providers), so a brand-new
    // client / process / facility / provider shows up here even before it has any CPTs. The CPT/Description cells are
    // LEFT-JOINed, so a link with no CPTs yet appears as ONE blank-CPT row ready to fill in. Scoped to coding-workflow
    // verticals (same fence as the on-screen facility picker below). Streamed + kept as text so CPT codes don't reformat.
    $existing = $pdo->query("SELECT c.name, p.name, f.name, pr.name, COALESCE(v.cpt_code,''), COALESCE(v.description,'')
        FROM clients c
        JOIN processes p ON p.client_id=c.id
        JOIN coding_facilities f ON f.process_id=p.id
        JOIN coding_facility_providers fp ON fp.facility_id=f.id
        JOIN coding_providers pr ON pr.id=fp.provider_id
        LEFT JOIN coding_cpt_validation v ON v.facility_id=f.id AND v.provider_id=pr.id AND v.status='active'
        WHERE c.deleted_at IS NULL AND p.deleted_at IS NULL AND " . coding_workflow_vertical_in_sql('c.vertical_id') . "
        ORDER BY c.name, p.name, f.name, pr.name, COALESCE(v.cpt_code,'~')");
    $x->addSheetFromStmt('Existing links', $cols, $existing);
    $x->download('cpt-links-template.xlsx');
    exit;
}

/* Download the LAST bulk-import result as .xlsx (per-CPT status + error). Stashed in the session by the
   bulk_import handler below so it survives the render→click round-trip without a persisted table. */
if (($_GET['download_result'] ?? '') === 'xlsx') {
    $res = $_SESSION['cpt_import_result']['rows'] ?? [];
    require_once __DIR__ . '/../includes/xlsx.php';
    $x = new SimpleXlsx();
    $data = [];
    foreach ($res as $r) $data[] = [$r['row'] ?? '', $r['client'] ?? '', $r['process'] ?? '', $r['facility'] ?? '', $r['provider'] ?? '', $r['cpt'] ?? '', $r['description'] ?? '', $r['status'] ?? '', $r['error'] ?? ''];
    $x->addSheet('Import result', ['Row', 'Client', 'Process', 'Facility', 'Provider', 'CPT', 'Description', 'Status', 'Error'], $data);
    $x->download('cpt-import-result-' . date('Ymd-His') . '.xlsx');
    exit;
}

$bulkReport = null;

/* ----------------------------------------------------------- POST handlers */
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_check_or_die();
    $act = $_POST['action'] ?? '';
    $back = '/admin/coding-cpt.php?facility_id=' . $facilityId . '&provider_id=' . $providerId;

    if ($act === 'add' && $facilityId && $providerId) {
        $code = strtoupper(trim((string) input('cpt_code')));
        $desc = trim((string) input('description'));
        if (coding_provider_is_scribe($pdo, $providerId)) {
            flash('error', 'A scribe is global and cannot be linked to a facility.');
        } elseif (!preg_match('/^[A-Z0-9]{3,7}$/', $code)) {
            flash('error', 'CPT must be 3–7 letters/digits, no spaces.');
        } else {
            $pdo->prepare("INSERT IGNORE INTO coding_cpt_codes (code,description,created_at) VALUES (?,?,NOW())")->execute([$code, $desc ?: null]);
            $ins = $pdo->prepare("INSERT INTO coding_cpt_validation (facility_id,provider_id,cpt_code,description,source,added_by,status,created_at,updated_at)
                                  VALUES (?,?,?,?, 'manual', ?, 'active', NOW(), NOW())
                                  ON DUPLICATE KEY UPDATE status='active', description=VALUES(description), updated_at=NOW()");
            $ins->execute([$facilityId, $providerId, $code, $desc ?: null, (int) $user['id']]);
            audit_log('coding.cpt.add', 'coding_cpt_validation', null, null, ['facility_id'=>$facilityId,'provider_id'=>$providerId,'cpt'=>$code]);
            flash('success', "CPT $code added.");
        }
        redirect($back);
    }

    if ($act === 'update') {
        $id   = (int) input('id');
        $desc = trim((string) input('description'));
        $status = in_array(input('status'), ['active','inactive'], true) ? input('status') : 'active';
        $row = $pdo->prepare("SELECT * FROM coding_cpt_validation WHERE id=?"); $row->execute([$id]); $row = $row->fetch();
        if ($row) {
            $pdo->prepare("UPDATE coding_cpt_validation SET description=?, status=?, updated_at=NOW() WHERE id=?")->execute([$desc ?: null, $status, $id]);
            audit_log('coding.cpt.update', 'coding_cpt_validation', $id, $row, ['description'=>$desc,'status'=>$status]);
            flash('success', 'CPT updated.');
            $back = '/admin/coding-cpt.php?facility_id=' . (int)$row['facility_id'] . '&provider_id=' . (int)$row['provider_id'];
        }
        redirect($back);
    }

    if ($act === 'delete') {
        $id = (int) input('id');
        $row = $pdo->prepare("SELECT * FROM coding_cpt_validation WHERE id=?"); $row->execute([$id]); $row = $row->fetch();
        if ($row) {
            $pdo->prepare("DELETE FROM coding_cpt_validation WHERE id=?")->execute([$id]);
            audit_log('coding.cpt.delete', 'coding_cpt_validation', $id, $row, null);
            flash('success', "CPT {$row['cpt_code']} removed.");
            $back = '/admin/coding-cpt.php?facility_id=' . (int)$row['facility_id'] . '&provider_id=' . (int)$row['provider_id'];
        }
        redirect($back);
    }

    if ($act === 'bulk_import') {                       // sets $bulkReport, falls through to render (no redirect)
        if (empty($_FILES['file']['tmp_name']) || !is_uploaded_file($_FILES['file']['tmp_name'])) {
            flash('error', 'Choose an .xlsx file to upload.');
        } else {
            try {
                require_once __DIR__ . '/../includes/xlsx-reader.php';
                $rd = new XlsxReader($_FILES['file']['tmp_name']); $rows = []; $i = 0;
                foreach ($rd->rows(0) as $r) { if (++$i === 1) continue; $rows[] = ['client'=>$r[0]??'','process'=>$r[1]??'','facility'=>$r[2]??'','provider'=>$r[3]??'','cpt'=>$r[4]??'','desc'=>$r[5]??'']; }
                $rd->close();
                $bulkReport = coding_import_cpt_links($pdo, $rows, (int) $user['id']);
                // Stash the per-row detail so the "Download results" button can stream it as .xlsx next request.
                $_SESSION['cpt_import_result'] = ['at' => time(), 'rows' => $bulkReport['rows'] ?? []];
            } catch (Throwable $e) { flash('error', 'Could not read the workbook: ' . (APP_DEBUG ? $e->getMessage() : 'invalid .xlsx file')); }
        }
    }
}

$pageTitle = 'CPT validation';
require __DIR__ . '/../includes/header.php';

/* facility / provider context */
$fac = null; $prov = null;
if ($facilityId) {
    $fac = $pdo->prepare("SELECT f.*, p.name pname, c.name cname FROM coding_facilities f JOIN processes p ON p.id=f.process_id JOIN clients c ON c.id=p.client_id WHERE f.id=?");
    $fac->execute([$facilityId]); $fac = $fac->fetch();
}
if ($providerId) { $prov = $pdo->prepare("SELECT * FROM coding_providers WHERE id=?"); $prov->execute([$providerId]); $prov = $prov->fetch(); }
?>
<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-list-numbers me-2 text-primary"></i>CPT validation</h2>
        <div class="text-secondary small">Per facility &amp; provider CPT sets. Add / edit / remove codes; review coder-added codes.</div>
    </div>
    <?php if ($fac && $prov): ?><div class="col-auto"><a href="<?= e(url('/admin/coding-cpt.php')) ?>" class="btn btn-outline-secondary"><i class="ti ti-arrow-left me-1"></i>All</a></div><?php endif; ?>
</div></div></div>

<div class="page-body"><div class="container-xl">
<?php
/* ---------- EDITOR: facility + provider chosen ---------- */
if ($fac && $prov):
    $rows = $pdo->prepare("SELECT v.*, u.name AS added_name FROM coding_cpt_validation v
        LEFT JOIN users u ON u.id=v.added_by WHERE v.facility_id=? AND v.provider_id=? ORDER BY v.cpt_code");
    $rows->execute([$facilityId, $providerId]); $rows = $rows->fetchAll();
    $provIsScribe = ($prov['provider_type'] ?? '') === 'scribe';   // scribes are global — never facility-scoped
?>
    <div class="alert alert-info d-flex flex-wrap gap-3 align-items-center">
        <div><i class="ti ti-building-hospital me-1"></i><strong><?= e($fac['name']) ?></strong> <span class="text-secondary">(<?= e($fac['cname']) ?> · <?= e($fac['pname']) ?>)</span></div>
        <div><i class="ti ti-user me-1"></i><strong><?= e($prov['name']) ?></strong><?php if ($provIsScribe): ?> <span class="badge bg-purple-lt ms-1"><i class="ti ti-pencil me-1"></i>Scribe</span><?php endif; ?></div>
        <div class="ms-auto"><span class="badge bg-blue-lt"><?= count($rows) ?> codes</span></div>
    </div>

    <?php if ($provIsScribe): ?>
    <div class="alert alert-warning"><i class="ti ti-alert-triangle me-1"></i><strong>A scribe is global and cannot be linked to a facility.</strong> Scribes are not facility-scoped, so they have no per-facility CPT validation set. Manage scribes on <a href="<?= e(url('/admin/coding-providers.php?provider_type=scribe')) ?>">Providers</a>.</div>
    <?php else: ?>
    <div class="card mb-3"><div class="card-body">
        <form method="POST" class="row g-2 align-items-end">
            <?= csrf_field() ?>
            <input type="hidden" name="action" value="add">
            <input type="hidden" name="facility_id" value="<?= $facilityId ?>">
            <input type="hidden" name="provider_id" value="<?= $providerId ?>">
            <div class="col-md-3"><label class="form-label">CPT code</label><input name="cpt_code" class="form-control text-uppercase" placeholder="99213" required maxlength="7"></div>
            <div class="col-md-7"><label class="form-label">Description (optional)</label><input name="description" class="form-control" maxlength="255" placeholder="OFFICE O/P EST LOW 20 MIN"></div>
            <div class="col-md-2"><button class="btn btn-primary w-100"><i class="ti ti-plus me-1"></i>Add CPT</button></div>
        </form>
    </div></div>
    <?php endif; ?>

    <div class="card">
        <div class="table-responsive"><table class="table table-vcenter card-table">
            <thead><tr><th>CPT</th><th>Description</th><th>Source</th><th>Added by</th><th>Status</th><th class="w-1"></th></tr></thead>
            <tbody>
            <?php foreach ($rows as $r):
                $srcBadge = ['seed'=>'secondary','coder'=>'orange','manual'=>'blue'][$r['source']] ?? 'secondary'; ?>
                <tr>
                    <td><code class="fw-bold"><?= e($r['cpt_code']) ?></code></td>
                    <td>
                        <form method="POST" class="d-flex gap-2 align-items-center">
                            <?= csrf_field() ?><input type="hidden" name="action" value="update"><input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                            <input type="hidden" name="facility_id" value="<?= $facilityId ?>"><input type="hidden" name="provider_id" value="<?= $providerId ?>">
                            <input name="description" class="form-control form-control-sm" value="<?= e($r['description']) ?>" maxlength="255" style="min-width:220px">
                            <select name="status" class="form-select form-select-sm w-auto">
                                <option value="active" <?= $r['status']==='active'?'selected':'' ?>>active</option>
                                <option value="inactive" <?= $r['status']==='inactive'?'selected':'' ?>>inactive</option>
                            </select>
                            <button class="btn btn-sm btn-ghost-primary" title="Save"><i class="ti ti-device-floppy"></i></button>
                        </form>
                    </td>
                    <td><span class="badge bg-<?= $srcBadge ?>-lt"><?= e($r['source']) ?></span></td>
                    <td class="text-secondary small"><?= e($r['added_name'] ?? '—') ?></td>
                    <td><span class="badge bg-<?= $r['status']==='active'?'success':'secondary' ?>-lt"><?= e($r['status']) ?></span></td>
                    <td>
                        <form method="POST" onsubmit="return confirm('Remove CPT <?= e($r['cpt_code']) ?>?');">
                            <?= csrf_field() ?><input type="hidden" name="action" value="delete"><input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                            <button class="btn btn-sm btn-ghost-danger"><i class="ti ti-trash"></i></button>
                        </form>
                    </td>
                </tr>
            <?php endforeach; ?>
            <?php if (!$rows): ?><tr><td colspan="6" class="text-center text-secondary py-4">No CPTs yet — add the first one above.</td></tr><?php endif; ?>
            </tbody>
        </table></div>
    </div>

<?php
/* ---------- PROVIDER PICKER: facility chosen, no provider ---------- */
elseif ($fac):
    $provs = $pdo->prepare("SELECT pr.id, pr.name, (SELECT COUNT(*) FROM coding_cpt_validation v WHERE v.facility_id=? AND v.provider_id=pr.id AND v.status='active') cpt_n
        FROM coding_facility_providers fp JOIN coding_providers pr ON pr.id=fp.provider_id WHERE fp.facility_id=? ORDER BY pr.name");
    $provs->execute([$facilityId, $facilityId]); $provs = $provs->fetchAll();
?>
    <div class="alert alert-info"><i class="ti ti-building-hospital me-1"></i>Pick a provider at <strong><?= e($fac['name']) ?></strong>:</div>
    <div class="card"><div class="list-group list-group-flush">
        <?php foreach ($provs as $pr): ?>
            <a href="<?= e(url('/admin/coding-cpt.php?facility_id='.$facilityId.'&provider_id='.$pr['id'])) ?>" class="list-group-item list-group-item-action d-flex align-items-center">
                <i class="ti ti-user me-2 text-secondary"></i><?= e($pr['name']) ?>
                <span class="badge bg-blue-lt ms-auto"><?= (int)$pr['cpt_n'] ?> CPTs</span>
            </a>
        <?php endforeach; ?>
        <?php if (!$provs): ?><div class="list-group-item text-secondary text-center py-4">No providers at this facility.</div><?php endif; ?>
    </div></div>

<?php
/* ---------- DEFAULT: monitoring (coder-added) + facility picker ---------- */
else:
    $added = $pdo->query("SELECT v.*, f.name fname, c.name cname, pr.name pname, u.name added_name
        FROM coding_cpt_validation v
        JOIN coding_facilities f ON f.id=v.facility_id
        JOIN processes p ON p.id=f.process_id JOIN clients c ON c.id=p.client_id
        JOIN coding_providers pr ON pr.id=v.provider_id
        LEFT JOIN users u ON u.id=v.added_by
        WHERE v.source='coder' ORDER BY v.created_at DESC LIMIT 500")->fetchAll();
    $facs = $pdo->query("SELECT f.id, f.name, c.name cname FROM coding_facilities f JOIN processes p ON p.id=f.process_id JOIN clients c ON c.id=p.client_id
        WHERE c.deleted_at IS NULL AND p.deleted_at IS NULL AND " . coding_workflow_vertical_in_sql('c.vertical_id') . " ORDER BY c.name, f.name")->fetchAll();
?>
    <?php coding_bulk_upload_render([
        'title'        => 'Bulk upload CPT ↔ provider links',
        'template_url' => url('/admin/coding-cpt.php?bulk_template=xlsx'),
        'action_url'   => url('/admin/coding-cpt.php'),
        'columns'      => ['Client', 'Process', 'Facility', 'Provider', 'CPT', 'Description'],
        'report'       => $bulkReport,
    ]); ?>
    <?php if ($bulkReport && !empty($bulkReport['rows'])):
        $rrows = $bulkReport['rows']; $errN = 0; foreach ($rrows as $rr) if (($rr['status'] ?? '') === 'error') $errN++; ?>
    <div class="card mb-3">
        <div class="card-header py-2">
            <h3 class="card-title mb-0">Import result — each CPT's status</h3>
            <div class="card-actions">
                <span class="badge bg-green-lt me-1"><?= (int)$bulkReport['created'] ?> created</span>
                <span class="badge bg-blue-lt me-1"><?= (int)$bulkReport['updated'] ?> updated</span>
                <span class="badge bg-<?= $errN ? 'red' : 'secondary' ?>-lt me-2"><?= (int)$errN ?> error<?= $errN === 1 ? '' : 's' ?></span>
                <a href="<?= e(url('/admin/coding-cpt.php?download_result=xlsx')) ?>" class="btn btn-sm btn-outline-primary"><i class="ti ti-file-spreadsheet me-1"></i>Download results (.xlsx)</a>
            </div>
        </div>
        <div class="table-responsive" style="max-height:420px;overflow:auto">
            <table class="table table-sm table-vcenter card-table">
                <thead><tr><th class="w-1">Row</th><th>Client » Process » Facility</th><th>Provider</th><th class="w-1">CPT</th><th class="w-1">Status</th><th>Error</th></tr></thead>
                <tbody>
                <?php foreach ($rrows as $rr): $st = $rr['status'] ?? ''; $ok = $st !== 'error';
                    $bc = $st === 'created' ? 'green' : ($st === 'updated' ? 'blue' : 'red'); ?>
                    <tr class="<?= $ok ? '' : 'table-danger' ?>">
                        <td class="text-secondary"><?= (int)($rr['row'] ?? 0) ?></td>
                        <td class="small"><?= e(trim(($rr['client'] ?? '') . ' » ' . ($rr['process'] ?? '') . ' » ' . ($rr['facility'] ?? ''), ' »')) ?></td>
                        <td class="small"><?= e($rr['provider'] ?? '') ?></td>
                        <td class="fw-bold text-nowrap"><?= e($rr['cpt'] ?? '') ?></td>
                        <td><span class="badge bg-<?= $bc ?>-lt"><?= e($st) ?></span></td>
                        <td class="small text-danger"><?= e($rr['error'] ?? '') ?></td>
                    </tr>
                <?php endforeach; ?>
                </tbody>
            </table>
        </div>
    </div>
    <?php endif; ?>
    <div class="card mb-3"><div class="card-body">
        <form method="GET" class="row g-2 align-items-end">
            <div class="col-md-8"><label class="form-label">Jump to a facility to manage its CPT sets</label>
                <select name="facility_id" class="form-select" onchange="this.form.submit()">
                    <option value="">— choose a facility —</option>
                    <?php foreach ($facs as $f): ?><option value="<?= (int)$f['id'] ?>"><?= e($f['cname']) ?> · <?= e($f['name']) ?></option><?php endforeach; ?>
                </select>
            </div>
        </form>
    </div></div>

    <div class="card">
        <div class="card-header"><h3 class="card-title"><i class="ti ti-eye me-1"></i>Coder-added CPTs <span class="badge bg-orange-lt ms-2"><?= count($added) ?></span></h3>
            <div class="card-actions text-secondary small">New codes coders added while coding (for monitoring)</div>
        </div>
        <div class="table-responsive"><table class="table table-vcenter card-table">
            <thead><tr><th>CPT</th><th>Description</th><th>Client</th><th>Facility</th><th>Provider</th><th>Added by</th><th>When</th><th>Status</th><th class="w-1"></th></tr></thead>
            <tbody>
            <?php foreach ($added as $r): ?>
                <tr>
                    <td><code class="fw-bold"><?= e($r['cpt_code']) ?></code></td>
                    <td class="small"><?= e($r['description']) ?></td>
                    <td class="small text-secondary"><?= e($r['cname']) ?></td>
                    <td class="small"><?= e($r['fname']) ?></td>
                    <td class="small"><?= e($r['pname']) ?></td>
                    <td class="small"><?= e($r['added_name'] ?? '—') ?></td>
                    <td class="small text-secondary text-nowrap"><?= e(fmt_dt($r['created_at'])) ?></td>
                    <td><span class="badge bg-<?= $r['status']==='active'?'success':'secondary' ?>-lt"><?= e($r['status']) ?></span></td>
                    <td><a href="<?= e(url('/admin/coding-cpt.php?facility_id='.(int)$r['facility_id'].'&provider_id='.(int)$r['provider_id'])) ?>" class="btn btn-sm" title="Manage"><i class="ti ti-pencil"></i></a></td>
                </tr>
            <?php endforeach; ?>
            <?php if (!$added): ?><tr><td colspan="9" class="text-center text-secondary py-4">No coder-added CPTs yet.</td></tr><?php endif; ?>
            </tbody>
        </table></div>
    </div>
<?php endif; ?>
</div></div>
<?php require __DIR__ . '/../includes/footer.php'; ?>
