/**
 * API utility functions for AJAX calls
 */

const { ajaxUrl, ajaxNonce } = window.wpfmjData || {};

/**
 * Make AJAX request
 */
const makeRequest = async (action, data = {}) => {
    const formData = new FormData();
    formData.append('action', action);
    formData.append('nonce', ajaxNonce);
    
    Object.keys(data).forEach(key => {
        if (typeof data[key] === 'object') {
            formData.append(key, JSON.stringify(data[key]));
        } else {
            formData.append(key, data[key]);
        }
    });

    const response = await fetch(ajaxUrl, {
        method: 'POST',
        body: formData
    });

    const result = await response.json();

    if (!result.success) {
        throw new Error(result.data || 'Request failed');
    }

    return result.data;
};

/**
 * Fetch all WPForms
 */
export const fetchForms = async () => {
    return await makeRequest('wpfmj_get_forms');
};

/**
 * Fetch form fields
 */
export const fetchFormFields = async (formId) => {
    return await makeRequest('wpfmj_get_form_fields', { form_id: formId });
};

/**
 * Test Mailjet connection
 */
export const testMailjetConnection = async (apiKey, apiSecret) => {
    return await makeRequest('wpfmj_test_mailjet', {
        api_key: apiKey,
        api_secret: apiSecret
    });
};

/**
 * Fetch Mailjet lists
 */
export const fetchMailjetLists = async (apiKey, apiSecret) => {
    return await makeRequest('wpfmj_get_mailjet_lists', {
        api_key: apiKey,
        api_secret: apiSecret
    });
};

/**
 * Save automation
 */
export const saveAutomation = async (data, editId = 0) => {
    return await makeRequest('wpfmj_save_automation', {
        data: data,
        edit_id: editId
    });
};

/**
 * Fetch automation
 */
export const fetchAutomation = async (id) => {
    return await makeRequest('wpfmj_get_automation', { id });
};

/**
 * Toggle automation status
 */
export const toggleAutomation = async (id) => {
    return await makeRequest('wpfmj_toggle_automation', { id });
};

/**
 * Delete automation
 */
export const deleteAutomation = async (id) => {
    return await makeRequest('wpfmj_delete_automation', { id });
};

/**
 * Get dashboard data
 */
export const fetchDashboardData = async () => {
    return await makeRequest('wpfmj_get_dashboard_data');
};
