<?php
require_once __DIR__ . '/../includes/auth.php';
require_once __DIR__ . '/../includes/csrf.php';
auth_require_super_admin();

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    csrf_verify();
    $do = $_POST['do'] ?? '';
    $id = (int)($_POST['id'] ?? 0);

    if ($do === 'toggle_active' && $id) {
        // Don't let super_admin deactivate themselves
        if ($id !== (int)auth_admin_id()) {
            db_exec('UPDATE admin_users SET active = 1 - active WHERE id = :id', ['id' => $id]);
        }
        header('Location: users.php'); exit;
    }
    if ($do === 'delete' && $id) {
        // Can't delete yourself, can't delete the last super_admin
        if ($id !== (int)auth_admin_id()) {
            $row = db_row('SELECT role FROM admin_users WHERE id=:id', ['id'=>$id]);
            $sa_count = (int)db_value("SELECT COUNT(*) FROM admin_users WHERE role='super_admin' AND active=1");
            if ($row && ($row['role'] !== 'super_admin' || $sa_count > 1)) {
                db_exec('DELETE FROM admin_users WHERE id = :id', ['id' => $id]);
            }
        }
        header('Location: users.php'); exit;
    }
}

$users = db_all('SELECT * FROM admin_users ORDER BY active DESC, role, created_at');

$page_title = 'Admin Users';
require __DIR__ . '/_guard.php';
?>

<style>
.atbl{width:100%;border-collapse:collapse;font-size:.875rem;}
.atbl th{padding:.55rem 1rem;background:var(--surface-alt);font-size:.7rem;text-transform:uppercase;letter-spacing:.05em;color:var(--ink-muted);border-bottom:2px solid var(--line);text-align:left;white-space:nowrap;}
.atbl td{padding:.7rem 1rem;border-bottom:1px solid var(--line);}
.role-pill{display:inline-block;padding:.15em .55em;border-radius:3px;font-size:.7rem;font-weight:700;text-transform:uppercase;letter-spacing:.04em;}
.role-super_admin{background:#312e81;color:#c7d2fe;}
.role-admin{background:#1f3a8a;color:#bfdbfe;}
.role-staff{background:#374151;color:#d1d5db;}
.inactive{color:var(--ink-muted);}
.atbl tr.inactive td{background:#fafafa;}
</style>

<?php
$settings_section = 'users';
require __DIR__ . '/_settings_open.php';
?>

<div class="settings-page-head" style="display:flex;justify-content:space-between;align-items:center;flex-wrap:wrap;gap:1rem;">
    <div>
        <h1>Admin Users</h1>
        <p class="crumb">Staff with access to the admin backend. Members are managed elsewhere.</p>
    </div>
    <a href="user-edit.php?action=add" class="btn">+ Add admin user</a>
</div>

<?php if (empty($users)): ?>
    <div class="card"><p class="muted" style="margin:0;">No admin users yet.</p></div>
<?php else: ?>
<div class="card" style="padding:0;overflow:auto;">
    <table class="atbl">
        <thead>
            <tr>
                <th>Name</th>
                <th>Email</th>
                <th>Role</th>
                <th>Status</th>
                <th>Last login</th>
                <th></th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($users as $u):
            $is_self = ((int)$u['id'] === (int)auth_admin_id());
            $is_active = (int)$u['active'] === 1;
        ?>
            <tr class="<?= $is_active ? '' : 'inactive' ?>">
                <td><strong><?= htmlspecialchars(trim($u['first_name'] . ' ' . $u['last_name']) ?: '—') ?></strong>
                    <?php if ($is_self): ?>
                        <span style="color:var(--brand-primary);font-size:.75rem;">(you)</span>
                    <?php endif; ?>
                </td>
                <td><?= htmlspecialchars($u['email']) ?></td>
                <td><span class="role-pill role-<?= htmlspecialchars($u['role']) ?>"><?= htmlspecialchars(str_replace('_',' ',$u['role'])) ?></span></td>
                <td>
                    <?php if ($is_active): ?>
                        <span class="tag tag-ok">Active</span>
                    <?php else: ?>
                        <span class="tag tag-err">Inactive</span>
                    <?php endif; ?>
                </td>
                <td class="muted" style="font-size:.82rem;">
                    <?= $u['last_login_at'] ? date('j M Y', strtotime($u['last_login_at'])) : '—' ?>
                </td>
                <td style="text-align:right;white-space:nowrap;">
                    <a href="user-edit.php?id=<?= $u['id'] ?>">Edit</a>

                    <?php if (!$is_self): ?>
                        &nbsp;
                        <form method="post" style="display:inline;" onsubmit="return confirm('<?= $is_active?'Deactivate':'Activate' ?> this admin?');">
                            <?= csrf_field() ?>
                            <input type="hidden" name="do" value="toggle_active">
                            <input type="hidden" name="id" value="<?= $u['id'] ?>">
                            <button type="submit" style="background:none;border:none;color:var(--brand-primary);cursor:pointer;font-size:.85rem;font-family:inherit;">
                                <?= $is_active ? 'Deactivate' : 'Activate' ?>
                            </button>
                        </form>
                    <?php endif; ?>
                </td>
            </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>
<?php endif; ?>

<?php require __DIR__ . '/_settings_close.php'; ?>

<?php require __DIR__ . '/_footer.php'; ?>