<div class="header">
    <h1>Users</h1>
</div>
<form method="get" action="<?= base_url('admin/users') ?>" style="display: flex; gap: 1rem; align-items: flex-end; flex-wrap: wrap; margin-bottom: 1.5rem;">
    <div>
        <label for="q">Search (phone, username, name)</label>
        <input type="text" name="q" id="q" value="<?= esc($filter_q ?? '') ?>" placeholder="Search…" style="min-width: 180px;">
    </div>
    <div>
        <label for="role">Role</label>
        <select name="role" id="role">
            <option value="">All</option>
            <option value="user" <?= ($filter_role ?? '') === 'user' ? 'selected' : '' ?>>User</option>
            <option value="driver" <?= ($filter_role ?? '') === 'driver' ? 'selected' : '' ?>>Driver</option>
        </select>
    </div>
    <div>
        <label for="status">Status</label>
        <select name="status" id="status">
            <option value="">All</option>
            <option value="active" <?= ($filter_status ?? '') === 'active' ? 'selected' : '' ?>>Active</option>
            <option value="inactive" <?= ($filter_status ?? '') === 'inactive' ? 'selected' : '' ?>>Inactive</option>
        </select>
    </div>
    <button type="submit" class="btn btn-primary">Filter</button>
    <?php if (($filter_q ?? '') !== '' || ($filter_role ?? '') !== '' || ($filter_status ?? '') !== ''): ?>
    <a href="<?= base_url('admin/users') ?>" class="btn btn-secondary">Clear</a>
    <?php endif ?>
</form>
<table>
    <thead>
        <tr><th>ID</th><th>Phone</th><th>Role</th><th>Status</th><th>Action</th></tr>
    </thead>
    <tbody>
        <?php foreach ($users as $u): ?>
        <tr>
            <td><?= $u->id ?></td>
            <td><?= esc($u->phone) ?></td>
            <td><?= esc($u->role ?? 'user') ?></td>
            <td>
                <span style="display: inline-block; padding: 0.25rem 0.75rem; background: <?= ($u->jambo_status ?? 'active') === 'active' ? '#d1fae5' : '#fee2e2' ?>; color: <?= ($u->jambo_status ?? 'active') === 'active' ? '#065f46' : '#991b1b' ?>; border-radius: 9999px; font-size: 0.75rem; font-weight: 600;">
                    <?= esc($u->jambo_status ?? 'active') ?>
                </span>
            </td>
            <td>
                <a href="<?= base_url('admin/users/' . $u->id) ?>" class="btn btn-primary" style="margin-right: 0.25rem;">View</a>
                <?php if (($u->role ?? '') !== 'admin'): ?>
                <form method="post" action="<?= base_url('admin/users/' . $u->id . '/toggle') ?>" style="display:inline;">
                    <input type="hidden" name="<?= csrf_token() ?>" value="<?= csrf_hash() ?>">
                    <button type="submit" class="btn btn-secondary"><?= ($u->jambo_status ?? 'active') === 'active' ? 'Deactivate' : 'Activate' ?></button>
                </form>
                <?php endif ?>
            </td>
        </tr>
        <?php endforeach ?>
    </tbody>
</table>