let _usersCache = {};
let _rolesCache = [];

$(function () {
    loadRoles();
    loadUsers();

    $('#btnAddUser').click(() => {
        clearForm();
        showModal();
    });

    $('#saveUser').click(saveUser);

    $(document).on('click', '.btn-edit', function () {
        const u = _usersCache[$(this).data('id')];
        if (!u) return;
        fillForm(u);
        showModal();
    });

    $(document).on('click', '.btn-delete', function () {
        deleteUser($(this).data('id'));
    });
});

function loadUsers() {
    $.get('api/users.php?action=list', function (res) {
        _usersCache = {};
        let html = '';
        res.data.forEach(u => {
            _usersCache[u.id] = u;
            html += '<tr>';
            html += '<td>' + escapeHtml(u.name) + '</td>';
            html += '<td>' + escapeHtml(u.email) + '</td>';
            html += '<td>' + escapeHtml(u.phone || '') + '</td>';
            html += '<td>' + escapeHtml(u.role_name) + '</td>';
            html += '<td>';
            html += '<span class="badge ' + (u.email_alerts_enabled == 1 ? 'bg-primary' : 'bg-secondary') + '">Email</span> ';
            html += '<span class="badge ' + (u.sms_alerts_enabled == 1 ? 'bg-success' : 'bg-secondary') + '">SMS</span>';
            html += '</td>';
            html += '<td>' + (u.is_active == 1 ? 'Active' : 'Inactive') + '</td>';
            if (window._CAN_EDIT || window._CAN_DELETE) {
                html += '<td>';
                if (window._CAN_EDIT) {
                    html += '<button class="btn btn-sm btn-warning btn-edit" data-id="' + u.id + '">Edit</button> ';
                }
                if (window._CAN_DELETE) {
                    html += '<button class="btn btn-sm btn-danger btn-delete" data-id="' + u.id + '">Delete</button>';
                }
                html += '</td>';
            }
            html += '</tr>';
        });
        $('#userTable').html(html);
    }, 'json');
}

function loadRoles() {
    $.get('api/users.php?action=roles', function (res) {
        _rolesCache = res.data;
        let html = '';
        res.data.forEach(r => {
            html += '<option value="' + r.id + '">' + escapeHtml(r.name) + '</option>';
        });
        $('#role_id').html(html);
        $(document).trigger('rolesLoaded');
    }, 'json');
}

function saveUser() {
    $.post('api/users.php?action=save', {
        id: $('#user_id').val(),
        name: $('#name').val(),
        email: $('#email').val(),
        phone: $('#phone').val(),
        email_alerts_enabled: $('#email_alerts_enabled').val(),
        sms_alerts_enabled: $('#sms_alerts_enabled').val(),
        password: $('#password').val(),
        role_id: $('#role_id').val(),
        is_active: $('#is_active').val()
    }, function (res) {
        if (res.status === 'error') {
            alert(res.message || 'Unable to save user');
            return;
        }
        loadUsers();
        hideModal();
    }, 'json');
}

function deleteUser(id) {
    if (!confirm('Delete user?')) return;
    $.post('api/users.php?action=delete', { id }, function () {
        loadUsers();
    });
}

function fillForm(u) {
    $('#user_id').val(u.id);
    $('#name').val(u.name);
    $('#email').val(u.email);
    $('#phone').val(u.phone || '');
    $('#email_alerts_enabled').val(u.email_alerts_enabled ?? 1);
    $('#sms_alerts_enabled').val(u.sms_alerts_enabled ?? 1);
    $('#is_active').val(u.is_active);
    selectRoleById(u.role_id);
}

function selectRoleById(roleId) {
    if (_rolesCache.length > 0) {
        $('#role_id').val(roleId);
    } else {
        // Roles not loaded yet — retry after load completes
        $(document).one('rolesLoaded', function () {
            $('#role_id').val(roleId);
        });
    }
}

function clearForm() {
    $('#user_id').val('');
    $('#name').val('');
    $('#email').val('');
    $('#phone').val('');
    $('#password').val('');
    $('#email_alerts_enabled').val('1');
    $('#sms_alerts_enabled').val('1');
    $('#is_active').val('1');
    if (_rolesCache.length > 0) {
        $('#role_id').val(_rolesCache[0].id);
    }
}

function showModal() {
    new bootstrap.Modal(document.getElementById('userModal')).show();
}

function hideModal() {
    bootstrap.Modal.getInstance(document.getElementById('userModal')).hide();
}

function escapeHtml(str) {
    var div = document.createElement('div');
    div.appendChild(document.createTextNode(str));
    return div.innerHTML;
}
