document.addEventListener('DOMContentLoaded', function() {
    // Handle form submission for processing utility bills
    const processForm = document.getElementById('process-bills-form');
    
    if (processForm) {
        processForm.addEventListener('submit', async function(e) {
            e.preventDefault();
            
            // Show loading indicator
            const submitButton = processForm.querySelector('button[type="submit"]');
            const originalButtonText = submitButton.innerHTML;
            submitButton.disabled = true;
            submitButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Processing...';
            
            try {
                const formData = new FormData(processForm);
                const response = await fetch(processForm.action, {
                    method: 'POST',
                    headers: {
                        'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').getAttribute('content'),
                        'Accept': 'application/json',
                        'X-Requested-With': 'XMLHttpRequest'
                    },
                    body: formData
                });
                
                const data = await response.json();
                
                if (response.ok) {
                    // Show success message
                    Swal.fire({
                        title: data.alert.title,
                        html: `
                            <div class="text-left">
                                <p class="mb-2">${data.alert.message}</p>
                                <div class="mt-4 p-3 bg-gray-50 rounded-md">
                                    <p class="text-sm text-gray-600">
                                        <span class="font-medium">Processed:</span> ${data.alert.details.total_processed} bills<br>
                                        <span class="font-medium">Failed:</span> ${data.alert.details.total_failed} bills<br>
                                        <span class="font-medium">Billing Period:</span> ${data.alert.details.billing_period}
                                    </p>
                                </div>
                            </div>
                        `,
                        icon: data.alert.type,
                        confirmButtonText: 'OK',
                        confirmButtonColor: '#2563eb',
                        customClass: {
                            confirmButton: 'px-4 py-2 bg-blue-600 text-white rounded-md hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:ring-offset-2',
                        }
                    }).then((result) => {
                        // Optionally refresh the page or update the UI
                        if (result.isConfirmed) {
                            window.location.reload();
                        }
                    });
                } else {
                    // Show error message
                    throw new Error(data.message || 'An error occurred while processing the bills');
                }
            } catch (error) {
                console.error('Error:', error);
                Swal.fire({
                    title: 'Error!',
                    text: error.message || 'An error occurred while processing your request',
                    icon: 'error',
                    confirmButtonText: 'OK',
                    confirmButtonColor: '#dc2626'
                });
            } finally {
                // Reset button state
                submitButton.disabled = false;
                submitButton.innerHTML = originalButtonText;
            }
        });
    }
});
