// Modal Handlers for Bootstrap

document.addEventListener('DOMContentLoaded', function() {
    // Handle delete button clicks
    const deleteButtons = document.querySelectorAll('[data-bs-toggle="deleteModal"]');

    deleteButtons.forEach(button => {
        button.addEventListener('click', function(e) {
            e.preventDefault();

            const targetModal = this.getAttribute('data-bs-target');
            const modal = new bootstrap.Modal(document.getElementById('deleteModal'));

            // Set up the delete form and message
            const deleteUrl = this.getAttribute('data-delete-url');
            const itemName = this.getAttribute('data-item-name') || 'this item';

            const deleteForm = document.getElementById('deleteForm');
            deleteForm.setAttribute('action', deleteUrl);

            const modalMessage = document.getElementById('deleteModalMessage');
            modalMessage.textContent = `Are you sure you want to delete "${itemName}"? This action cannot be undone.`;

            modal.show();
        });
    });

    // Handle update button clicks for inline editing
    const updateButtons = document.querySelectorAll('[data-bs-toggle="updateModal"]');

    updateButtons.forEach(button => {
        button.addEventListener('click', function(e) {
            e.preventDefault();

            const targetModal = this.getAttribute('data-bs-target');
            const modal = new bootstrap.Modal(document.getElementById('updateModal'));

            // Load the form content via AJAX
            const updateUrl = this.getAttribute('data-update-url');

            fetch(updateUrl)
                .then(response => response.text())
                .then(html => {
                    const modalBody = document.querySelector('#updateModal .modal-body');
                    modalBody.innerHTML = html;

                    // Re-initialize any form validation or JavaScript within the modal
                    initializeModalForms();

                    modal.show();
                })
                .catch(error => {
                    console.error('Error loading form:', error);
                    alert('Error loading the form. Please try again.');
                });
        });
    });
});

// Initialize forms within modals
function initializeModalForms() {
    // Handle form submissions within modals
    const modalForms = document.querySelectorAll('#updateModal form');

    modalForms.forEach(form => {
        form.addEventListener('submit', function(e) {
            e.preventDefault();

            const formData = new FormData(this);
            const submitUrl = this.getAttribute('action');

            fetch(submitUrl, {
                method: 'POST',
                body: formData,
                headers: {
                    'X-CSRFToken': formData.get('csrfmiddlewaretoken')
                }
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    // Close the modal and refresh the page or update the content
                    bootstrap.Modal.getInstance(document.getElementById('updateModal')).hide();

                    // Reload the page or update the specific element
                    if (data.reload) {
                        window.location.reload();
                    } else if (data.update_element) {
                        // Update specific element if needed
                        console.log('Element updated:', data.update_element);
                    }
                } else {
                    // Show errors in the form
                    displayFormErrors(form, data.errors);
                }
            })
            .catch(error => {
                console.error('Error submitting form:', error);
                alert('Error submitting the form. Please try again.');
            });
        });
    });
}

// Display form errors
function displayFormErrors(form, errors) {
    // Remove existing error messages
    const existingErrors = form.querySelectorAll('.alert-danger');
    existingErrors.forEach(error => error.remove());

    // Add error messages
    if (errors && Object.keys(errors).length > 0) {
        const errorDiv = document.createElement('div');
        errorDiv.className = 'alert alert-danger';
        errorDiv.innerHTML = '<strong>Please correct the following errors:</strong><ul>';

        for (const [field, messages] of Object.entries(errors)) {
            messages.forEach(message => {
                errorDiv.innerHTML += `<li>${field}: ${message}</li>`;
            });
        }

        errorDiv.innerHTML += '</ul>';
        form.insertBefore(errorDiv, form.firstChild);
    }
}
