let allUsers = [];


document.addEventListener('DOMContentLoaded', () => {
    const userJson = localStorage.getItem('user');
    if (!userJson) {
        window.location.href = '../index.html';
        return;
    }
    const user = JSON.parse(userJson);

    // HARD GUARD: only Director can access this page
    if (user.Role !== 'Director') {
        alert('You are not allowed to access User Management.');
        window.location.href = 'dashboard.html';
        return;
    }

    const fullEl = document.getElementById('user-fullname');
    const roleEl = document.getElementById('user-role');
    const initEl = document.getElementById('user-initial');
    if (fullEl) fullEl.textContent = user.FullName || '';
    if (roleEl) roleEl.textContent = user.Role || '';
    if (initEl && user.FullName) initEl.textContent = user.FullName.charAt(0).toUpperCase();

    // mobile sidebar
    const mobileToggle = document.getElementById('mobile-toggle');
    const sidebar = document.getElementById('sidebar');
    const overlay = document.getElementById('sidebar-overlay');

    if (sidebar) {
        if (window.innerWidth < 1024) {
            sidebar.classList.add('-translate-x-full');
        } else {
            sidebar.classList.remove('-translate-x-full');
        }
    }

    if (mobileToggle && sidebar && overlay) {
        mobileToggle.addEventListener('click', () => {
            sidebar.classList.toggle('-translate-x-full');
            overlay.classList.toggle('hidden');
        });

        overlay.addEventListener('click', () => {
            sidebar.classList.add('-translate-x-full');
            overlay.classList.add('hidden');
        });

        window.addEventListener('resize', () => {
            if (window.innerWidth >= 1024) {
                sidebar.classList.remove('-translate-x-full');
                overlay.classList.add('hidden');
            } else {
                sidebar.classList.add('-translate-x-full');
            }
        });
    }

    // form buttons
    document.getElementById('BtnNewUser')?.addEventListener('click', e => {
        e.preventDefault();
        clearForm();
    });

    document.getElementById('BtnClearForm')?.addEventListener('click', e => {
        e.preventDefault();
        clearForm();
    });

    document.getElementById('BtnSaveUser')?.addEventListener('click', e => {
        e.preventDefault();
        saveUser();
    });

    document.getElementById('BtnResetPassword')?.addEventListener('click', e => {
        e.preventDefault();
        resetPassword();
    });

    const search = document.getElementById('TxtSearchUsers');
    if (search) {
        search.addEventListener('input', () => {
            filterUsers(search.value.trim().toLowerCase());
        });
    }

    loadUsers();
});


function logout() {
    localStorage.removeItem('user');
    window.location.replace('../index.html');
}

async function loadUsers() {
    try {
        const res = await fetch('../api/users.php?action=list');
        const data = await res.json();
        allUsers = Array.isArray(data) ? data : [];
        renderUsers(allUsers);
    } catch (err) {
        console.error('Failed to load users', err);
    }
}

function renderUsers(list) {
    const tbody = document.getElementById('UsersTableBody');
    const countEl = document.getElementById('UsersCount');
    if (countEl) countEl.textContent = list.length;

    if (!tbody) return;

    if (!list.length) {
        tbody.innerHTML = `
            <tr>
                <td colspan="7" class="py-6 text-center text-gray-400 text-sm">
                    No users found
                </td>
            </tr>`;
        return;
    }

    tbody.innerHTML = list.map(u => {
        const webBadge = u.AllowWebAccess == 1
            ? '<span class="inline-flex items-center px-2 py-1 rounded-full bg-green-50 text-green-600 text-[11px] font-semibold"><i class="fas fa-check mr-1 text-[9px]"></i>Allowed</span>'
            : '<span class="inline-flex items-center px-2 py-1 rounded-full bg-gray-100 text-gray-500 text-[11px] font-semibold"><i class="fas fa-ban mr-1 text-[9px]"></i>Disabled</span>';

        const safeName = (u.FullName || '').replace(/'/g, "\\'");

        return `
            <tr class="hover:bg-[#f6f9fc] transition-colors">
                <td class="px-4 py-3 text-xs text-gray-500">${u.Id}</td>
                <td class="px-4 py-3 font-semibold text-gray-800">${u.FullName}</td>
                <td class="px-4 py-3 text-gray-700">${u.Username}</td>
                <td class="px-4 py-3 text-gray-500 text-[11px]">${u.Email}</td>
                <td class="px-4 py-3 text-gray-700 font-semibold">${u.Role}</td>
                <td class="px-4 py-3 text-center">${webBadge}</td>
                <td class="px-4 py-3 text-center">
                    <div class="inline-flex items-center justify-end gap-1">
                        <button class="w-7 h-7 rounded-md bg-gray-50 text-gray-500 hover:bg-gray-100 hover:text-[#3baa15] text-xs"
                                title="Edit user"
                                onclick="editUser(${u.Id})">
                            <i class="fas fa-pen"></i>
                        </button>
                        <button class="w-7 h-7 rounded-md bg-gray-50 text-gray-500 hover:bg-gray-100 hover:text-gray-800 text-xs"
                                title="Reset password"
                                onclick="resetPasswordPrompt(${u.Id})">
                            <i class="fas fa-key"></i>
                        </button>
                        <button class="w-7 h-7 rounded-md bg-gray-50 text-gray-500 hover:bg-red-50 hover:text-red-600 text-xs"
                                title="Toggle web access"
                                onclick="toggleWebAccess(${u.Id})">
                            <i class="fas fa-user-slash"></i>
                        </button>
                        <button class="w-7 h-7 rounded-md bg-gray-50 text-gray-400 hover:bg-red-50 hover:text-red-600 text-xs"
                                title="Delete user"
                                onclick="deleteUser(${u.Id}, '${safeName}')">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </td>
            </tr>
        `;
    }).join('');
}

function filterUsers(term) {
    if (!term) {
        renderUsers(allUsers);
        return;
    }
    const filtered = allUsers.filter(u =>
        (u.FullName && u.FullName.toLowerCase().includes(term)) ||
        (u.Username && u.Username.toLowerCase().includes(term)) ||
        (u.Email && u.Email.toLowerCase().includes(term)) ||
        (u.Role && u.Role.toLowerCase().includes(term))
    );
    renderUsers(filtered);
}

function clearForm() {
    document.getElementById('UserId').value = '';
    document.getElementById('TxtFullName').value = '';
    document.getElementById('TxtUsername').value = '';
    document.getElementById('TxtEmail').value = '';
    document.getElementById('CmbRole').value = '';
    document.getElementById('ChkWebAccess').checked = false;
    document.getElementById('TxtPassword').value = '';
    document.getElementById('FormMode').textContent = 'New';
    document.getElementById('BtnResetPassword').classList.add('hidden');
}

function editUser(id) {
    const u = allUsers.find(x => Number(x.Id) === Number(id));
    if (!u) return;

    document.getElementById('UserId').value = u.Id;
    document.getElementById('TxtFullName').value = u.FullName || '';
    document.getElementById('TxtUsername').value = u.Username || '';
    document.getElementById('TxtEmail').value = u.Email || '';
    document.getElementById('CmbRole').value = u.Role || '';
    document.getElementById('ChkWebAccess').checked = (u.AllowWebAccess == 1);
    document.getElementById('TxtPassword').value = '';
    document.getElementById('FormMode').textContent = 'Edit';
    document.getElementById('BtnResetPassword').classList.remove('hidden');
}

async function saveUser() {
    const id = document.getElementById('UserId').value || '';
    const fullName = document.getElementById('TxtFullName').value.trim();
    const username = document.getElementById('TxtUsername').value.trim();
    const email = document.getElementById('TxtEmail').value.trim();
    const role = document.getElementById('CmbRole').value;
    const allowWeb = document.getElementById('ChkWebAccess').checked ? 1 : 0;
    const password = document.getElementById('TxtPassword').value;

    if (!fullName || !username || !email || !role) {
        alert('Full name, username, email and role are required.');
        return;
    }

    if (!id && !password) {
        alert('Initial password is required for a new user.');
        return;
    }

    const payload = new FormData();
    payload.append('action', 'save');
    if (id) payload.append('id', id);
    payload.append('fullName', fullName);
    payload.append('username', username);
    payload.append('email', email);
    payload.append('role', role);
    payload.append('allowWeb', allowWeb);
    if (password) payload.append('password', password);

    try {
        const res = await fetch('../api/users.php', {
            method: 'POST',
            body: payload
        });
        const data = await res.json();

        if (!res.ok || !data.success) {
            console.error('Save user failed', data);
            alert(data.message || 'Failed to save user.');
            return;
        }

        clearForm();
        await loadUsers();
    } catch (err) {
        console.error('Save user error', err);
        alert('Error saving user.');
    }
}

function resetPasswordPrompt(id) {
    const newPwd = prompt('Enter new password for this user:');
    if (!newPwd) return;
    resetPassword(id, newPwd);
}

async function resetPassword(idParam, newPwdParam) {
    const id = idParam || document.getElementById('UserId').value;
    if (!id) {
        alert('Select a user first.');
        return;
    }

    const newPassword = newPwdParam || prompt('Enter new password:');
    if (!newPassword) return;

    const payload = new FormData();
    payload.append('action', 'reset_password');
    payload.append('id', id);
    payload.append('password', newPassword);

    try {
        const res = await fetch('../api/users.php', {
            method: 'POST',
            body: payload
        });
        const data = await res.json();

        if (!res.ok || !data.success) {
            console.error('Reset password failed', data);
            alert(data.message || 'Failed to reset password.');
            return;
        }

        alert('Password reset successfully.');
        document.getElementById('TxtPassword').value = '';
    } catch (err) {
        console.error('Reset password error', err);
        alert('Error resetting password.');
    }
}

async function toggleWebAccess(id) {
    const u = allUsers.find(x => Number(x.Id) === Number(id));
    if (!u) return;

    const newVal = u.AllowWebAccess == 1 ? 0 : 1;

    const payload = new FormData();
    payload.append('action', 'toggle_web');
    payload.append('id', id);
    payload.append('allowWeb', newVal);

    try {
        const res = await fetch('../api/users.php', {
            method: 'POST',
            body: payload
        });
        const data = await res.json();

        if (!res.ok || !data.success) {
            console.error('Toggle web access failed', data);
            alert(data.message || 'Failed to update web access.');
            return;
        }

        await loadUsers();
    } catch (err) {
        console.error('Toggle web access error', err);
        alert('Error updating web access.');
    }
}

async function deleteUser(id, name) {
    if (!id) return;

    const confirmed = confirm(
        `Are you sure you want to permanently delete this user?\n\nID: ${id}\nName: ${name || ''}\n\nThis cannot be undone.`
    );
    if (!confirmed) return;

    const payload = new FormData();
    payload.append('action', 'delete');
    payload.append('id', id);

    try {
        const res = await fetch('../api/users.php', {
            method: 'POST',
            body: payload
        });
        const data = await res.json();

        if (!res.ok || !data.success) {
            console.error('Delete user failed', data);
            alert(data.message || 'Failed to delete user.');
            return;
        }

        await loadUsers();
    } catch (err) {
        console.error('Delete user error', err);
        alert('Error deleting user.');
    }
}

// expose for inline handlers
window.editUser = editUser;
window.resetPasswordPrompt = resetPasswordPrompt;
window.toggleWebAccess = toggleWebAccess;
window.deleteUser = deleteUser;
