<?php
/**
 * User Profile Page
 * SSCI Office Platform
 */

$auth = $GLOBALS['auth'];
$db = $GLOBALS['db'];
$pageTitle = trans('profile') . ' - ' . config('app.name');

if (!$auth->isAuthenticated()) {
    header('Location: ?page=login');
    exit();
}

require_once __DIR__ . '/../layouts/header.php';

$user = $auth->getCurrentUser();
$primaryColor = config('app.ui.primary_color') ?? '#2563eb';
?>

<!-- Cropper CSS and Library -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.13/cropper.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/cropperjs/1.5.13/cropper.min.js"></script>

<div class="animate__animated animate__fadeIn w-full mx-auto px-4 sm:px-6 lg:px-8 max-w-4xl pb-20 md:pb-8">
    <div class="mb-6">
        <h1 class="text-2xl sm:text-3xl font-bold text-gray-800">
            <i class="fas fa-user" style="color: <?php echo htmlspecialchars($primaryColor); ?>;"></i> <?php echo trans('profile'); ?>
        </h1>
        <p class="text-gray-600 text-sm mt-1"><?php echo trans('manage_profile') ?? 'View and manage your profile information'; ?></p>
    </div>

    <!-- Profile Tabs -->
    <div class="bg-white rounded-lg shadow overflow-hidden mb-6">
        <div class="flex border-b border-gray-200 overflow-x-auto">
            <button type="button" class="profile-tab-btn flex-1 min-w-max px-4 sm:px-6 py-4 text-center font-semibold transition-colors tab-btn active text-blue-600 border-b-2 border-blue-600" data-tab="profile">
                <i class="fas fa-id-card mr-2"></i><span class="hidden sm:inline"><?php echo trans('profile'); ?></span>
            </button>
            <button type="button" class="profile-tab-btn flex-1 min-w-max px-4 sm:px-6 py-4 text-center font-semibold transition-colors tab-btn text-gray-600" data-tab="security">
                <i class="fas fa-lock mr-2"></i><span class="hidden sm:inline"><?php echo trans('security') ?? 'Security'; ?></span>
            </button>
            <button type="button" class="profile-tab-btn flex-1 min-w-max px-4 sm:px-6 py-4 text-center font-semibold transition-colors tab-btn text-gray-600" data-tab="preferences">
                <i class="fas fa-sliders-h mr-2"></i><span class="hidden sm:inline"><?php echo trans('preferences') ?? 'Preferences'; ?></span>
            </button>
        </div>
    </div>

    <!-- Profile Information Tab -->
    <div id="profile-tab" class="tab-content active">
        <form id="profileForm" class="bg-white rounded-lg shadow p-6 sm:p-8 space-y-6">
            <h2 class="text-xl sm:text-2xl font-bold text-gray-800 pb-4 border-b-2 border-blue-200">
                <i class="fas fa-user-circle text-blue-600 mr-3"></i><?php echo trans('profile_information'); ?>
            </h2>

            <!-- Photo Upload Section -->
            <div class="flex flex-col sm:flex-row gap-6 items-start">
                <div class="flex flex-col items-center">
                    <div class="w-32 h-32 rounded-lg overflow-hidden bg-gray-100 border-2 border-gray-300 flex items-center justify-center mb-4">
                        <?php if (!empty($user['photo'])) { ?>
                            <img id="profilePhotoPreview" src="<?php echo htmlspecialchars($user['photo']); ?>" alt="<?php echo htmlspecialchars($user['name']); ?>" class="w-full h-full object-cover">
                        <?php } else { ?>
                            <div id="profilePhotoPreview" class="w-full h-full bg-gradient-to-br from-blue-400 to-blue-600 flex items-center justify-center text-white text-4xl font-bold">
                                <?php echo substr($user['name'], 0, 1); ?>
                            </div>
                        <?php } ?>
                    </div>
                    <input type="file" id="photoInput" accept="image/*" class="hidden">
                    <button type="button" class="upload-photo-btn bg-blue-600 text-white px-4 py-2 rounded-lg hover:bg-blue-700 transition font-semibold text-sm">
                        <i class="fas fa-camera mr-2"></i><?php echo trans('upload_logo') ?? 'Change Photo'; ?>
                    </button>
                    <p class="text-xs text-gray-500 mt-2 text-center"><?php echo trans('square_crop_recommended') ?? 'Square format recommended'; ?></p>
                </div>

                <div class="flex-1 space-y-4">
                    <!-- Name -->
                    <div>
                        <label class="block text-gray-700 font-semibold mb-2">
                            <i class="fas fa-user text-blue-600 mr-2"></i><?php echo trans('name'); ?>
                        </label>
                        <input type="text" name="name" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-200" 
                               value="<?php echo htmlspecialchars($user['name']); ?>" required>
                    </div>

                    <!-- Email (Read-only) -->
                    <div>
                        <label class="block text-gray-700 font-semibold mb-2">
                            <i class="fas fa-envelope text-blue-600 mr-2"></i><?php echo trans('email'); ?>
                        </label>
                        <input type="email" class="w-full px-4 py-3 border border-gray-300 rounded-lg bg-gray-50" 
                               value="<?php echo htmlspecialchars($user['email']); ?>" readonly>
                        <p class="text-xs text-gray-500 mt-1"><?php echo trans('email_cannot_be_changed') ?? 'Email cannot be changed'; ?></p>
                    </div>
                </div>
            </div>

            <!-- Other Profile Fields -->
            <div class="grid grid-cols-1 md:grid-cols-2 gap-6">
                <div>
                    <label class="block text-gray-700 font-semibold mb-2">
                        <i class="fas fa-phone text-blue-600 mr-2"></i><?php echo trans('phone'); ?>
                    </label>
                    <input type="tel" name="phone" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-200" 
                           value="<?php echo htmlspecialchars($user['phone'] ?? ''); ?>" placeholder="+254 712 345 678">
                </div>

                <div>
                    <label class="block text-gray-700 font-semibold mb-2">
                        <i class="fab fa-whatsapp text-green-600 mr-2"></i>WhatsApp
                    </label>
                    <input type="tel" name="whatsapp" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-200" 
                           value="<?php echo htmlspecialchars($user['whatsapp'] ?? ''); ?>" placeholder="+254 712 345 678">
                </div>

                <div>
                    <label class="block text-gray-700 font-semibold mb-2">
                        <i class="fas fa-briefcase text-blue-600 mr-2"></i><?php echo trans('role'); ?>
                    </label>
                    <input type="text" class="w-full px-4 py-3 border border-gray-300 rounded-lg bg-gray-50" 
                           value="<?php echo ucfirst($user['role']); ?>" readonly>
                </div>

                <div>
                    <label class="block text-gray-700 font-semibold mb-2">
                        <i class="fas fa-check-circle text-green-600 mr-2"></i><?php echo trans('status'); ?>
                    </label>
                    <div class="px-4 py-3 bg-green-50 border border-green-200 rounded-lg">
                        <span class="text-green-700 font-semibold"><i class="fas fa-check-circle mr-2"></i><?php echo trans('active'); ?></span>
                    </div>
                </div>
            </div>

            <!-- Address -->
            <div>
                <label class="block text-gray-700 font-semibold mb-2">
                    <i class="fas fa-map-pin text-blue-600 mr-2"></i><?php echo trans('address') ?? 'Address'; ?>
                </label>
                <textarea name="address" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-200" 
                          rows="3" placeholder="Your address"><?php echo htmlspecialchars($user['address'] ?? ''); ?></textarea>
            </div>

            <input type="hidden" name="photo_data" id="photoData">

            <!-- Save Button -->
            <div class="flex gap-3 pt-4 border-t border-gray-200">
                <button type="submit" class="bg-blue-600 text-white px-6 py-3 rounded-lg hover:bg-blue-700 transition font-semibold">
                    <i class="fas fa-save mr-2"></i><?php echo trans('save_changes') ?? 'Save Changes'; ?>
                </button>
            </div>
        </form>
    </div>

    <!-- Security Settings Tab -->
    <div id="security-tab" class="tab-content hidden">
        <form id="securityForm" class="bg-white rounded-lg shadow p-6 sm:p-8 space-y-6">
            <h2 class="text-xl sm:text-2xl font-bold text-gray-800 pb-4 border-b-2 border-blue-200">
                <i class="fas fa-lock text-blue-600 mr-3"></i><?php echo trans('change_password'); ?>
            </h2>

            <div class="space-y-6">
                <div>
                    <label class="block text-gray-700 font-semibold mb-2">
                        <i class="fas fa-key text-blue-600 mr-2"></i><?php echo trans('current_password'); ?>
                    </label>
                    <input type="password" name="current_password" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-200" 
                           placeholder="Enter current password" required>
                </div>

                <div>
                    <label class="block text-gray-700 font-semibold mb-2">
                        <i class="fas fa-lock text-blue-600 mr-2"></i><?php echo trans('new_password'); ?>
                    </label>
                    <input type="password" name="new_password" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-200" 
                           placeholder="Enter new password" required>
                    <p class="text-xs text-gray-500 mt-1"><?php echo trans('password_requirements') ?? 'Minimum 8 characters'; ?></p>
                </div>

                <div>
                    <label class="block text-gray-700 font-semibold mb-2">
                        <i class="fas fa-lock text-blue-600 mr-2"></i><?php echo trans('confirm_password'); ?>
                    </label>
                    <input type="password" name="confirm_password" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-200" 
                           placeholder="Confirm new password" required>
                </div>
            </div>

            <div class="flex gap-3 pt-4 border-t border-gray-200">
                <button type="submit" class="bg-red-600 text-white px-6 py-3 rounded-lg hover:bg-red-700 transition font-semibold">
                    <i class="fas fa-key mr-2"></i><?php echo trans('update_password'); ?>
                </button>
            </div>
        </form>

        <!-- Two-Factor Authentication -->
        <div class="bg-white rounded-lg shadow p-6 sm:p-8 mt-6">
            <h2 class="text-xl sm:text-2xl font-bold text-gray-800 pb-4 border-b-2 border-blue-200">
                <i class="fas fa-shield-alt text-blue-600 mr-3"></i><?php echo trans('two_factor_authentication') ?? 'Two-Factor Authentication'; ?>
            </h2>
            <div class="bg-blue-50 border border-blue-200 rounded-lg p-4 mt-4">
                <p class="text-sm text-gray-700 mb-4"><?php echo trans('2fa_description') ?? 'Add extra security'; ?></p>
                <button type="button" id="enable2FABtn" class="bg-blue-600 text-white px-6 py-3 rounded-lg hover:bg-blue-700 transition font-semibold">
                    <i class="fas fa-check-circle mr-2"></i><?php echo trans('enable_2fa') ?? 'Enable 2FA'; ?>
                </button>
            </div>
        </div>
    </div>

    <!-- Preferences Tab -->
    <div id="preferences-tab" class="tab-content hidden">
        <form id="preferencesForm" class="bg-white rounded-lg shadow p-6 sm:p-8 space-y-6">
            <h2 class="text-xl sm:text-2xl font-bold text-gray-800 pb-4 border-b-2 border-blue-200">
                <i class="fas fa-sliders-h text-blue-600 mr-3"></i><?php echo trans('preferences'); ?>
            </h2>

            <div class="space-y-6">
                <!-- Language Preference -->
                <div>
                    <label class="block text-gray-700 font-semibold mb-2">
                        <i class="fas fa-globe text-blue-600 mr-2"></i><?php echo trans('language'); ?>
                    </label>
                    <select name="language" class="w-full px-4 py-3 border border-gray-300 rounded-lg focus:outline-none focus:border-blue-500 focus:ring-2 focus:ring-blue-200">
                        <option value="en" <?php echo ($user['language'] === 'en') ? 'selected' : ''; ?>>English</option>
                        <option value="fr" <?php echo ($user['language'] === 'fr') ? 'selected' : ''; ?>>Français</option>
                    </select>
                </div>

                <!-- Notification Preferences -->
                <div class="border-t pt-6">
                    <h3 class="text-lg font-semibold text-gray-700 mb-4">
                        <i class="fas fa-bell text-blue-600 mr-2"></i><?php echo trans('notification_preferences'); ?>
                    </h3>
                    <div class="space-y-3">
                        <label class="flex items-center gap-3 cursor-pointer">
                            <input type="checkbox" name="email_notifications" class="w-5 h-5 rounded border-gray-300" <?php echo (!empty($user['email_notifications'])) ? 'checked' : ''; ?>>
                            <span class="text-gray-700 text-sm"><?php echo trans('receive_email_notifications') ?? 'Email notifications'; ?></span>
                        </label>
                        <label class="flex items-center gap-3 cursor-pointer">
                            <input type="checkbox" name="in_app_notifications" class="w-5 h-5 rounded border-gray-300" <?php echo (!empty($user['in_app_notifications'])) ? 'checked' : ''; ?>>
                            <span class="text-gray-700 text-sm"><?php echo trans('receive_in_app_notifications') ?? 'In-app notifications'; ?></span>
                        </label>
                        <label class="flex items-center gap-3 cursor-pointer">
                            <input type="checkbox" name="sms_notifications" class="w-5 h-5 rounded border-gray-300" <?php echo (!empty($user['sms_notifications'])) ? 'checked' : ''; ?>>
                            <span class="text-gray-700 text-sm"><?php echo trans('receive_sms_notifications') ?? 'SMS notifications'; ?></span>
                        </label>
                    </div>
                </div>
            </div>

            <div class="flex gap-3 pt-4 border-t border-gray-200">
                <button type="submit" class="bg-blue-600 text-white px-6 py-3 rounded-lg hover:bg-blue-700 transition font-semibold">
                    <i class="fas fa-save mr-2"></i><?php echo trans('save_preferences'); ?>
                </button>
            </div>
        </form>
    </div>
</div>

<?php require_once __DIR__ . '/../layouts/footer.php'; ?>
<script
    // Hide all tabs
    document.querySelectorAll('.tab-content').forEach(tab => {
        tab.classList.add('hidden');
        tab.classList.remove('active');
    });
    
    // Reset all buttons
    document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.classList.remove('text-blue-600', 'border-b-2', 'border-blue-600');
        btn.classList.add('text-gray-600');
    });

    // Show selected tab
    const tabElement = document.getElementById(tabName + '-tab');
    if (tabElement) {
        tabElement.classList.remove('hidden');
        tabElement.classList.add('active');
    }
    
    // Highlight active button
    const activeBtn = document.querySelector('[data-tab="' + tabName + '"]');
    if (activeBtn) {
        activeBtn.classList.remove('text-gray-600');
        activeBtn.classList.add('text-blue-600', 'border-b-2', 'border-blue-600');
    }
}

let cropper = null;
const primaryColor = '<?php echo htmlspecialchars($primaryColor); ?>';

function enable2FA() {
    Swal.fire({
        title: '<?php echo trans('enable_2fa'); ?>',
        text: '<?php echo trans('2fa_setup_required') ?? 'You will need an authenticator app'; ?>',
        icon: 'info',
        confirmButtonText: '<?php echo trans('continue'); ?>'
    });
}

function openCropperModal(imageSrc) {
    const modal = document.createElement('div');
    modal.className = 'fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center p-4 z-50';
    modal.id = 'cropperModal';
    modal.innerHTML = `
        <div class="bg-white rounded-lg shadow-lg max-w-2xl w-full animate__animated animate__slideInDown">
            <div class="flex justify-between items-center p-6 border-b border-gray-200">
                <h2 class="text-xl font-bold text-gray-800"><?php echo trans('crop_photo') ?? 'Crop Photo'; ?></h2>
                <button type="button" class="closeModal text-gray-500 hover:text-gray-700 text-2xl font-bold">×</button>
            </div>
            
            <div class="p-6 max-h-96 overflow-auto bg-gray-50">
                <img id="cropperImage" src="${imageSrc}" style="max-width: 100%; display: block;">
            </div>
            
            <div class="flex gap-3 p-6 border-t border-gray-200">
                <button type="button" class="saveCrop flex-1 text-white py-2 rounded-lg transition font-semibold" style="background-color: ${primaryColor};">
                    <i class="fas fa-check mr-2"></i><?php echo trans('save'); ?>
                </button>
                <button type="button" class="closeModal flex-1 bg-gray-300 text-gray-700 py-2 rounded-lg hover:bg-gray-400 transition font-semibold">
                    <?php echo trans('cancel'); ?>
                </button>
            </div>
        </div>
    `;
    
    document.body.appendChild(modal);
    
    // Attach event listeners
    document.querySelectorAll('.closeModal').forEach(btn => {
        btn.addEventListener('click', function() {
            if (cropper) {
                cropper.destroy();
                cropper = null;
            }
            modal.remove();
        });
    });
    
    document.querySelector('.saveCrop').addEventListener('click', cropImage);
    
    // Initialize Cropper
    const image = modal.querySelector('#cropperImage');
    if (cropper) {
        cropper.destroy();
    }
    cropper = new Cropper(image, {
        aspectRatio: 1,
        viewMode: 1,
        autoCropArea: 1,
        responsive: true,
        restore: true,
        guides: true,
        center: true,
        highlight: true,
        cropBoxMovable: true,
        cropBoxResizable: true,
        toggleDragModeOnDblclick: true
    });
}

function cropImage() {
    if (!cropper) return;
    
    const canvas = cropper.getCroppedCanvas({
        maxWidth: 400,
        maxHeight: 400,
        fillColor: '#fff',
        imageSmoothingEnabled: true,
        imageSmoothingQuality: 'high'
    });
    
    // Update preview with new image
    const previewDiv = document.getElementById('profilePhotoPreview');
    if (previewDiv) {
        previewDiv.innerHTML = '';
        const img = new Image();
        img.src = canvas.toDataURL('image/jpeg');
        img.className = 'w-full h-full object-cover';
        previewDiv.appendChild(img);
    }
    
    // Store base64 data for form submission
    document.getElementById('photoData').value = canvas.toDataURL('image/jpeg');
    
    // Clean up cropper
    if (cropper) {
        cropper.destroy();
        cropper = null;
    }
    
    // Close modal
    const modal = document.getElementById('cropperModal');
    if (modal) {
        modal.remove();
    }
    
    // Show success message
    Swal.fire({
        icon: 'success',
        title: '<?php echo trans('success'); ?>',
        text: '<?php echo trans('photo_updated'); ?>',
        toast: true,
        position: 'top-end',
        showConfirmButton: false,
        timer: 2000
    });
}

document.addEventListener('DOMContentLoaded', function() {
    // Photo upload handler
    const photoInput = document.getElementById('photoInput');
    if (photoInput) {
        photoInput.addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(event) {
                    openCropperModal(event.target.result);
                };
                reader.readAsDataURL(file);
            }
        });
    }

    // Profile Form Submission
    const profileForm = document.getElementById('profileForm');
    if (profileForm) {
        profileForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const photoData = document.getElementById('photoData').value;
            if (photoData) {
                formData.append('photo', photoData);
            }
            
            const submitBtn = this.querySelector('button[type="submit"]');
            const originalHTML = submitBtn.innerHTML;
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i><?php echo trans("saving"); ?>';
            
            fetch('?page=api&action=saveProfile', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    Swal.fire({
                        icon: 'success',
                        title: '<?php echo trans("success"); ?>',
                        text: data.message || '<?php echo trans("profile_updated_successfully"); ?>',
                        toast: true,
                        position: 'top-end',
                        showConfirmButton: false,
                        timer: 2000
                    }).then(() => {
                        setTimeout(() => {
                            location.reload();
                        }, 300);
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: '<?php echo trans("error"); ?>',
                        text: data.message || '<?php echo trans("an_error_occurred"); ?>'
                    });
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = originalHTML;
                }
            })
            .catch(error => {
                console.error('Error:', error);
                Swal.fire({
                    icon: 'error',
                    title: '<?php echo trans("error"); ?>',
                    text: '<?php echo trans("an_error_occurred"); ?>'
                });
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalHTML;
            });
        });
    }

    // Security Form Submission
    const securityForm = document.getElementById('securityForm');
    if (securityForm) {
        securityForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const newPassword = document.querySelector('input[name="new_password"]').value;
            const confirmPassword = document.querySelector('input[name="confirm_password"]').value;
            
            if (newPassword !== confirmPassword) {
                Swal.fire({
                    icon: 'warning',
                    title: '<?php echo trans("password_mismatch"); ?>',
                    text: '<?php echo trans("passwords_do_not_match"); ?>'
                });
                return;
            }
            
            const formData = new FormData(this);
            const submitBtn = this.querySelector('button[type="submit"]');
            const originalHTML = submitBtn.innerHTML;
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i><?php echo trans("updating"); ?>';
            
            fetch('?page=api&action=changePassword', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    Swal.fire({
                        icon: 'success',
                        title: '<?php echo trans("success"); ?>',
                        text: data.message || '<?php echo trans("password_changed_successfully"); ?>',
                        toast: true,
                        position: 'top-end',
                        showConfirmButton: false,
                        timer: 2000
                    }).then(() => {
                        setTimeout(() => {
                            location.reload();
                        }, 300);
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: '<?php echo trans("error"); ?>',
                        text: data.message || '<?php echo trans("an_error_occurred"); ?>'
                    });
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = originalHTML;
                }
            })
            .catch(error => {
                console.error('Error:', error);
                Swal.fire({
                    icon: 'error',
                    title: '<?php echo trans("error"); ?>',
                    text: '<?php echo trans("an_error_occurred"); ?>'
                });
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalHTML;
            });
        });
    }

    // Preferences Form Submission
    const preferencesForm = document.getElementById('preferencesForm');
    if (preferencesForm) {
        preferencesForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            const formData = new FormData(this);
            const submitBtn = this.querySelector('button[type="submit"]');
            const originalHTML = submitBtn.innerHTML;
            submitBtn.disabled = true;
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin mr-2"></i><?php echo trans("saving"); ?>';
            
            fetch('?page=api&action=savePreferences', {
                method: 'POST',
                body: formData
            })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    Swal.fire({
                        icon: 'success',
                        title: '<?php echo trans("success"); ?>',
                        text: data.message || '<?php echo trans("preferences_updated_successfully"); ?>',
                        toast: true,
                        position: 'top-end',
                        showConfirmButton: false,
                        timer: 2000
                    }).then(() => {
                        setTimeout(() => {
                            location.reload();
                        }, 300);
                    });
                } else {
                    Swal.fire({
                        icon: 'error',
                        title: '<?php echo trans("error"); ?>',
                        text: data.message || '<?php echo trans("an_error_occurred"); ?>'
                    });
                    submitBtn.disabled = false;
                    submitBtn.innerHTML = originalHTML;
                }
            })
            .catch(error => {
                console.error('Error:', error);
                Swal.fire({
                    icon: 'error',
                    title: '<?php echo trans("error"); ?>',
                    text: '<?php echo trans("an_error_occurred"); ?>'
                });
                submitBtn.disabled = false;
                submitBtn.innerHTML = originalHTML;
            });
        });
    }
});
</script>

