$(function () {
    loadProfile();

    $('#profileForm').on('submit', function (e) {
        e.preventDefault();
        saveProfile();
    });

    $('#passwordForm').on('submit', function (e) {
        e.preventDefault();
        changePassword();
    });
});

function showAlert(msg, type) {
    var $a = $('#alertBox');
    $a.removeClass('d-none alert-success alert-danger alert-warning').addClass('alert-' + (type || 'success')).text(msg);
}

function loadProfile() {
    $.get('api/users.php?action=profile', function (r) {
        if (r.status !== 'success') { showAlert(r.message, 'danger'); return; }
        var u = r.data;
        $('#profileName').val(u.name);
        $('#profileEmail').val(u.email);
        $('#profilePhone').val(u.phone || '');
        $('#profileRole').val(u.role_name || '');
    }, 'json');
}

function saveProfile() {
    $.post('api/users.php?action=save_profile', {
        name: $('#profileName').val().trim(),
        phone: $('#profilePhone').val().trim(),
        csrf_token: window.CSRF_TOKEN
    }, function (r) {
        if (r.status !== 'success') { showAlert(r.message, 'danger'); return; }
        showAlert('Profile updated', 'success');
    }, 'json').fail(function () { showAlert('Server error', 'danger'); });
}

function changePassword() {
    var current = $('#currentPassword').val();
    var newPass = $('#newPassword').val();
    var confirm = $('#confirmPassword').val();
    if (!current || !newPass || !confirm) { showAlert('All fields are required', 'warning'); return; }
    if (newPass !== confirm) { showAlert('New passwords do not match', 'warning'); return; }
    $.post('api/users.php?action=change_password', {
        current_password: current,
        new_password: newPass,
        csrf_token: window.CSRF_TOKEN
    }, function (r) {
        if (r.status !== 'success') { showAlert(r.message, 'danger'); return; }
        showAlert('Password changed successfully', 'success');
        $('#currentPassword, #newPassword, #confirmPassword').val('');
    }, 'json').fail(function () { showAlert('Server error', 'danger'); });
}
