/**
 * Contact Form Handling with AJAX and Validation
 */

$(document).ready(function() {
    
    // ========================================
    // Contact Form Validation & Submission
    // ========================================
    $('#contactForm').validate({
        rules: {
            name: {
                required: true,
                minlength: 3,
                maxlength: 100
            },
            email: {
                required: true,
                email: true,
                maxlength: 100
            },
            phone: {
                required: false,
                digits: true,
                minlength: 10,
                maxlength: 15
            },
            interest: {
                required: true
            },
            message: {
                required: true,
                minlength: 10,
                maxlength: 2000
            },
            consent: {
                required: true
            }
        },
        
        messages: {
            name: {
                required: "Please enter your name",
                minlength: "Name must be at least 3 characters"
            },
            email: {
                required: "Please enter your email address",
                email: "Please enter a valid email address"
            },
            phone: {
                digits: "Please enter a valid phone number",
                minlength: "Phone number must be at least 10 digits"
            },
            interest: {
                required: "Please select an option"
            },
            message: {
                required: "Please enter your message",
                minlength: "Message must be at least 10 characters"
            },
            consent: {
                required: "You must agree to the privacy policy"
            }
        },
        
        errorElement: 'span',
        errorClass: 'error-message',
        
        highlight: function(element) {
            $(element).closest('.form-group').addClass('has-error');
        },
        
        unhighlight: function(element) {
            $(element).closest('.form-group').removeClass('has-error');
        },
        
        submitHandler: function(form) {
            submitContactForm();
        }
    });
    
    // ========================================
    // Newsletter Form Validation
    // ========================================
    $('#newsletterForm').validate({
        rules: {
            email: {
                required: true,
                email: true
            }
        },
        
        messages: {
            email: {
                required: "Please enter your email",
                email: "Please enter a valid email"
            }
        },
        
        submitHandler: function(form) {
            submitNewsletterForm();
        }
    });
    
    // ========================================
    // Submit Contact Form via AJAX
    // ========================================
    function submitContactForm() {
        const $form = $('#contactForm');
        const $submitBtn = $('#submitBtn');
        const $status = $('#formStatus');
        
        // Show loading state
        $submitBtn.prop('disabled', true);
        $submitBtn.find('span').text('Sending...');
        $submitBtn.find('i').removeClass('fa-paper-plane').addClass('fa-spinner fa-spin');
        $status.removeClass('success error').html('');
        
        // Collect form data
        const formData = {
            name: $('#name').val(),
            email: $('#email').val(),
            phone: $('#phone').val(),
            interest: $('#interest').val(),
            message: $('#message').val(),
            consent: $('#consent').is(':checked'),
            website: '' // Honeypot
        };
        
        // AJAX request
        $.ajax({
            url: 'php/contact-handler.php',
            type: 'POST',
            data: JSON.stringify(formData),
            contentType: 'application/json',
            dataType: 'json',
            timeout: 10000,
            
            success: function(response) {
                if (response.success) {
                    // Show success message
                    $status.addClass('success').html(
                        '<i class="fas fa-check-circle"></i> ' + response.message
                    );
                    
                    // Reset form
                    $form[0].reset();
                    
                    // Optional: redirect or show modal
                    showSuccessModal();
                    
                } else {
                    // Show error message
                    let errorHtml = '<i class="fas fa-exclamation-circle"></i> ';
                    if (response.errors) {
                        errorHtml += response.errors.join('<br>');
                    } else {
                        errorHtml += response.message || 'An error occurred. Please try again.';
                    }
                    $status.addClass('error').html(errorHtml);
                }
            },
            
            error: function(xhr, status, error) {
                console.error('AJAX Error:', error);
                $status.addClass('error').html(
                    '<i class="fas fa-exclamation-circle"></i> ' +
                    'Connection error. Please try again or email us directly.'
                );
            },
            
            complete: function() {
                // Reset button state
                $submitBtn.prop('disabled', false);
                $submitBtn.find('span').text('Send Message');
                $submitBtn.find('i').removeClass('fa-spinner fa-spin').addClass('fa-paper-plane');
            }
        });
    }
    
    // ========================================
    // Submit Newsletter Form
    // ========================================
    function submitNewsletterForm() {
        const $form = $('#newsletterForm');
        const $submitBtn = $form.find('button[type="submit"]');
        const email = $form.find('input[type="email"]').val();
        
        // Show loading
        $submitBtn.prop('disabled', true).html('<i class="fas fa-spinner fa-spin"></i>');
        
        // Simulate API call (replace with actual endpoint)
        setTimeout(() => {
            // Show success message
            showNotification('Thank you for subscribing!', 'success');
            
            // Reset form
            $form[0].reset();
            $submitBtn.prop('disabled', false).html('Subscribe');
        }, 1500);
    }
    
    // ========================================
    // Success Modal
    // ========================================
    function showSuccessModal() {
        // Create modal if it doesn't exist
        if (!$('#successModal').length) {
            const modalHtml = `
                <div id="successModal" class="modal">
                    <div class="modal-content">
                        <div class="modal-icon">
                            <i class="fas fa-check-circle"></i>
                        </div>
                        <h3>Thank You!</h3>
                        <p>Your message has been sent successfully. We'll get back to you within 24 hours.</p>
                        <div class="modal-actions">
                            <button class="btn btn-primary close-modal">Got it</button>
                        </div>
                    </div>
                </div>
            `;
            $('body').append(modalHtml);
            
            // Add modal styles
            const modalStyles = `
                <style>
                    .modal {
                        position: fixed;
                        top: 0;
                        left: 0;
                        width: 100%;
                        height: 100%;
                        background: rgba(0,0,0,0.5);
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        z-index: 9999;
                        opacity: 0;
                        visibility: hidden;
                        transition: all 0.3s;
                    }
                    
                    .modal.show {
                        opacity: 1;
                        visibility: visible;
                    }
                    
                    .modal-content {
                        background: white;
                        padding: 40px;
                        border-radius: 30px;
                        max-width: 400px;
                        text-align: center;
                        transform: scale(0.7);
                        transition: all 0.3s;
                    }
                    
                    .modal.show .modal-content {
                        transform: scale(1);
                    }
                    
                    .modal-icon {
                        width: 80px;
                        height: 80px;
                        background: #6b03fc;
                        color: white;
                        border-radius: 50%;
                        display: flex;
                        align-items: center;
                        justify-content: center;
                        font-size: 40px;
                        margin: 0 auto 20px;
                    }
                    
                    .modal h3 {
                        font-size: 24px;
                        margin-bottom: 10px;
                        color: #212121;
                    }
                    
                    .modal p {
                        color: #5f5f6b;
                        margin-bottom: 20px;
                    }
                </style>
            `;
            $('head').append(modalStyles);
        }
        
        // Show modal
        const $modal = $('#successModal');
        $modal.addClass('show');
        
        // Close handlers
        $modal.find('.close-modal').on('click', function() {
            $modal.removeClass('show');
        });
        
        $(window).on('click', function(e) {
            if ($(e.target).is($modal)) {
                $modal.removeClass('show');
            }
        });
    }
    
    // ========================================
    // Notification System
    // ========================================
    function showNotification(message, type = 'success') {
        const notificationId = 'notification-' + Date.now();
        const notificationHtml = `
            <div id="${notificationId}" class="notification notification-${type}">
                <i class="fas fa-${type === 'success' ? 'check-circle' : 'exclamation-circle'}"></i>
                <span>${message}</span>
            </div>
        `;
        
        // Add styles if not present
        if (!$('#notification-styles').length) {
            const notificationStyles = `
                <style id="notification-styles">
                    .notification {
                        position: fixed;
                        top: 20px;
                        right: 20px;
                        padding: 15px 25px;
                        background: white;
                        border-radius: 10px;
                        box-shadow: 0 10px 30px rgba(0,0,0,0.15);
                        display: flex;
                        align-items: center;
                        gap: 10px;
                        z-index: 10000;
                        animation: slideIn 0.3s ease;
                        border-left: 4px solid #6b03fc;
                    }
                    
                    .notification-success {
                        border-left-color: #28a745;
                    }
                    
                    .notification-error {
                        border-left-color: #dc3545;
                    }
                    
                    @keyframes slideIn {
                        from {
                            transform: translateX(100%);
                            opacity: 0;
                        }
                        to {
                            transform: translateX(0);
                            opacity: 1;
                        }
                    }
                </style>
            `;
            $('head').append(notificationStyles);
        }
        
        $('body').append(notificationHtml);
        
        setTimeout(() => {
            $(`#${notificationId}`).fadeOut(300, function() {
                $(this).remove();
            });
        }, 5000);
    }
    
    // ========================================
    // Live Form Validation Feedback
    // ========================================
    $('.form-group input, .form-group select, .form-group textarea').on('input blur', function() {
        const $field = $(this);
        const $group = $field.closest('.form-group');
        
        if ($field.val().trim() !== '') {
            $group.addClass('filled');
        } else {
            $group.removeClass('filled');
        }
    });
    
    // ========================================
    // Phone Number Formatting
    // ========================================
    $('#phone').on('input', function() {
        let value = $(this).val().replace(/\D/g, '');
        if (value.length > 0) {
            if (value.length <= 3) {
                value = value;
            } else if (value.length <= 6) {
                value = value.slice(0, 3) + ' ' + value.slice(3);
            } else {
                value = value.slice(0, 3) + ' ' + value.slice(3, 6) + ' ' + value.slice(6, 10);
            }
            $(this).val(value);
        }
    });
    
});