/**
 * Trial Booking Form JavaScript
 *
 * @package Karate_Club_Manager
 * @since 1.0.61
 */

(function($) {
    'use strict';

    function i18n(key, fallback) {
        return (typeof macmTrialBooking !== 'undefined' && macmTrialBooking.i18n && macmTrialBooking.i18n[key]) ? macmTrialBooking.i18n[key] : fallback;
    }

    // Email validation helper
    function isValidEmail(email) {
        var re = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
        return re.test(email);
    }

    $(document).ready(function() {
        // Toggle parent name field based on checkbox
        $('#is_for_child').on('change', function() {
            if ($(this).is(':checked')) {
                $('#parent_name_group').slideDown();
                $('#parent_name').attr('required', true);
                // Update "Full Name" label to "Child's Name"
                $('#full_name_label').html(i18n('childsName', "Child's Name") + ' <span class="required">*</span>');
                $('#full_name_hint').slideDown();
            } else {
                $('#parent_name_group').slideUp();
                $('#parent_name').attr('required', false);
                $('#parent_name').val('');
                // Restore "Full Name" label
                $('#full_name_label').html(i18n('fullName', 'Full Name') + ' <span class="required">*</span>');
                $('#full_name_hint').slideUp();
            }
        });

        // Mobile number validation
        $('#mobile').on('input', function() {
            var value = $(this).val();
            // Remove any non-numeric characters except spaces, hyphens, plus, parentheses
            var cleaned = value.replace(/[^0-9\s\-\+\(\)]/g, '');
            $(this).val(cleaned);
        });

        // Form submission
        $('#kcm-trial-booking-form').on('submit', function(e) {
            e.preventDefault();

            var $form = $(this);
            var $button = $form.find('.kcm-submit-button');
            var $message = $('#kcm-booking-message');

            // Client-side validation
            var errors = [];
            var fullName = $('#full_name').val().trim();
            var isForChild = $('#is_for_child').is(':checked');
            var parentName = $('#parent_name').val().trim();
            var email = $('#email').val().trim();
            var classId = $('input[name="class_id"]:checked').val();

            if (!fullName) {
                errors.push(i18n('fullNameRequired', 'Full name is required.'));
            }

            if (isForChild && !parentName) {
                errors.push(i18n('parentNameRequired', 'Parent name is required when booking for a child.'));
            }

            if (!email) {
                errors.push(i18n('emailRequired', 'Email is required.'));
            } else if (!isValidEmail(email)) {
                errors.push(i18n('invalidEmail', 'Please enter a valid email address.'));
            }

            // Class selection is optional

            // If there are validation errors, show them and stop
            if (errors.length > 0) {
                $message
                    .removeClass('kcm-message-success')
                    .addClass('kcm-message-error')
                    .html(errors.join('<br>'))
                    .slideDown();

                // Scroll to message
                $('html, body').animate({
                    scrollTop: $message.offset().top - 100
                }, 500);

                return false;
            }

            // Hide any previous messages
            $message.hide();

            // Disable submit button
            $button.prop('disabled', true).text(i18n('submitting', 'Submitting...'));

            // Get form data
            var formData = {
                action: 'macm_submit_trial_booking',
                nonce: macmTrialBooking.nonce,
                full_name: fullName,
                is_for_child: isForChild ? 1 : 0,
                parent_name: parentName,
                mobile: $('#mobile').val(),
                email: email,
                class_id: classId
            };

            // Submit via AJAX
            $.ajax({
                url: macmTrialBooking.ajaxurl,
                type: 'POST',
                data: formData,
                success: function(response) {
                    if (response.success) {
                        // Show success message
                        $message
                            .removeClass('kcm-message-error')
                            .addClass('kcm-message-success')
                            .html(response.data.message)
                            .slideDown();

                        // Reset form
                        $form[0].reset();
                        $('#parent_name_group').hide();

                        // Scroll to message
                        $('html, body').animate({
                            scrollTop: $message.offset().top - 100
                        }, 500);
                    } else {
                        // Show error message
                        $message
                            .removeClass('kcm-message-success')
                            .addClass('kcm-message-error')
                            .html(response.data.message)
                            .slideDown();

                        // Scroll to message
                        $('html, body').animate({
                            scrollTop: $message.offset().top - 100
                        }, 500);
                    }
                },
                error: function() {
                    $message
                        .removeClass('kcm-message-success')
                        .addClass('kcm-message-error')
                        .html(i18n('errorTryAgain', 'An error occurred. Please try again.'))
                        .slideDown();
                },
                complete: function() {
                    // Re-enable submit button
                    $button.prop('disabled', false).text(i18n('bookTrialClass', 'Book Trial Class'));
                }
            });
        });
    });

})(jQuery);
