<?php
/**
 * Secondary reasons (coding.supervise) — a supervisor / manager adds, edits (rename /
 * activate-deactivate) and deletes the RFI and Disregard reason lists that appear in the
 * coder and Validator dropdowns. Stored in coding_secondary_reasons; charts keep their
 * chosen reason as text, so editing/deleting a reason never alters existing charts.
 */
require_once __DIR__ . '/../includes/config.php';
$user = require_login('internal');
$pdo  = db();
$uid  = (int) $user['id'];

$KINDS = ['rfi' => 'RFI', 'disregard' => 'Disregard'];

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

    if ($act === 'add') {
        $kind  = isset($KINDS[$_POST['kind'] ?? '']) ? (string) $_POST['kind'] : '';
        $label = trim((string) input('label'));
        if (!$kind || $label === '') { flash('error', 'Pick a type and enter a reason.'); }
        elseif (mb_strlen($label) > 120) { flash('error', 'Reason is too long (max 120 chars).'); }
        else {
            $mx = $pdo->prepare("SELECT COALESCE(MAX(sort_order)+1,0) FROM coding_secondary_reasons WHERE kind=?");
            $mx->execute([$kind]); $so = (int) $mx->fetchColumn();
            try {
                $pdo->prepare("INSERT INTO coding_secondary_reasons (kind,label,sort_order,created_by) VALUES (?,?,?,?)")
                    ->execute([$kind, $label, $so, $uid]);
                audit_log('coding.reason.add', 'coding_secondary_reasons', null, null, ['kind'=>$kind,'label'=>$label]);
                flash('success', 'Reason added.');
            } catch (Throwable $e) { flash('error', 'That reason already exists for ' . $KINDS[$kind] . '.'); }
        }
    } elseif ($act === 'edit') {
        $id = (int) input('id'); $label = trim((string) input('label'));
        if ($id && $label !== '') {
            try {
                $pdo->prepare("UPDATE coding_secondary_reasons SET label=? WHERE id=?")->execute([$label, $id]);
                audit_log('coding.reason.edit', 'coding_secondary_reasons', $id, null, ['label'=>$label]);
                flash('success', 'Reason renamed.');
            } catch (Throwable $e) { flash('error', 'A reason with that name already exists.'); }
        } else flash('error', 'Reason cannot be empty.');
    } elseif ($act === 'toggle') {
        $id = (int) input('id');
        $pdo->prepare("UPDATE coding_secondary_reasons SET status = IF(status='active','inactive','active') WHERE id=?")->execute([$id]);
        audit_log('coding.reason.toggle', 'coding_secondary_reasons', $id);
        flash('success', 'Reason updated.');
    } elseif ($act === 'delete') {
        $id = (int) input('id');
        $pdo->prepare("DELETE FROM coding_secondary_reasons WHERE id=?")->execute([$id]);
        audit_log('coding.reason.delete', 'coding_secondary_reasons', $id);
        flash('success', 'Reason deleted. (Existing charts keep their text.)');
    }
    redirect('/admin/coding-reasons.php');
}

$byKind = ['rfi' => [], 'disregard' => []];
foreach ($pdo->query("SELECT * FROM coding_secondary_reasons ORDER BY kind, sort_order, label")->fetchAll() as $r)
    if (isset($byKind[$r['kind']])) $byKind[$r['kind']][] = $r;

$pageTitle = 'Secondary reasons';
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-list-details me-2 text-primary"></i>Secondary reasons</h2>
        <div class="text-secondary small">Manage the <strong>RFI</strong> and <strong>Disregard</strong> reason lists shown to coders and validators. Editing or deleting a reason 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">
    <?php foreach ($KINDS as $kind => $kLabel): $list = $byKind[$kind]; $col = $kind==='rfi'?'orange':'danger'; ?>
    <div class="col-md-6"><div class="card">
        <div class="card-header py-2"><h3 class="card-title mb-0"><span class="badge bg-<?= $col ?>-lt me-1"><?= e($kLabel) ?></span>secondary reasons
            <span class="text-secondary fw-normal small">(<?= count($list) ?>)</span></h3></div>
        <div class="table-responsive"><table class="table table-vcenter card-table">
            <thead><tr><th>Reason</th><th class="w-1 text-nowrap">Status</th><th class="w-1 text-end">Actions</th></tr></thead>
            <tbody>
            <?php foreach ($list as $r): $active = $r['status']==='active'; ?>
                <tr>
                    <td><form method="POST" class="d-flex gap-1"><?= csrf_field() ?><input type="hidden" name="action" value="edit"><input type="hidden" name="id" value="<?= (int)$r['id'] ?>">
                        <input name="label" class="form-control form-control-sm" value="<?= e($r['label']) ?>" maxlength="120">
                        <button class="btn btn-sm btn-outline-primary" title="Save name"><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="id" value="<?= (int)$r['id'] ?>">
                            <button class="btn btn-sm btn-ghost-secondary" title="<?= $active?'Hide from dropdowns':'Show in dropdowns' ?>"><i class="ti ti-<?= $active?'eye-off':'eye' ?>"></i></button></form>
                        <form method="POST" class="d-inline" onsubmit="return confirm('Delete this reason? Existing charts keep their text.');"><?= 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 (!$list): ?><tr><td colspan="3" class="text-center text-secondary py-3">No <?= e($kLabel) ?> reasons yet.</td></tr><?php endif; ?>
            </tbody>
        </table></div>
        <div class="card-footer py-2"><form method="POST" class="d-flex gap-1"><?= csrf_field() ?><input type="hidden" name="action" value="add"><input type="hidden" name="kind" value="<?= e($kind) ?>">
            <input name="label" class="form-control form-control-sm" placeholder="Add a <?= e($kLabel) ?> reason…" maxlength="120" required>
            <button class="btn btn-sm btn-primary text-nowrap"><i class="ti ti-plus me-1"></i>Add</button>
        </form></div>
    </div></div>
    <?php endforeach; ?>
</div></div></div>
<?php require __DIR__ . '/../includes/footer.php'; ?>
