<?php
/**
 * CPT modifiers (coding.supervise) — a supervisor / manager adds, edits (description /
 * activate-deactivate) and deletes the modifier reference list that appears in the coder's
 * per-CPT modifier dropdown and gates chart validation. Stored in coding_modifiers (code = PK);
 * charts keep their chosen modifier as text in coding_chart_cpt_modifiers, so editing / deleting
 * a modifier here never alters existing charts. Read live via coding_modifiers() in includes/coding.php.
 */
require_once __DIR__ . '/../includes/config.php';
$user = require_login('internal');
$pdo  = db();
$uid  = (int) $user['id'];

/* Normalise a modifier code: trim + uppercase (modifiers are short alphanumerics like 25, 59, GT, JZ). */
function cmod_norm(string $c): string { return strtoupper(trim($c)); }

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

    if ($act === 'add') {
        $code = cmod_norm((string) ($_POST['code'] ?? ''));
        $desc = trim((string) ($_POST['description'] ?? ''));
        if ($code === '') { flash('error', 'Enter a modifier code.'); }
        elseif (!preg_match('/^[A-Z0-9]{1,8}$/', $code)) { flash('error', 'A modifier is 1–8 letters/digits (e.g. 25, 59, GT).'); }
        elseif (mb_strlen($desc) > 255) { flash('error', 'Description is too long (max 255 chars).'); }
        else {
            $mx = (int) $pdo->query("SELECT COALESCE(MAX(sort_order)+1,0) FROM coding_modifiers")->fetchColumn();
            try {
                $pdo->prepare("INSERT INTO coding_modifiers (code, description, status, sort_order, created_at) VALUES (?,?, 'active', ?, NOW())")
                    ->execute([$code, ($desc !== '' ? $desc : null), $mx]);
                audit_log('coding.modifier.add', 'coding_modifiers', null, null, ['code' => $code, 'description' => $desc]);
                flash('success', "Modifier {$code} added.");
            } catch (Throwable $e) { flash('error', "Modifier {$code} already exists — edit it below."); }
        }
    } elseif ($act === 'edit') {
        $code = cmod_norm((string) ($_POST['code'] ?? ''));
        $desc = trim((string) ($_POST['description'] ?? ''));
        if ($code === '') { flash('error', 'Missing modifier code.'); }
        elseif (mb_strlen($desc) > 255) { flash('error', 'Description is too long (max 255 chars).'); }
        else {
            $pdo->prepare("UPDATE coding_modifiers SET description=? WHERE code=?")->execute([($desc !== '' ? $desc : null), $code]);
            audit_log('coding.modifier.edit', 'coding_modifiers', null, null, ['code' => $code, 'description' => $desc]);
            flash('success', "Modifier {$code} updated.");
        }
    } elseif ($act === 'toggle') {
        $code = cmod_norm((string) ($_POST['code'] ?? ''));
        if ($code !== '') {
            $pdo->prepare("UPDATE coding_modifiers SET status = IF(status='active','inactive','active') WHERE code=?")->execute([$code]);
            audit_log('coding.modifier.toggle', 'coding_modifiers', null, null, ['code' => $code]);
            flash('success', "Modifier {$code} updated.");
        }
    } elseif ($act === 'delete') {
        $code = cmod_norm((string) ($_POST['code'] ?? ''));
        if ($code !== '') {
            $pdo->prepare("DELETE FROM coding_modifiers WHERE code=?")->execute([$code]);
            audit_log('coding.modifier.delete', 'coding_modifiers', null, null, ['code' => $code]);
            flash('success', "Modifier {$code} deleted. (Existing charts keep their text.)");
        }
    }
    redirect('/admin/coding-modifiers.php');
}

$rows = [];
try {
    $rows = $pdo->query("SELECT code, description, status, sort_order FROM coding_modifiers ORDER BY sort_order, code")->fetchAll();
} catch (Throwable $e) { $rows = []; }
$activeCt = 0; foreach ($rows as $r) if ($r['status'] === 'active') $activeCt++;

$pageTitle = 'CPT modifiers';
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-adjustments-alt me-2 text-primary"></i>CPT modifiers</h2>
        <div class="text-secondary small">Manage the modifier list coders can attach to a CPT. Hidden (inactive) modifiers stay off the dropdown but keep validating existing charts; editing or deleting a modifier never changes charts already tagged with it.</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 g-3 justify-content-center">
    <div class="col-lg-8"><div class="card">
        <div class="card-header py-2"><h3 class="card-title mb-0">Modifiers
            <span class="text-secondary fw-normal small">(<?= (int) $activeCt ?> active / <?= count($rows) ?> total)</span></h3></div>
        <div class="table-responsive"><table class="table table-vcenter card-table">
            <thead><tr><th class="w-1">Code</th><th>Description</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): $active = $r['status'] === 'active'; ?>
                <tr>
                    <td class="fw-bold text-nowrap"><?= e($r['code']) ?></td>
                    <td><form method="POST" class="d-flex gap-1"><?= csrf_field() ?><input type="hidden" name="action" value="edit"><input type="hidden" name="code" value="<?= e($r['code']) ?>">
                        <input name="description" class="form-control form-control-sm" value="<?= e($r['description'] ?? '') ?>" maxlength="255" placeholder="(no description)">
                        <button class="btn btn-sm btn-outline-primary" title="Save description"><i class="ti ti-device-floppy"></i></button>
                    </form></td>
                    <td><span class="badge bg-<?= $active ? 'success' : 'secondary' ?>-lt"><?= $active ? '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="code" value="<?= e($r['code']) ?>">
                            <button class="btn btn-sm btn-ghost-secondary" title="<?= $active ? 'Hide from the coder dropdown' : 'Show in the coder dropdown' ?>"><i class="ti ti-<?= $active ? 'eye-off' : 'eye' ?>"></i></button></form>
                        <form method="POST" class="d-inline" onsubmit="return confirm('Delete modifier <?= e($r['code']) ?>? Existing charts keep their text.');"><?= csrf_field() ?><input type="hidden" name="action" value="delete"><input type="hidden" name="code" value="<?= e($r['code']) ?>">
                            <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-3">No modifiers yet — add the first one below.</td></tr><?php endif; ?>
            </tbody>
        </table></div>
        <div class="card-footer py-2"><form method="POST" class="row g-1 align-items-center"><?= csrf_field() ?><input type="hidden" name="action" value="add">
            <div class="col-auto"><input name="code" class="form-control form-control-sm" style="width:110px" placeholder="Code" maxlength="8" required></div>
            <div class="col"><input name="description" class="form-control form-control-sm" placeholder="Description (optional)" maxlength="255"></div>
            <div class="col-auto"><button class="btn btn-sm btn-primary text-nowrap"><i class="ti ti-plus me-1"></i>Add modifier</button></div>
        </form></div>
    </div></div>
</div></div></div>
<?php require __DIR__ . '/../includes/footer.php'; ?>
