/**
 * Maintenance Mode Form Handler
 * Handles AJAX form submission for maintenance mode contact forms
 */
document.addEventListener('DOMContentLoaded', function () {
    const form = document.getElementById('maintenance-query-form');

    if (!form) {
        return;
    }
    
    const messagesContainer = document.getElementById('form-messages');
    const submitButton = form.querySelector('input[type="submit"]');

    if (!messagesContainer) {
        return;
    }

    form.addEventListener('submit', function (e) {
        e.preventDefault(); // Prevent the default form submission

        // Clear previous messages
        messagesContainer.innerHTML = '';

        // Prepare to validate form fields
        let valid = true; // Flag to check if the form is valid

        // Check for required fields
        const emailField = document.getElementById('user_email');
        const messageField = document.getElementById('user_message');

        if (!emailField || !messageField) {
            messagesContainer.innerHTML = `<div class="message error">Form configuration error. Please contact the administrator.</div>`;
            return;
        }

        // Reset field styles
        emailField.style.border = '';
        messageField.style.border = '';

        // Validate email
        if (!emailField.value.trim()) {
            valid = false;
            emailField.style.border = '2px solid red'; // Highlight border in red
        }

        // Validate message
        if (!messageField.value.trim()) {
            valid = false;
            messageField.style.border = '2px solid red'; // Highlight border in red
        }

        // If form is not valid, show message and exit
        if (!valid) {
            messagesContainer.innerHTML = `<div class="message error">Please fill in all required fields.</div>`;
            return; // Exit the function
        }

        // Disable the submit button and change its text
        submitButton.disabled = true;
        const originalButtonText = submitButton.value;
        submitButton.value = 'Sending...';

        // Prepare form data
        const formData = new FormData(form);

        // Convert FormData to a plain object
        const data = {};
        formData.forEach((value, key) => {
            data[key] = value;
        });

        // Get WordPress REST API URL and nonce from the form
        const nonceField = form.querySelector('input[name="nonce"]');
        if (!nonceField) {
            messagesContainer.innerHTML = `<div class="message error">Security token missing. Please refresh the page.</div>`;
            submitButton.disabled = false;
            submitButton.value = originalButtonText;
            return;
        }

        const nonce = nonceField.value;
        const wpJsonUrl = window.location.origin + '/wp-json';
        const url = `${wpJsonUrl}/wpnts/v1/maintenance_mode`;

        // Use the Fetch API for the POST request
        fetch(url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'X-WP-NONCE': nonce
            },
            body: JSON.stringify(data)
        })
        .then(response => response.json())
        .then(resData => {
            // Re-enable the submit button
            submitButton.disabled = false;
            submitButton.value = originalButtonText; // Reset button text

            if (resData.success) {
                // Display success message
                messagesContainer.innerHTML = `<div class="message success">${resData.message}</div>`;
                // Reset the form
                form.reset();
                // Reset field styles
                emailField.style.border = '';
                messageField.style.border = '';
            } else {
                // Display error message for failed responses
                messagesContainer.innerHTML = `<div class="message error">${resData.message || 'An error occurred.'}</div>`;
            }

            // Remove messages after 4 seconds
            setTimeout(() => {
                messagesContainer.innerHTML = '';
            }, 4000);
        })
        .catch(err => {
            messagesContainer.innerHTML = `<div class="message error">An unexpected error occurred. Please try again later.</div>`;
            // Re-enable the submit button
            submitButton.disabled = false;
            submitButton.value = originalButtonText; // Reset button text

            // Remove messages after 4 seconds
            setTimeout(() => {
                messagesContainer.innerHTML = '';
            }, 4000);
        });
    });
});