<!-- ── Page Header ──────────────────────────────────────────────────────────── -->
<div class="page-header">
    <div>
        <h1>Staff & Users</h1>
        <p>Manage staff accounts and their access roles.</p>
    </div>
    <?php if (\Core\Auth::can('user.create')): ?>
    <a href="<?= url('users/create') ?>" class="btn btn-accent">
        <i class="bi bi-person-plus-fill me-1"></i> Add Staff User
    </a>
    <?php endif; ?>
</div>

<!-- ── Role summary chips ────────────────────────────────────────────────────── -->
<div class="d-flex flex-wrap gap-2 mb-4">
    <?php foreach ($roles as $role): ?>
    <span class="badge rounded-pill px-3 py-2" style="background:var(--accent-soft);color:var(--accent);font-size:.78rem;font-weight:600;">
        <?= e($role['label']) ?>
    </span>
    <?php endforeach; ?>
</div>

<!-- ── Users table ───────────────────────────────────────────────────────────── -->
<div class="card">
    <div class="card-body p-0">
        <?php if (empty($users)): ?>
        <div class="p-5 text-center text-secondary">
            <i class="bi bi-people fs-1 d-block mb-2 opacity-25"></i>
            No staff users yet.
            <?php if (\Core\Auth::can('user.create')): ?>
            <a href="<?= url('users/create') ?>" class="d-block mt-2 text-accent">Add the first user</a>
            <?php endif; ?>
        </div>
        <?php else: ?>
        <div class="table-responsive">
            <table class="table mb-0">
                <thead>
                    <tr>
                        <th>User</th>
                        <th>Role</th>
                        <th>Phone</th>
                        <th>Last Login</th>
                        <th>Status</th>
                        <th class="text-end">Actions</th>
                    </tr>
                </thead>
                <tbody>
                    <?php foreach ($users as $user): ?>
                    <?php $isSelf = ($user['id'] === \Core\Auth::id()); ?>
                    <tr>
                        <td>
                            <div class="d-flex align-items-center gap-3">
                                <div class="avatar-circle" style="width:36px;height:36px;font-size:.85rem;border-radius:10px;background:var(--accent);color:#fff;display:flex;align-items:center;justify-content:center;font-weight:700;flex-shrink:0;">
                                    <?= strtoupper(substr($user['name'], 0, 1)) ?>
                                </div>
                                <div>
                                    <div class="fw-600" style="font-size:.875rem;">
                                        <?= e($user['name']) ?>
                                        <?php if ($isSelf): ?>
                                        <span class="badge ms-1" style="background:var(--accent-soft);color:var(--accent);font-size:.65rem;">You</span>
                                        <?php endif; ?>
                                    </div>
                                    <div class="text-secondary" style="font-size:.78rem;"><?= e($user['email']) ?></div>
                                </div>
                            </div>
                        </td>
                        <td>
                            <span class="status-badge" style="background:#f0f4ff;color:#2563eb;">
                                <?= e($user['role_label']) ?>
                            </span>
                        </td>
                        <td style="font-size:.85rem;"><?= e($user['phone'] ?: '—') ?></td>
                        <td style="font-size:.8rem;color:var(--text-secondary);">
                            <?= $user['last_login'] ? format_datetime($user['last_login']) : '—' ?>
                            <?php if ($user['locked_until'] && strtotime($user['locked_until']) > time()): ?>
                            <div class="text-danger" style="font-size:.72rem;"><i class="bi bi-lock-fill me-1"></i>Locked</div>
                            <?php endif; ?>
                        </td>
                        <td>
                            <?php if ($user['is_active']): ?>
                            <span class="status-badge" style="background:#f0fdf4;color:#16a34a;">Active</span>
                            <?php else: ?>
                            <span class="status-badge" style="background:#fef2f2;color:#dc2626;">Inactive</span>
                            <?php endif; ?>
                        </td>
                        <td class="text-end">
                            <div class="d-flex justify-content-end gap-1">
                                <?php if (\Core\Auth::can('user.edit')): ?>
                                <a href="<?= url('users/'.$user['id'].'/edit') ?>" class="btn btn-sm btn-outline-secondary" title="Edit">
                                    <i class="bi bi-pencil"></i>
                                </a>

                                <?php if (!$isSelf): ?>
                                <!-- Toggle active -->
                                <button class="btn btn-sm <?= $user['is_active'] ? 'btn-outline-warning' : 'btn-outline-success' ?>"
                                        title="<?= $user['is_active'] ? 'Deactivate' : 'Activate' ?>"
                                        onclick="toggleUser(<?= $user['id'] ?>, this)">
                                    <i class="bi bi-<?= $user['is_active'] ? 'pause-circle' : 'play-circle' ?>"></i>
                                </button>

                                <?php if ($user['locked_until'] && strtotime($user['locked_until']) > time()): ?>
                                <form method="POST" action="<?= url('users/'.$user['id'].'/reset-lock') ?>" class="d-inline">
                                    <?= csrf_field() ?>
                                    <button type="submit" class="btn btn-sm btn-outline-info" title="Clear Login Lock">
                                        <i class="bi bi-unlock"></i>
                                    </button>
                                </form>
                                <?php endif; ?>
                                <?php endif; ?>
                                <?php endif; ?>

                                <?php if (\Core\Auth::can('user.delete') && !$isSelf): ?>
                                <form method="POST" action="<?= url('users/'.$user['id'].'/delete') ?>"
                                      onsubmit="return confirm('Delete user <?= addslashes(e($user['name'])) ?>? This cannot be undone.')">
                                    <?= csrf_field() ?>
                                    <button type="submit" class="btn btn-sm btn-outline-danger" title="Delete">
                                        <i class="bi bi-trash"></i>
                                    </button>
                                </form>
                                <?php endif; ?>
                            </div>
                        </td>
                    </tr>
                    <?php endforeach; ?>
                </tbody>
            </table>
        </div>
        <?php endif; ?>
    </div>
</div>

<?php if (!empty($pagination) && $pagination['total_pages'] > 1): ?>
<nav class="mt-3">
    <ul class="pagination justify-content-center">
        <?php for ($p = 1; $p <= $pagination['total_pages']; $p++): ?>
        <li class="page-item <?= $p === $pagination['current_page'] ? 'active' : '' ?>">
            <a class="page-link" href="?page=<?= $p ?>"><?= $p ?></a>
        </li>
        <?php endfor; ?>
    </ul>
</nav>
<?php endif; ?>

<?php ob_start(); ?>
<script>
async function toggleUser(id, btn) {
    const fd = new FormData();
    fd.append('_csrf', '<?= csrf_token() ?>');
    const res  = await fetch(`<?= url('users') ?>/${id}/toggle`, { method: 'POST', body: fd });
    const data = await res.json();
    if (data.success) location.reload();
}
</script>
<?php $extraJs = ob_get_clean(); ?>
