<?php
/**
 * Billing carriers & codes (billing.allocate) — a supervisor / manager maintains the three
 * dropdowns the biller uses while working a chart:
 *   - Carrier (insurance) — seeded ONCE from collection_raw; searchable; add/edit/hide/delete here.
 *   - Unbilled secondary reason — shown only when a biller marks a chart "Unbilled".
 *   - Comment — the biller's comment dropdown.
 * Stored in billing_dropdowns; worked charts 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 = ['carrier' => 'Carrier (insurance)', 'secondary_reason' => 'Unbilled secondary reason', 'comment' => 'Comment'];

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) > 200) { flash('error', 'Value is too long (max 200 chars).'); }
        else {
            try {
                $pdo->prepare("INSERT INTO billing_dropdowns (kind,label,sort_order,created_by) VALUES (?,?,0,?)")
                    ->execute([$kind, $label, $uid]);
                audit_log('billing.dropdown.add', 'billing_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 billing_dropdowns SET label=? WHERE id=?")->execute([$label, $id]);
                audit_log('billing.dropdown.edit', 'billing_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 billing_dropdowns SET status = IF(status='active','inactive','active') WHERE id=?")->execute([$id]);
        audit_log('billing.dropdown.toggle', 'billing_dropdowns', $id);
        flash('success', 'Value updated.');
    } elseif ($act === 'delete') {
        $id = (int) input('id');
        $pdo->prepare("DELETE FROM billing_dropdowns WHERE id=?")->execute([$id]);
        audit_log('billing.dropdown.delete', 'billing_dropdowns', $id);
        flash('success', 'Value deleted. (Worked charts keep their text.)');
    }
    redirect('/admin/billing-codes.php');
}

$byKind = ['carrier' => [], 'secondary_reason' => [], 'comment' => []];
foreach ($pdo->query("SELECT * FROM billing_dropdowns ORDER BY kind, label")->fetchAll() as $r)
    if (isset($byKind[$r['kind']])) $byKind[$r['kind']][] = $r;

/** One CRUD card for a dropdown kind. $searchable adds a client-side filter box (for the long carrier list). */
$card = function (string $kind, string $kLabel, array $list, string $col, bool $searchable) {
    ?>
    <div class="card mb-3"><div class="card-header py-2 d-flex align-items-center">
        <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>
        <?php if ($searchable): ?>
            <div class="ms-auto" style="max-width:280px"><input type="search" class="form-control form-control-sm js-bcfilter"
                data-kind="<?= e($kind) ?>" placeholder="Search <?= e($kLabel) ?>…"></div>
        <?php endif; ?>
    </div>
    <div class="table-responsive" style="<?= $searchable ? 'max-height:420px;overflow:auto' : '' ?>">
        <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 data-kind="<?= e($kind) ?>">
            <?php foreach ($list as $r): $active = $r['status']==='active'; ?>
                <tr data-label="<?= e(mb_strtolower($r['label'])) ?>">
                    <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="200">
                        <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 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 class="js-empty"><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="200" required>
        <button class="btn btn-sm btn-primary text-nowrap"><i class="ti ti-plus me-1"></i>Add</button>
    </form></div>
    </div>
    <?php
};

$pageTitle = 'Billing carriers & codes';
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>Billing carriers &amp; codes</h2>
        <div class="text-secondary small">Maintain the <strong>Carrier</strong> (insurance) list and the <strong>Unbilled secondary reason</strong> &amp; <strong>Comment</strong> dropdowns the biller picks from. Editing or deleting a value never changes charts already worked with it.</div>
    </div>
    <div class="col-auto"><a href="<?= e(url('/admin/billing-allocation.php')) ?>" class="btn btn-outline-secondary"><i class="ti ti-arrow-left me-1"></i>Allocate billing</a></div>
</div></div></div>
<div class="page-body"><div class="container-xl">
    <div class="row g-3">
        <div class="col-lg-7"><?php $card('carrier', $KINDS['carrier'], $byKind['carrier'], 'azure', true); ?></div>
        <div class="col-lg-5">
            <?php $card('secondary_reason', $KINDS['secondary_reason'], $byKind['secondary_reason'], 'orange', false); ?>
            <?php $card('comment', $KINDS['comment'], $byKind['comment'], 'green', false); ?>
        </div>
    </div>
</div></div>
<script>
document.querySelectorAll('.js-bcfilter').forEach(function (box) {
    box.addEventListener('input', function () {
        var q = this.value.trim().toLowerCase();
        var tbody = document.querySelector('tbody[data-kind="' + this.dataset.kind + '"]');
        if (!tbody) return;
        tbody.querySelectorAll('tr[data-label]').forEach(function (tr) {
            tr.style.display = (!q || tr.dataset.label.indexOf(q) !== -1) ? '' : 'none';
        });
    });
});
</script>
<?php require __DIR__ . '/../includes/footer.php'; ?>
