<?php
/**
 * AR claim-status & action-taken lists (ar.allocate) — a supervisor / manager adds, edits
 * (rename / activate-deactivate) and deletes the two customizable dropdowns used by AR users
 * while working claims. Stored in ar_dropdowns; worked claims keep their chosen value as text,
 * so editing/deleting a value never alters past work.
 */
require_once __DIR__ . '/../includes/config.php';
$user = require_login('internal');
$pdo  = db();
$uid  = (int) $user['id'];

$KINDS = ['claim_status' => 'Claim status', 'action_taken' => 'Action taken'];

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 list and enter a value.'); }
        elseif (mb_strlen($label) > 180)    { flash('error', 'Value is too long (max 180 chars).'); }
        else {
            $mx = $pdo->prepare("SELECT COALESCE(MAX(sort_order)+1,0) FROM ar_dropdowns WHERE kind=?");
            $mx->execute([$kind]); $so = (int) $mx->fetchColumn();
            try {
                $pdo->prepare("INSERT INTO ar_dropdowns (kind,label,sort_order,created_by) VALUES (?,?,?,?)")
                    ->execute([$kind, $label, $so, $uid]);
                audit_log('ar.dropdown.add', 'ar_dropdowns', null, null, ['kind'=>$kind,'label'=>$label]);
                flash('success', 'Value added.');
            } catch (Throwable $e) { flash('error', 'That value already exists in ' . $KINDS[$kind] . '.'); }
        }
    } elseif ($act === 'edit') {
        $id = (int) input('id'); $label = trim((string) input('label'));
        if ($id && $label !== '') {
            try {
                $pdo->prepare("UPDATE ar_dropdowns SET label=? WHERE id=?")->execute([$label, $id]);
                audit_log('ar.dropdown.edit', 'ar_dropdowns', $id, null, ['label'=>$label]);
                flash('success', 'Value renamed.');
            } catch (Throwable $e) { flash('error', 'A value with that name already exists.'); }
        } else flash('error', 'Value cannot be empty.');
    } elseif ($act === 'toggle') {
        $id = (int) input('id');
        $pdo->prepare("UPDATE ar_dropdowns SET status = IF(status='active','inactive','active') WHERE id=?")->execute([$id]);
        audit_log('ar.dropdown.toggle', 'ar_dropdowns', $id);
        flash('success', 'Value updated.');
    } elseif ($act === 'delete') {
        $id = (int) input('id');
        $pdo->prepare("DELETE FROM ar_dropdowns WHERE id=?")->execute([$id]);
        audit_log('ar.dropdown.delete', 'ar_dropdowns', $id);
        flash('success', 'Value deleted. (Worked claims keep their text.)');
    }
    redirect('/admin/ar-codes.php');
}

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

$pageTitle = 'AR claim-status & action lists';
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-check me-2 text-primary"></i>AR claim-status &amp; action lists</h2>
        <div class="text-secondary small">Manage the <strong>Claim status</strong> and <strong>Action taken</strong> dropdowns AR users pick from while working a claim. Editing or deleting a value never changes claims already worked with it.</div>
    </div>
    <div class="col-auto"><a href="<?= e(url('/admin/ar-allocation.php')) ?>" class="btn btn-outline-secondary"><i class="ti ti-arrow-left me-1"></i>AR allocation</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==='claim_status'?'azure':'green'; ?>
    <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>
            <span class="text-secondary fw-normal small">(<?= count($list) ?>)</span></h3></div>
        <div class="table-responsive"><table class="table table-vcenter table-sm card-table">
            <thead><tr><th>Value</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="180">
                        <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 dropdown':'Show in dropdown' ?>"><i class="ti ti-<?= $active?'eye-off':'eye' ?>"></i></button></form>
                        <form method="POST" class="d-inline" onsubmit="return confirm('Delete this value? Worked claims 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) ?> values 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) ?> value…" maxlength="180" 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'; ?>
