/**
 * Report Cybercrime Form - Enhanced AJAX Handler
 * Features: SweetAlert2, Real-time validation, Submit button state management
 */

document.addEventListener('DOMContentLoaded', function() {
    const reportForm = document.getElementById('reportForm');
    const submitBtn = reportForm?.querySelector('button[type="submit"]');
    
    if (!reportForm) {
        console.error('Report form not found');
        return;
    }

    // =================== FORM VALIDATION ===================
    const requiredFields = [
        'fullName', 'organization', 'email', 'phone',
        'incidentType', 'incidentDate', 'incidentDescription'
    ];

    /**
     * Check if all required fields are filled
     */
    function checkFormValidity() {
        let isValid = true;
        
        // Check text inputs
        requiredFields.forEach(fieldName => {
            const field = reportForm.querySelector(`[name="${fieldName}"]`);
            if (field && !field.value.trim()) {
                isValid = false;
            }
        });

        // Check priority selection
        const priorityLevel = document.getElementById('priorityLevel');
        if (!priorityLevel || !priorityLevel.value) {
            isValid = false;
        }

        // Update submit button state
        if (submitBtn) {
            submitBtn.disabled = !isValid;
            
            if (isValid) {
                submitBtn.classList.remove('btn-secondary');
                submitBtn.classList.add('btn-danger');
            } else {
                submitBtn.classList.remove('btn-danger');
                submitBtn.classList.add('btn-secondary');
            }
        }

        return isValid;
    }

    /**
     * Validate individual field
     */
    function validateField(field) {
        const fieldName = field.name;
        const value = field.value.trim();
        let isValid = true;
        let errorMessage = '';

        // Required field validation
        if (requiredFields.includes(fieldName) && !value) {
            isValid = false;
            errorMessage = 'This field is required';
        }

        // Email validation
        if (fieldName === 'email' && value) {
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
            if (!emailRegex.test(value)) {
                isValid = false;
                errorMessage = 'Please enter a valid email address';
            }
        }

        // Phone validation
        if (fieldName === 'phone' && value) {
            const phoneRegex = /^[\d\s\-\+\(\)]+$/;
            if (!phoneRegex.test(value) || value.length < 10) {
                isValid = false;
                errorMessage = 'Please enter a valid phone number';
            }
        }

        // Update field UI
        if (!isValid && value) {
            showFieldError(field, errorMessage);
        } else {
            clearFieldError(field);
        }

        return isValid;
    }

    /**
     * Show error for specific field
     */
    function showFieldError(field, message) {
        field.classList.add('is-invalid');
        field.classList.remove('is-valid');

        let errorElement = field.parentElement.querySelector('.invalid-feedback');
        
        if (!errorElement) {
            errorElement = document.createElement('div');
            errorElement.className = 'invalid-feedback';
            field.parentElement.appendChild(errorElement);
        }

        errorElement.textContent = message;
        errorElement.style.display = 'block';
    }

    /**
     * Clear field error
     */
    function clearFieldError(field) {
        field.classList.remove('is-invalid');
        
        if (field.value.trim()) {
            field.classList.add('is-valid');
        } else {
            field.classList.remove('is-valid');
        }

        const errorElement = field.parentElement.querySelector('.invalid-feedback');
        if (errorElement) {
            errorElement.style.display = 'none';
        }
    }

    /**
     * Clear all errors
     */
    function clearAllErrors() {
        reportForm.querySelectorAll('.is-invalid, .is-valid').forEach(element => {
            element.classList.remove('is-invalid', 'is-valid');
        });

        reportForm.querySelectorAll('.invalid-feedback').forEach(element => {
            element.style.display = 'none';
        });
    }

    // =================== REAL-TIME VALIDATION ===================
    // Attach blur event to all required fields
    requiredFields.forEach(fieldName => {
        const field = reportForm.querySelector(`[name="${fieldName}"]`);
        if (field) {
            field.addEventListener('blur', function() {
                validateField(this);
                checkFormValidity();
            });

            field.addEventListener('input', function() {
                if (this.classList.contains('is-invalid')) {
                    validateField(this);
                }
                checkFormValidity();
            });
        }
    });

    // Initial check
    checkFormValidity();

    // =================== PRIORITY SELECTION ===================
    window.selectPriority = function(level) {
        // Remove selected class from all cards
        document.querySelectorAll('.priority-card').forEach(card => {
            card.classList.remove('selected');
        });

        // Add selected class to clicked card
        event.currentTarget.classList.add('selected');

        // Set priority level
        const priorityLevel = document.getElementById('priorityLevel');
        if (priorityLevel) {
            priorityLevel.value = level;
        }

        // Check form validity
        checkFormValidity();
    };

    // =================== FORM SUBMISSION ===================
    reportForm.addEventListener('submit', function(e) {
        e.preventDefault();

        // Final validation check
        if (!checkFormValidity()) {
            Swal.fire({
                icon: 'warning',
                title: 'Incomplete Form',
                text: 'Please fill in all required fields before submitting.',
                confirmButtonColor: '#dc3545',
                confirmButtonText: 'OK'
            });
            return;
        }

        // Create FormData
        const formData = new FormData(reportForm);

        // Add priority level
        const priorityLevel = document.getElementById('priorityLevel').value;
        formData.append('priority', priorityLevel);

        // Show loading state
        submitBtn.disabled = true;
        submitBtn.innerHTML = `
            <span class="spinner-border spinner-border-sm me-2" role="status" aria-hidden="true"></span>
            Submitting Report...
        `;

        // Submit via AJAX
        fetch('php/report-cybercrime.php', {
            method: 'POST',
            body: formData,
            headers: {
                'X-Requested-With': 'XMLHttpRequest'
            }
        })
        .then(response => {
            if (!response.ok) {
                return response.json().then(data => {
                    throw data;
                });
            }
            return response.json();
        })
        .then(data => {
            // Reset button
            resetSubmitButton();

            if (data.success) {
                // Show success with SweetAlert2
                Swal.fire({
                    icon: 'success',
                    title: 'Report Submitted Successfully!',
                    html: `
                        <p class="mb-3">Your incident report has been received and processed.</p>
                        <div class="alert alert-info text-start mb-0">
                            <strong>Reference ID:</strong><br>
                            <code style="background-color: #f8f9fa; padding: 8px 12px; border-radius: 4px; display: inline-block; margin-top: 5px; font-size: 1.1rem;">${data.referenceId}</code>
                        </div>
                        <p class="mt-3 text-muted small">Please save this reference ID for tracking your case.</p>
                    `,
                    confirmButtonColor: '#28a745',
                    confirmButtonText: 'OK',
                    allowOutsideClick: false
                }).then(() => {
                    // Reset form
                    reportForm.reset();
                    document.getElementById('priorityLevel').value = '';
                    clearAllErrors();
                    
                    // Clear priority selection
                    document.querySelectorAll('.priority-card').forEach(card => {
                        card.classList.remove('selected');
                    });

                    // Recheck form validity
                    checkFormValidity();

                    // Scroll to top
                    window.scrollTo({ top: 0, behavior: 'smooth' });
                });
            } else {
                handleErrors(data);
            }
        })
        .catch(error => {
            resetSubmitButton();
            
            console.error('Submission error:', error);

            if (error.errors) {
                handleErrors(error);
            } else {
                Swal.fire({
                    icon: 'error',
                    title: 'Submission Failed',
                    text: error.message || 'An error occurred while submitting your report. Please try again.',
                    footer: '<strong>Emergency Hotline:</strong> +231 (90) 909 4712',
                    confirmButtonColor: '#dc3545'
                });
            }
        });
    });

    /**
     * Handle validation errors from server
     */
    function handleErrors(data) {
        if (data.errors && Object.keys(data.errors).length > 0) {
            // Show field errors
            Object.keys(data.errors).forEach(fieldName => {
                const field = reportForm.querySelector(`[name="${fieldName}"]`);
                if (field) {
                    showFieldError(field, data.errors[fieldName]);
                }
            });

            // Show error summary
            Swal.fire({
                icon: 'error',
                title: 'Validation Error',
                text: data.message || 'Please fix the errors highlighted in the form.',
                confirmButtonColor: '#dc3545'
            });

            // Scroll to first error
            const firstError = reportForm.querySelector('.is-invalid');
            if (firstError) {
                firstError.scrollIntoView({ behavior: 'smooth', block: 'center' });
                firstError.focus();
            }
        }
    }

    /**
     * Reset submit button to original state
     */
    function resetSubmitButton() {
        if (submitBtn) {
            submitBtn.disabled = false;
            submitBtn.innerHTML = `
                <i class="bi bi-send-fill me-2"></i> Submit Incident Report
            `;
            checkFormValidity(); // Re-enable/disable based on form state
        }
    }
});

/**
 * Auto-format phone number input
 */
document.addEventListener('DOMContentLoaded', function() {
    const phoneInput = document.querySelector('input[name="phone"]');
    if (phoneInput) {
        phoneInput.addEventListener('input', function(e) {
            // Remove non-numeric characters except +, -, (, ), and spaces
            let value = e.target.value.replace(/[^\d\s\-\+\(\)]/g, '');
            e.target.value = value;
        });
    }
});

/**
 * Character counter for description field
 */
document.addEventListener('DOMContentLoaded', function() {
    const descriptionField = document.querySelector('textarea[name="incidentDescription"]');
    if (descriptionField) {
        const maxLength = descriptionField.maxLength || 1000;
        
        // Create counter element
        const counter = document.createElement('small');
        counter.className = 'text-muted float-end';
        counter.textContent = `0 / ${maxLength}`;
        descriptionField.parentElement.appendChild(counter);

        descriptionField.addEventListener('input', function() {
            const length = this.value.length;
            counter.textContent = `${length} / ${maxLength}`;
            
            if (length >= maxLength * 0.9) {
                counter.classList.add('text-warning');
            } else {
                counter.classList.remove('text-warning');
            }
        });
    }
});