<?php
/**
 * Admin User Management View
 * Full listing with role filter, search, status toggle, and bulk actions.
 */
?>
<div class="container-fluid py-4 px-4">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <div>
            <h2 class="fw-bold font-outfit text-dark m-0"><i class="fa-solid fa-users-gear text-primary me-2"></i>User Management</h2>
            <p class="text-muted mb-0"><?= number_format($pagination['total'] ?? 0) ?> total users registered</p>
        </div>
        <a href="<?= APP_URL ?>/admin/users/create" class="btn btn-primary rounded-pill px-4 font-outfit fw-bold">
            <i class="fa-solid fa-user-plus me-2"></i>Add User
        </a>
    </div>

    <!-- Filters -->
    <div class="card border-0 shadow-sm p-4 mb-4">
        <form action="<?= APP_URL ?>/admin/users" method="GET" class="row g-3 align-items-end">
            <div class="col-md-4">
                <label class="form-label text-muted text-xs font-outfit fw-bold">Search</label>
                <div class="input-group">
                    <span class="input-group-text bg-white border-end-0"><i class="fa-solid fa-search text-muted"></i></span>
                    <input type="text" name="q" class="form-control border-start-0 ps-0" placeholder="Name, email..." value="<?= htmlspecialchars($q ?? '') ?>">
                </div>
            </div>
            <div class="col-md-2">
                <label class="form-label text-muted text-xs font-outfit fw-bold">Role</label>
                <select name="role" class="form-select">
                    <option value="">All Roles</option>
                    <?php foreach (['student', 'mentor', 'tutor', 'admin'] as $r): ?>
                        <option value="<?= $r ?>" <?= ($role_filter ?? '') === $r ? 'selected' : '' ?>><?= ucfirst($r) ?></option>
                    <?php endforeach; ?>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label text-muted text-xs font-outfit fw-bold">Status</label>
                <select name="status" class="form-select">
                    <option value="">All Status</option>
                    <option value="active" <?= ($q_status ?? '') === 'active' ? 'selected' : '' ?>>Active</option>
                    <option value="inactive" <?= ($q_status ?? '') === 'inactive' ? 'selected' : '' ?>>Inactive</option>
                    <option value="pending" <?= ($q_status ?? '') === 'pending' ? 'selected' : '' ?>>Pending</option>
                </select>
            </div>
            <div class="col-md-2">
                <label class="form-label text-muted text-xs font-outfit fw-bold">Sort By</label>
                <select name="sort" class="form-select">
                    <option value="newest" <?= ($sort ?? '') === 'newest' ? 'selected' : '' ?>>Newest First</option>
                    <option value="oldest" <?= ($sort ?? '') === 'oldest' ? 'selected' : '' ?>>Oldest First</option>
                    <option value="name_az" <?= ($sort ?? '') === 'name_az' ? 'selected' : '' ?>>Name A–Z</option>
                </select>
            </div>
            <div class="col-md-2">
                <button class="btn btn-primary rounded-pill w-100 font-outfit fw-bold"><i class="fa-solid fa-filter me-2"></i>Filter</button>
            </div>
        </form>
    </div>

    <!-- Bulk Actions Bar (shows when rows selected) -->
    <div class="alert alert-primary d-none mb-3 d-flex align-items-center gap-3 rounded-3" id="bulk-action-bar">
        <span class="fw-bold font-outfit" id="selected-count">0 selected</span>
        <form action="<?= APP_URL ?>/admin/users/bulk" method="POST" class="d-flex gap-2 ms-auto">
            <?= csrf_field() ?>
            <input type="hidden" name="user_ids" id="bulk-user-ids">
            <select name="action" class="form-select form-select-sm rounded-pill" style="width:auto;">
                <option value="activate">Activate</option>
                <option value="deactivate">Deactivate</option>
                <option value="delete">Delete</option>
            </select>
            <button type="submit" class="btn btn-sm btn-primary rounded-pill px-4 font-outfit fw-bold" onclick="prepareBulkIds()">Apply</button>
        </form>
    </div>

    <!-- Users Table -->
    <div class="card border-0 shadow-sm">
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover align-middle text-sm mb-0" id="users-table">
                    <thead class="table-light">
                        <tr>
                            <th class="border-0 ps-4 py-3"><input type="checkbox" id="select-all" class="form-check-input"></th>
                            <th class="border-0 font-outfit fw-bold text-muted">User</th>
                            <th class="border-0 font-outfit fw-bold text-muted">Role</th>
                            <th class="border-0 font-outfit fw-bold text-muted">Status</th>
                            <th class="border-0 font-outfit fw-bold text-muted">Joined</th>
                            <th class="border-0 font-outfit fw-bold text-muted">Last Active</th>
                            <th class="border-0 font-outfit fw-bold text-muted text-center">Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($users ?? [] as $user): ?>
                            <tr class="user-row" data-id="<?= $user['id'] ?>">
                                <td class="ps-4">
                                    <input type="checkbox" class="form-check-input row-checkbox" value="<?= $user['id'] ?>">
                                </td>
                                <td>
                                    <div class="d-flex align-items-center gap-3">
                                        <img src="<?= !empty($user['avatar']) ? htmlspecialchars($user['avatar']) : 'https://api.dicebear.com/7.x/initials/svg?seed=' . urlencode($user['first_name'] . ' ' . $user['last_name']) . '&backgroundColor=1a2940' ?>" 
                                             alt="<?= htmlspecialchars($user['first_name'] . ' ' . $user['last_name']) ?>" 
                                             class="rounded-circle" width="38" height="38" style="object-fit:cover;">
                                        <div>
                                            <span class="fw-bold font-outfit text-dark d-block"><?= htmlspecialchars($user['first_name'] . ' ' . $user['last_name']) ?></span>
                                            <small class="text-muted"><?= htmlspecialchars($user['email']) ?></small>
                                        </div>
                                    </div>
                                </td>
                                <td>
                                    <?php
                                    $roleColors = ['student' => 'primary', 'mentor' => 'success', 'tutor' => 'purple', 'admin' => 'danger'];
                                    $roleColor = $roleColors[$user['role']] ?? 'secondary';
                                    ?>
                                    <span class="badge bg-<?= $roleColor ?>-subtle text-<?= $roleColor ?> rounded-pill font-outfit fw-bold"><?= ucfirst($user['role']) ?></span>
                                </td>
                                <td>
                                    <?php
                                    $statusColors = ['active'=>'success','inactive'=>'secondary','pending'=>'warning','suspended'=>'danger'];
                                    $statusColor = $statusColors[$user['status']] ?? 'secondary';
                                    ?>
                                    <span class="badge bg-<?= $statusColor ?>-subtle text-<?= $statusColor ?> rounded-pill font-outfit">
                                        <?= ucfirst($user['status']) ?>
                                    </span>
                                </td>
                                <td class="text-muted"><?= formatDate($user['created_at']) ?></td>
                                <td class="text-muted"><?= !empty($user['last_login']) ? timeAgo($user['last_login']) : 'Never' ?></td>
                                <td class="text-center">
                                    <div class="d-flex justify-content-center gap-1">
                                        <a href="<?= APP_URL ?>/admin/users/<?= $user['id'] ?>" class="btn btn-sm btn-outline-primary rounded-pill px-2" title="View"><i class="fa-solid fa-eye"></i></a>
                                        <a href="<?= APP_URL ?>/admin/users/<?= $user['id'] ?>/edit" class="btn btn-sm btn-outline-secondary rounded-pill px-2" title="Edit"><i class="fa-solid fa-pen"></i></a>
                                        <form action="<?= APP_URL ?>/admin/users/<?= $user['id'] ?>/toggle" method="POST" class="d-inline">
                                            <?= csrf_field() ?>
                                            <button class="btn btn-sm btn-outline-<?= ($user['status'] === 'active') ? 'warning' : 'success' ?> rounded-pill px-2" title="<?= ($user['status'] === 'active') ? 'Deactivate' : 'Activate' ?>">
                                                <i class="fa-solid fa-<?= ($user['status'] === 'active') ? 'ban' : 'circle-check' ?>"></i>
                                            </button>
                                        </form>
                                        <form action="<?= APP_URL ?>/admin/users/<?= $user['id'] ?>/delete" method="POST" class="d-inline" onsubmit="return confirm('Delete this user? This cannot be undone.')">
                                            <?= csrf_field() ?>
                                            <button class="btn btn-sm btn-outline-danger rounded-pill px-2" title="Delete"><i class="fa-solid fa-trash"></i></button>
                                        </form>
                                    </div>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                        <?php if (empty($users)): ?>
                            <tr><td colspan="7" class="text-center py-5 text-muted">No users found matching your criteria.</td></tr>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
    </div>

    <!-- Pagination -->
    <?php if (($pagination['total_pages'] ?? 1) > 1): ?>
        <nav class="mt-4 d-flex justify-content-center">
            <ul class="pagination pagination-sm gap-1">
                <?php for ($p = 1; $p <= $pagination['total_pages']; $p++): ?>
                    <li class="page-item <?= $p == ($pagination['current_page'] ?? 1) ? 'active' : '' ?>">
                        <a class="page-link rounded-circle border-0 shadow-sm" href="<?= APP_URL ?>/admin/users?page=<?= $p ?>&q=<?= urlencode($q ?? '') ?>&role=<?= urlencode($role_filter ?? '') ?>"><?= $p ?></a>
                    </li>
                <?php endfor; ?>
            </ul>
        </nav>
    <?php endif; ?>
</div>

<script>
document.addEventListener('DOMContentLoaded', function () {
    const selectAll = document.getElementById('select-all');
    const checkboxes = document.querySelectorAll('.row-checkbox');
    const bulkBar = document.getElementById('bulk-action-bar');
    const selectedCount = document.getElementById('selected-count');

    function updateBulkBar() {
        const checked = document.querySelectorAll('.row-checkbox:checked');
        if (checked.length > 0) {
            bulkBar.classList.remove('d-none');
            selectedCount.textContent = checked.length + ' selected';
        } else {
            bulkBar.classList.add('d-none');
        }
    }

    selectAll.addEventListener('change', function () {
        checkboxes.forEach(cb => { cb.checked = this.checked; });
        updateBulkBar();
    });
    checkboxes.forEach(cb => cb.addEventListener('change', updateBulkBar));

    window.prepareBulkIds = function () {
        const ids = Array.from(document.querySelectorAll('.row-checkbox:checked')).map(cb => cb.value);
        document.getElementById('bulk-user-ids').value = ids.join(',');
    };
});
</script>
