/**
 * =============================================================================
 * @package         Blue Raven (Free Version)
 * @Plugin URI      https://enterrahost.com/plugins/blue-raven
 * 
 * @Author          EnterraHost
 * @Author URI      https://enterrahost.com
 * @License         GPL-2.0-or-later
 *  
 * @Copyright       (c) 2025 EnterraHost
 * @Contents        Javascript for the The Mail Form Submission
 *
 * =============================================================================
 * 
 * || INDEX:
 * ||   - SUBMIT CUSTOM FORM 
 * ||   
 * =============================================================================
 */

/*
============================================================
    SUBMIT CUSTOM FORM 
============================================================
*/

jQuery(document).on('submit', '.blue-raven-form', function (e) {
    e.preventDefault();

    const $form = jQuery(this);
    const $messageTarget = $form.find('#br-mf-m');
    const $submitButton = $form.find('button[type="submit"]');
    const captchaToken = $form.find('.captcha-token-field').val();
    
    // Show loading state
    $submitButton.prop('disabled', true).text('Submitting...');
    $messageTarget.removeClass('success error').text('');

    // Find required fields
    const requiredFields = [];
    $form.find('[required]').each(function () {
        const name = jQuery(this).attr('name');
        if (name) requiredFields.push(name);
    });

    // Gather form data as regular object (not JSON string)
    const formDataObj = {};
    $form.find('input, textarea, select').each(function () {
        const name = jQuery(this).attr('name');
        if (name) {
            formDataObj[name] = jQuery(this).val();
        }
    });

    jQuery.ajax({
        url: BlueRavenAjax.ajax_url,
        method: 'POST',
        data: {
            action: 'blue_raven_submit_form',
            nonce: BlueRavenAjax.nonce,
            form_data: formDataObj,
            form_id: $form.data('form-id'),
            required_fields: requiredFields,
            captcha_token: captchaToken
        },
        success: function (response) {
            if (response.success) {
                $messageTarget.text(response.data || 'Thank you for your submission!')
                             .addClass('success');
                $form[0].reset();
            } else {
                $messageTarget.text(response.data || 'Please check your form and try again.')
                             .addClass('error');
            }
        },
        error: function (xhr, status, error) {
            $messageTarget.text('Network error: ' + error)
                         .addClass('error');
        },
        complete: function () {
            $submitButton.prop('disabled', false).text('Submit');
        }
    });
});