<?= $this->extend('layouts/panel') ?>
<?= $this->section('sidebar') ?>
<?= $this->include('panel/_sidebar') ?>
<?= $this->endSection() ?>

<?= $this->section('content') ?>

<div class="d-flex justify-content-between align-items-center mb-3">
    <h5 class="mb-0">Registered Users</h5>
    <div class="d-flex gap-2">
        <input type="text" id="searchFilter" class="form-control form-control-sm" style="width:200px;" placeholder="Search name/email/phone">
        <select id="roleFilter" class="form-select form-select-sm" style="width:150px;">
            <option value="">All roles</option>
            <option value="candidate">Candidate</option>
            <option value="agency_owner">Agency Owner</option>
            <option value="recruiter">Recruiter</option>
            <option value="super_admin">Super Admin</option>
        </select>
        <select id="statusFilter" class="form-select form-select-sm" style="width:130px;">
            <option value="">All statuses</option>
            <option value="active">Active</option>
            <option value="inactive">Inactive</option>
            <option value="banned">Banned</option>
            <option value="pending_verification">Pending</option>
        </select>
    </div>
</div>

<div class="li-card">
    <div class="table-responsive">
        <table class="table li-table mb-0">
            <thead><tr><th>Name</th><th>Role</th><th>Contact</th><th>Verified</th><th>Status</th><th>Joined</th><th></th></tr></thead>
            <tbody id="usersTable"></tbody>
        </table>
    </div>
    <div id="usersEmpty" class="text-center text-muted py-5 d-none">No users match your filters.</div>
</div>

<div class="modal fade" id="userActivityModal" tabindex="-1">
    <div class="modal-dialog modal-lg modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <div>
                    <h6 class="modal-title mb-0">Activity — <span id="uaUserName"></span></h6>
                    <div class="text-muted small" id="uaUserMeta"></div>
                </div>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body" id="uaBody">Loading...</div>
        </div>
    </div>
</div>

<?= $this->endSection() ?>

<?= $this->section('scripts') ?>
<script>
function roleBadge(role) {
    const map = { candidate: 'blue', agency_owner: 'green', recruiter: 'blue', super_admin: 'red', support_staff: 'gray' };
    return `<span class="li-pill li-pill-${map[role] || 'gray'}">${role.replace(/_/g,' ')}</span>`;
}
function statusBadge(status) {
    const map = { active: 'green', inactive: 'gray', banned: 'red', pending_verification: 'yellow' };
    return `<span class="li-pill li-pill-${map[status] || 'gray'}">${status.replace(/_/g,' ')}</span>`;
}

let searchTimer = null;
document.getElementById('searchFilter').addEventListener('input', () => {
    clearTimeout(searchTimer);
    searchTimer = setTimeout(loadUsers, 400);
});
document.getElementById('roleFilter').addEventListener('change', loadUsers);
document.getElementById('statusFilter').addEventListener('change', loadUsers);

async function loadUsers() {
    const params = new URLSearchParams();
    const q = document.getElementById('searchFilter').value;
    const role = document.getElementById('roleFilter').value;
    const status = document.getElementById('statusFilter').value;
    if (q) params.set('q', q);
    if (role) params.set('role', role);
    if (status) params.set('status', status);

    try {
        const res = await apiFetch(`/admin/users?${params.toString()}`);
        renderUsers(res.data || []);
    } catch (e) { showToast(e.message, true); }
}

function renderUsers(users) {
    const tbody = document.getElementById('usersTable');
    const empty = document.getElementById('usersEmpty');
    if (users.length === 0) { tbody.innerHTML = ''; empty.classList.remove('d-none'); return; }
    empty.classList.add('d-none');

    tbody.innerHTML = users.map(u => `
        <tr>
            <td>
                <span class="fw-semibold">${escapeHtml(u.name)}</span>
                ${u.company_name ? `<div class="text-muted small">${escapeHtml(u.company_name)}</div>` : ''}
            </td>
            <td>${roleBadge(u.role_slug)}</td>
            <td class="small">${escapeHtml(u.email)}<div class="text-muted">${escapeHtml(u.phone || '—')}</div></td>
            <td class="small">
                ${u.email_verified_at ? '<i class="bi bi-envelope-check text-success" title="Email verified"></i>' : '<i class="bi bi-envelope text-muted" title="Email not verified"></i>'}
                ${u.mobile_verified_at ? '<i class="bi bi-phone text-success ms-1" title="Mobile verified"></i>' : '<i class="bi bi-phone text-muted ms-1" title="Mobile not verified"></i>'}
            </td>
            <td>${statusBadge(u.status)}</td>
            <td class="text-muted small">${dateOnly(u.created_at)}</td>
            <td>
                <div class="dropdown">
                    <button class="btn btn-sm btn-li-ghost" data-bs-toggle="dropdown"><i class="bi bi-three-dots"></i></button>
                    <ul class="dropdown-menu dropdown-menu-end">
                        <li><a class="dropdown-item" href="#" onclick="viewUserActivity(${u.id}, '${escapeHtml(u.name)}');return false;"><i class="bi bi-clock-history me-1"></i>View Activity</a></li>
                        <li><hr class="dropdown-divider"></li>
                        ${u.status !== 'active' ? `<li><a class="dropdown-item" href="#" onclick="activateUser(${u.id});return false;">Activate</a></li>` : ''}
                        ${u.status === 'active' ? `<li><a class="dropdown-item" href="#" onclick="suspendUser(${u.id});return false;">Suspend</a></li>` : ''}
                        <li><a class="dropdown-item text-danger" href="#" onclick="banUser(${u.id});return false;">Ban</a></li>
                    </ul>
                </div>
            </td>
        </tr>
    `).join('');
}

async function suspendUser(id) {
    if (!confirm('Suspend this user? They will lose access.')) return;
    try { await apiFetch(`/admin/users/${id}/suspend`, { method: 'POST' }); showToast('User suspended.'); loadUsers(); }
    catch (e) { showToast(e.message, true); }
}
async function activateUser(id) {
    try { await apiFetch(`/admin/users/${id}/activate`, { method: 'POST' }); showToast('User activated.'); loadUsers(); }
    catch (e) { showToast(e.message, true); }
}
async function banUser(id) {
    if (!confirm('Ban this user permanently?')) return;
    try { await apiFetch(`/admin/users/${id}/ban`, { method: 'POST' }); showToast('User banned.'); loadUsers(); }
    catch (e) { showToast(e.message, true); }
}

function activityActionLabel(action) {
    return action.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase());
}

function activityDetails(row) {
    if (!row.metadata) return '';
    try {
        const meta = typeof row.metadata === 'string' ? JSON.parse(row.metadata) : row.metadata;
        const kv = Object.entries(meta).map(([k, v]) => `${k}: ${v}`).join(', ');
        return kv ? `<div class="text-muted small">${escapeHtml(kv)}</div>` : '';
    } catch (e) { return ''; }
}

async function viewUserActivity(userId, userName) {
    document.getElementById('uaUserName').textContent = userName;
    document.getElementById('uaUserMeta').textContent = '';
    document.getElementById('uaBody').innerHTML = 'Loading...';
    new bootstrap.Modal(document.getElementById('userActivityModal')).show();

    try {
        const res = await apiFetch(`/admin/users/${userId}/activity`);
        const { user, activity } = res.data;
        document.getElementById('uaUserMeta').textContent = `${user.email} · ${(user.role_slug || '').replace(/_/g,' ')}`;

        if (activity.length === 0) {
            document.getElementById('uaBody').innerHTML = '<p class="text-muted small mb-0">No recorded activity for this user yet.</p>';
            return;
        }

        document.getElementById('uaBody').innerHTML = `
            <div class="text-muted small mb-2">${res.meta.total} total event${res.meta.total === 1 ? '' : 's'}${res.meta.total > activity.length ? ` — showing the most recent ${activity.length}` : ''}</div>
            ${activity.map(row => `
                <div class="border-bottom py-2">
                    <div class="small fw-semibold">${escapeHtml(activityActionLabel(row.action))}</div>
                    ${activityDetails(row)}
                    <div class="text-muted" style="font-size:11px;">${formatDateTime(row.created_at)} ${row.ip_address ? '· ' + escapeHtml(row.ip_address) : ''}</div>
                </div>
            `).join('')}
        `;
    } catch (e) {
        document.getElementById('uaBody').innerHTML = `<div class="alert alert-danger">${e.message}</div>`;
    }
}

loadUsers();
</script>
<?= $this->endSection() ?>
