/**
 * Global Admin Scripts
 */

console.log('CMS Admin Main JS loaded');

// Helper to handle AJAX form submissions with confirmation or loading state
window.handleFormAjax = async (formEl, options = {}) => {
    const { 
        confirmMessage = null, 
        onSuccess = null, 
        onError = null,
        loaderBtn = null
    } = options;

    if (confirmMessage && !confirm(confirmMessage)) {
        return false;
    }

    const formData = new FormData(formEl);
    const data = Object.fromEntries(formData.entries());
    const originalBtnHtml = loaderBtn ? loaderBtn.innerHTML : null;

    try {
        if (loaderBtn) {
            loaderBtn.disabled = true;
            loaderBtn.innerHTML = '<i class="fas fa-spinner fa-spin me-1"></i>Processing...';
        }

        const response = await fetch(formEl.action, {
            method: formEl.method || 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify(data)
        });

        const result = await response.json();

        if (result.success) {
            if (onSuccess) onSuccess(result);
            else showToast('Success', result.message || 'Operation successful', 'success');
        } else {
            if (onError) onError(result);
            else showToast('Error', result.message || 'Operation failed', 'error');
        }
    } catch (error) {
        console.error('AJAX Error:', error);
        showToast('Error', 'A network error occurred', 'error');
    } finally {
        if (loaderBtn) {
            loaderBtn.disabled = false;
            loaderBtn.innerHTML = originalBtnHtml;
        }
    }
};
