<?php
$filters = $filters ?? ['search' => '', 'status' => '', 'role' => ''];
$pagination = $pagination ?? ['page' => 1, 'pages' => 1, 'total' => 0, 'perPage' => 25];
$query = static function (int $page) use ($filters): string {
    $params = array_filter(['search' => $filters['search'], 'status' => $filters['status'], 'role' => $filters['role']], static fn($v) => $v !== '');
    $params['page'] = $page;
    return '?' . http_build_query($params);
};
?>
<section class="page-header">
    <div><p class="eyebrow">System</p><h1>Users</h1><p>Manage CRM accounts, roles and access status.</p></div>
    <a class="btn btn-primary" href="/crm/public/users/create">+ Create User</a>
</section>

<?php if (!empty($message)): ?><div class="alert alert-success" role="status"><?= htmlspecialchars($message, ENT_QUOTES, 'UTF-8') ?></div><?php endif; ?>
<?php if (!empty($error)): ?><div class="alert alert-danger" role="alert"><?= htmlspecialchars($error, ENT_QUOTES, 'UTF-8') ?></div><?php endif; ?>

<section class="card section-gap">
    <form method="get" class="filter-grid">
        <label class="form-field"><span>Search</span><input type="search" name="search" value="<?= htmlspecialchars($filters['search'], ENT_QUOTES, 'UTF-8') ?>" placeholder="Name, email or phone"></label>
        <label class="form-field"><span>Status</span><select name="status"><option value="">All statuses</option><option value="active" <?= $filters['status'] === 'active' ? 'selected' : '' ?>>Active</option><option value="inactive" <?= $filters['status'] === 'inactive' ? 'selected' : '' ?>>Inactive</option></select></label>
        <label class="form-field"><span>Role</span><select name="role"><option value="">All roles</option><?php foreach ($roles as $role): ?><option value="<?= htmlspecialchars($role['name'], ENT_QUOTES, 'UTF-8') ?>" <?= $filters['role'] === $role['name'] ? 'selected' : '' ?>><?= htmlspecialchars($role['display_name'], ENT_QUOTES, 'UTF-8') ?></option><?php endforeach; ?></select></label>
        <div class="filter-actions"><button class="btn btn-primary" type="submit">Filter</button><a class="btn btn-secondary" href="/crm/public/users">Clear</a></div>
    </form>
</section>

<section class="card section-gap">
    <div class="card-header"><div><h2>CRM accounts</h2><p><?= (int) $pagination['total'] ?> account(s) found.</p></div></div>
    <?php if (!$users): ?>
        <div class="empty-state"><strong>No users found</strong><p>Try changing your filters or create a new user.</p></div>
    <?php else: ?>
        <div class="table-wrap"><table class="data-table"><thead><tr><th>Name</th><th>Email</th><th>Role</th><th>Status</th><th>Last login</th><th>Actions</th></tr></thead><tbody>
        <?php foreach ($users as $user): ?>
            <tr>
                <td><strong><?= htmlspecialchars($user['full_name'], ENT_QUOTES, 'UTF-8') ?></strong><br><small class="muted"><?= htmlspecialchars((string) ($user['phone'] ?? ''), ENT_QUOTES, 'UTF-8') ?></small></td>
                <td><?= htmlspecialchars($user['email'], ENT_QUOTES, 'UTF-8') ?></td>
                <td><?= htmlspecialchars($user['role_names'] ?: 'No role', ENT_QUOTES, 'UTF-8') ?></td>
                <td><span class="badge <?= $user['status'] === 'active' ? 'badge-success' : 'badge-danger' ?>"><?= htmlspecialchars(ucfirst($user['status']), ENT_QUOTES, 'UTF-8') ?></span></td>
                <td><?= $user['last_login_at'] ? htmlspecialchars(date('d/m/Y H:i', strtotime($user['last_login_at'])), ENT_QUOTES, 'UTF-8') : 'Never' ?></td>
                <td><div class="action-row"><?php if (!empty($user['can_manage'])): ?><a class="btn btn-secondary btn-small" href="/crm/public/users/<?= (int) $user['id'] ?>/edit">Edit</a><?php endif; ?><?php if (!empty($user['can_manage']) && $user['status'] === 'active' && (int) $user['id'] !== (int) (\App\Core\Auth::id() ?? 0)): ?><form method="post" action="/crm/public/users/<?= (int) $user['id'] ?>/disable" class="inline-form" onsubmit="return confirm('Disable this user account?');"><input type="hidden" name="_csrf" value="<?= htmlspecialchars(\App\Core\Csrf::token(), ENT_QUOTES, 'UTF-8') ?>"><button class="btn btn-danger btn-small" type="submit">Disable</button></form><?php endif; ?></div></td>
            </tr>
        <?php endforeach; ?>
        </tbody></table></div>
        <?php if ($pagination['pages'] > 1): ?><nav class="pagination" aria-label="Users pagination">
            <a class="page-button" href="<?= $query(max(1, $pagination['page'] - 1)) ?>" aria-label="Previous">‹</a>
            <?php for ($p = 1; $p <= $pagination['pages']; $p++): ?><a class="page-button <?= $p === $pagination['page'] ? 'active' : '' ?>" href="<?= $query($p) ?>" <?= $p === $pagination['page'] ? 'aria-current="page"' : '' ?>><?= $p ?></a><?php endfor; ?>
            <a class="page-button" href="<?= $query(min($pagination['pages'], $pagination['page'] + 1)) ?>" aria-label="Next">›</a>
        </nav><?php endif; ?>
    <?php endif; ?>
</section>
