<?php
/**
 * CPT → ALF billing map (coding.supervise) — a supervisor / manager adds, edits, hides and
 * deletes the CPT→ALF pairs. When a chart goes to billing, each CPT is printed with its ALF
 * code as "CPT/ALF" (e.g. 99202/99341) in the deliverables export, the on-screen detail, and
 * the billing queue. Stored in coding_alf_map; charts are not stored with the pair, so editing
 * the map applies everywhere immediately (and never rewrites a chart's coded CPTs).
 */
require_once __DIR__ . '/../includes/config.php';
$user = require_login('internal');
$pdo  = db();
$uid  = (int) $user['id'];

$normCode = static function ($v): string {
    return strtoupper(trim((string) $v));
};
$validCode = static function (string $v): bool {
    return (bool) preg_match('/^[A-Z0-9]{3,7}$/', $v);   // CPT/HCPCS-style code
};

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_check_or_die();
    $act = $_POST['action'] ?? '';

    if ($act === 'add') {
        $cpt = $normCode(input('cpt_code'));
        $alf = $normCode(input('alf_code'));
        if (!$validCode($cpt) || !$validCode($alf)) {
            flash('error', 'Enter a valid CPT code and ALF code (3–7 letters/digits each).');
        } else {
            try {
                $pdo->prepare("INSERT INTO coding_alf_map (cpt_code, alf_code, created_by) VALUES (?,?,?)")
                    ->execute([$cpt, $alf, $uid]);
                audit_log('coding.alf.add', 'coding_alf_map', null, null, ['cpt'=>$cpt, 'alf'=>$alf]);
                flash('success', "Mapping added: {$cpt}/{$alf}.");
            } catch (Throwable $e) {
                flash('error', "A mapping for CPT {$cpt} already exists — edit it instead.");
            }
        }
    } elseif ($act === 'edit') {
        $id  = (int) input('id');
        $cpt = $normCode(input('cpt_code'));
        $alf = $normCode(input('alf_code'));
        if (!$id || !$validCode($cpt) || !$validCode($alf)) {
            flash('error', 'Enter a valid CPT code and ALF code.');
        } else {
            try {
                $pdo->prepare("UPDATE coding_alf_map SET cpt_code=?, alf_code=? WHERE id=?")->execute([$cpt, $alf, $id]);
                audit_log('coding.alf.edit', 'coding_alf_map', $id, null, ['cpt'=>$cpt, 'alf'=>$alf]);
                flash('success', "Mapping saved: {$cpt}/{$alf}.");
            } catch (Throwable $e) {
                flash('error', "Another mapping already uses CPT {$cpt}.");
            }
        }
    } elseif ($act === 'toggle') {
        $id = (int) input('id');
        $pdo->prepare("UPDATE coding_alf_map SET status = IF(status='active','inactive','active') WHERE id=?")->execute([$id]);
        audit_log('coding.alf.toggle', 'coding_alf_map', $id);
        flash('success', 'Mapping updated.');
    } elseif ($act === 'delete') {
        $id = (int) input('id');
        $pdo->prepare("DELETE FROM coding_alf_map WHERE id=?")->execute([$id]);
        audit_log('coding.alf.delete', 'coding_alf_map', $id);
        flash('success', 'Mapping deleted.');
    }
    redirect('/admin/coding-alf.php');
}

$rows = $pdo->query("SELECT * FROM coding_alf_map ORDER BY cpt_code")->fetchAll();
$active = 0; foreach ($rows as $r) if ($r['status'] === 'active') $active++;

$pageTitle = 'CPT → ALF map';
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-arrows-exchange me-2 text-primary"></i>CPT → ALF billing map</h2>
        <div class="text-secondary small">When a chart goes to billing, each CPT is paired with its ALF code as <code>CPT/ALF</code> (e.g. <code>99202/99341</code>) in the Excel download, the deliverables detail, and the billing queue. Edits apply everywhere immediately and never change a chart's coded CPTs.</div>
    </div>
    <div class="col-auto"><a href="<?= e(url('/admin/coding-home.php')) ?>" class="btn btn-outline-secondary"><i class="ti ti-arrow-left me-1"></i>Coding home</a></div>
</div></div></div>
<div class="page-body"><div class="container-xl"><div class="row justify-content-center"><div class="col-lg-8">
    <div class="card">
        <div class="card-header py-2"><h3 class="card-title mb-0">Mappings <span class="text-secondary fw-normal small">(<?= count($rows) ?> total, <?= $active ?> active)</span></h3></div>
        <div class="card-body py-2 border-bottom">
            <form method="POST" class="row g-2 align-items-end"><?= csrf_field() ?><input type="hidden" name="action" value="add">
                <div class="col-auto"><label class="form-label mb-1 small">CPT code</label><input name="cpt_code" class="form-control form-control-sm" placeholder="99202" maxlength="7" style="width:7rem" required></div>
                <div class="col-auto pb-1 fw-bold text-secondary align-self-center">/</div>
                <div class="col-auto"><label class="form-label mb-1 small">ALF code</label><input name="alf_code" class="form-control form-control-sm" placeholder="99341" maxlength="7" style="width:7rem" required></div>
                <div class="col-auto"><button class="btn btn-sm btn-primary"><i class="ti ti-plus me-1"></i>Add mapping</button></div>
            </form>
        </div>
        <div class="table-responsive"><table class="table table-vcenter card-table">
            <thead><tr><th>Mapping (CPT / ALF)</th><th>Billed as</th><th class="w-1 text-nowrap">Status</th><th class="w-1 text-end">Actions</th></tr></thead>
            <tbody>
            <?php foreach ($rows as $r): $on = $r['status'] === 'active'; ?>
                <tr>
                    <td><form method="POST" class="d-flex gap-1 align-items-center"><?= csrf_field() ?><input type="hidden" name="action" value="edit"><input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                        <input name="cpt_code" class="form-control form-control-sm" value="<?= e($r['cpt_code']) ?>" maxlength="7" style="width:6.5rem">
                        <span class="fw-bold text-secondary">/</span>
                        <input name="alf_code" class="form-control form-control-sm" value="<?= e($r['alf_code']) ?>" maxlength="7" style="width:6.5rem">
                        <button class="btn btn-sm btn-outline-primary" title="Save"><i class="ti ti-device-floppy"></i></button>
                    </form></td>
                    <td><span class="badge bg-azure-lt"><?= e($r['cpt_code']) ?>/<?= e($r['alf_code']) ?></span></td>
                    <td><span class="badge bg-<?= $on?'success':'secondary' ?>-lt"><?= $on?'active':'hidden' ?></span></td>
                    <td class="text-end text-nowrap">
                        <form method="POST" class="d-inline"><?= csrf_field() ?><input type="hidden" name="action" value="toggle"><input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                            <button class="btn btn-sm btn-ghost-secondary" title="<?= $on?'Hide (stop pairing)':'Activate' ?>"><i class="ti ti-<?= $on?'eye-off':'eye' ?>"></i></button></form>
                        <form method="POST" class="d-inline" onsubmit="return confirm('Delete the <?= e($r['cpt_code']) ?>/<?= e($r['alf_code']) ?> mapping?');"><?= 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" title="Delete"><i class="ti ti-trash"></i></button></form>
                    </td>
                </tr>
            <?php endforeach; ?>
            <?php if (!$rows): ?><tr><td colspan="4" class="text-center text-secondary py-4">No CPT→ALF mappings yet. Add one above.</td></tr><?php endif; ?>
            </tbody>
        </table></div>
    </div>
</div></div></div></div>
<?php require __DIR__ . '/../includes/footer.php'; ?>
