/**
 * PC Form Builder Public Scripts
 *
 * Frontend JavaScript functionality for form handling.
 *
 * @package PCFormBuilder
 */

(function($) {
    'use strict';

    var PCFB_Public = {
        init: function() {
            this.initForms();
        },

        initForms: function() {
            var self = this;

            $(document).on('submit', '.pcfb-form', function(e) {
                e.preventDefault();
                self.handleFormSubmit($(this));
            });
        },

        handleFormSubmit: function($form) {
            var self = this;
            var formId = $form.data('form-id');
            var $submitButton = $form.find('.pcfb-submit-button');
            var $submitText = $form.find('.pcfb-submit-text');
            var $submitLoader = $form.find('.pcfb-submit-loader');
            var $successMessage = $form.closest('.pcfb-form-container').find('.pcfb-success-message');
            var $errorMessage = $form.closest('.pcfb-form-container').find('.pcfb-error-message');

            $form.find('.pcfb-form-group').removeClass('error');
            $form.find('.pcfb-field-error').text('');
            $errorMessage.hide().find('.pcfb-message-text').text('');
            $successMessage.hide();

            var formData = $form.serialize();
            var ajaxData = {
                action: 'pcfb_submit_form',
                form_id: formId,
                form_data: {},
                nonce: pcfbVars.nonce
            };

            $form.find('input, textarea, select').each(function() {
                var $field = $(this);
                var name = $field.attr('name');
                if (name && name !== 'action' && name !== 'form_id' && name !== 'pcfb_nonce') {
                    if ($field.is(':checkbox')) {
                        if ($field.is(':checked')) {
                            if (!ajaxData.form_data[name]) {
                                ajaxData.form_data[name] = [];
                            }
                            ajaxData.form_data[name].push($field.val());
                        }
                    } else if ($field.is(':radio')) {
                        if ($field.is(':checked')) {
                            ajaxData.form_data[name] = $field.val();
                        }
                    } else {
                        ajaxData.form_data[name] = $field.val();
                    }
                }
            });

            $form.addClass('loading');
            $submitButton.prop('disabled', true);
            $submitText.hide();
            $submitLoader.show();

            $.ajax({
                url: pcfbVars.ajaxurl,
                type: 'POST',
                data: ajaxData,
                dataType: 'json',
                success: function(response) {
                    $form.removeClass('loading');
                    $submitButton.prop('disabled', false);
                    $submitText.show();
                    $submitLoader.hide();

                    if (response.success) {
                        $successMessage.find('.pcfb-message-text').text(response.data.message || 'Thank you!');
                        $successMessage.show();
                        $form.hide();

                        if (response.data.response_id) {
                            console.log('Response ID:', response.data.response_id);
                        }
                    } else {
                        if (response.data.errors) {
                            $.each(response.data.errors, function(fieldName, errorMessage) {
                                var $fieldGroup = $form.find('[name="' + fieldName + '"]').closest('.pcfb-form-group');
                                if ($fieldGroup.length === 0) {
                                    $fieldGroup = $form.find('[name^="' + fieldName + '"]').closest('.pcfb-form-group');
                                }
                                if ($fieldGroup.length > 0) {
                                    $fieldGroup.addClass('error');
                                    $fieldGroup.find('.pcfb-field-error').text(errorMessage);
                                }
                            });
                        }

                        var errorText = response.data.message || 'An error occurred. Please try again.';
                        $errorMessage.find('.pcfb-message-text').text(errorText);
                        $errorMessage.show();
                    }
                },
                error: function(xhr, status, error) {
                    $form.removeClass('loading');
                    $submitButton.prop('disabled', false);
                    $submitText.show();
                    $submitLoader.hide();

                    var errorText = 'An error occurred. Please try again.';
                    if (xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
                        errorText = xhr.responseJSON.data.message;
                    } else if (xhr.statusText) {
                        errorText = xhr.statusText;
                    }

                    $errorMessage.find('.pcfb-message-text').text(errorText);
                    $errorMessage.show();
                }
            });
        }
    };

    $(document).ready(function() {
        PCFB_Public.init();
    });

})(jQuery);
