/**
 * AUTO TESTER - Payment Gateway JavaScript
 * Unified payment processing for InstaPay and Vodafone Cash
 */

class PaymentGateway {
    constructor() {
        this.selectedMethod = null;
        this.paymentAmount = 0;
        this.paymentData = {};
        this.timer = null;
        this.checkInterval = null;
        
        this.init();
    }
    
    init() {
        // Get payment data from URL or localStorage
        const urlParams = new URLSearchParams(window.location.search);
        this.paymentAmount = parseFloat(urlParams.get('amount')) || 0;
        
        // Get stored payment data
        const storedData = localStorage.getItem('payment_data');
        if (storedData) {
            this.paymentData = JSON.parse(storedData);
            this.paymentAmount = this.paymentData.amount || this.paymentAmount;
        }
        
        // Update amount displays
        this.updateAmountDisplays();
        
        // Setup event listeners
        this.setupEventListeners();
    }
    
    setupEventListeners() {
        // Payment method selection
        document.querySelectorAll('.payment-card').forEach(card => {
            card.addEventListener('click', (e) => {
                const method = e.currentTarget.getAttribute('data-method');
                this.selectPaymentMethod(method);
            });
        });
        
        // Form submissions
        const instapayForm = document.getElementById('instapay-form');
        if (instapayForm) {
            instapayForm.addEventListener('submit', (e) => {
                e.preventDefault();
                this.processInstaPayPayment();
            });
        }
        
        const vodafoneForm = document.getElementById('vodafone-form');
        if (vodafoneForm) {
            vodafoneForm.addEventListener('submit', (e) => {
                e.preventDefault();
                this.processVodafonePayment();
            });
        }
    }
    
    updateAmountDisplays() {
        const formattedAmount = this.formatCurrency(this.paymentAmount, 'EGP');
        
        const instapayAmount = document.getElementById('instapay-amount');
        const vodafoneAmount = document.getElementById('vodafone-amount');
        
        if (instapayAmount) instapayAmount.textContent = formattedAmount;
        if (vodafoneAmount) vodafoneAmount.textContent = formattedAmount;
    }
    
    selectPaymentMethod(method) {
        this.selectedMethod = method;
        
        // Update card states
        document.querySelectorAll('.payment-card').forEach(card => {
            card.classList.remove('active');
        });
        
        const selectedCard = document.querySelector(`[data-method="${method}"]`);
        if (selectedCard) {
            selectedCard.classList.add('active');
        }
        
        // Hide all forms
        document.querySelectorAll('.payment-form').forEach(form => {
            form.classList.remove('active');
        });
        
        // Show selected form
        const formId = method + '-form';
        const form = document.getElementById(formId);
        if (form) {
            form.classList.add('active');
            form.scrollIntoView({ behavior: 'smooth' });
        }
    }
    
    async processInstaPayPayment() {
        const phoneNumber = document.getElementById('instapay-number')?.value;
        const accountName = document.getElementById('instapay-name')?.value;
        
        // Validation
        if (!phoneNumber || !accountName) {
            this.showStatus('instapay-status', 'error', t('payment.validation.fill_all_fields'));
            return;
        }
        
        if (!this.validatePhoneNumber(phoneNumber)) {
            this.showStatus('instapay-status', 'error', t('payment.validation.invalid_phone'));
            return;
        }
        
        try {
            this.showLoading('instapay');
            
            // Create payment
            const orderId = 'INS_' + Date.now();
            const result = await this.createInstaPayPayment(phoneNumber, accountName, orderId);
            
            if (result.success) {
                this.showInstaPayQR(result.qr_code, result.payment_id);
                this.startPaymentMonitoring('instapay', result.payment_id);
            } else {
                this.showStatus('instapay-status', 'error', result.message || t('payment.instapay.creation_failed'));
            }
            
        } catch (error) {
            this.showStatus('instapay-status', 'error', t('payment.general.error'));
            console.error('InstaPay error:', error);
        } finally {
            this.hideLoading('instapay');
        }
    }
    
    showInstaPayQR(qrData, paymentId) {
        const qrSection = document.getElementById('instapay-qr');
        if (!qrSection) return;
        
        qrSection.style.display = 'block';
        
        // Generate QR code
        const qrCode = qrSection.querySelector('.qr-code');
        if (qrCode) {
            qrCode.innerHTML = `
                <img src="https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=${encodeURIComponent(qrData)}" 
                     alt="InstaPay QR Code" 
                     style="width: 100%; height: auto; border-radius: 10px;">
            `;
        }
        
        // Start timer
        this.startPaymentTimer('instapay');
        
        // Show instructions
        this.showStatus('instapay-status', 'info', t('payment.instapay.qr_instructions'));
    }
    
    async processVodafonePayment() {
        const phoneNumber = document.getElementById('vodafone-number')?.value;
        const pin = document.getElementById('vodafone-pin')?.value;
        const otp = document.getElementById('vodafone-otp')?.value;
        
        // Validation
        if (!phoneNumber || !pin || !otp) {
            this.showStatus('vodafone-status', 'error', t('payment.validation.fill_all_fields'));
            return;
        }
        
        if (!this.validateVodafoneNumber(phoneNumber)) {
            this.showStatus('vodafone-status', 'error', t('payment.validation.invalid_vodafone'));
            return;
        }
        
        if (pin.length !== 4) {
            this.showStatus('vodafone-status', 'error', t('payment.validation.invalid_pin'));
            return;
        }
        
        if (otp.length !== 6) {
            this.showStatus('vodafone-status', 'error', t('payment.validation.invalid_otp'));
            return;
        }
        
        try {
            this.showLoading('vodafone');
            
            // Get session ID from stored data
            const sessionId = this.paymentData.vodafone_session_id;
            if (!sessionId) {
                throw new Error('No session found');
            }
            
            // Process payment
            const result = await this.verifyVodafonePayment(sessionId, otp, pin);
            
            if (result.success) {
                this.showPaymentSuccess('vodafone', result.transaction_id);
            } else {
                this.showStatus('vodafone-status', 'error', result.message || t('payment.vodafone.payment_failed'));
            }
            
        } catch (error) {
            this.showStatus('vodafone-status', 'error', t('payment.general.error'));
            console.error('Vodafone Cash error:', error);
        } finally {
            this.hideLoading('vodafone');
        }
    }
    
    async requestVodafoneOTP() {
        const phoneNumber = document.getElementById('vodafone-number')?.value;
        
        if (!phoneNumber) {
            this.showStatus('vodafone-status', 'error', t('payment.validation.enter_phone'));
            return;
        }
        
        if (!this.validateVodafoneNumber(phoneNumber)) {
            this.showStatus('vodafone-status', 'error', t('payment.validation.invalid_vodafone'));
            return;
        }
        
        try {
            this.showLoading('vodafone');
            
            // Initiate payment first
            const orderId = 'VDF_' + Date.now();
            const initiateResult = await this.initiateVodafonePayment(phoneNumber, orderId);
            
            if (initiateResult.success) {
                // Store session ID
                this.paymentData.vodafone_session_id = initiateResult.session_id;
                localStorage.setItem('payment_data', JSON.stringify(this.paymentData));
                
                // Send OTP
                const otpResult = await this.sendVodafoneOTP(phoneNumber, initiateResult.session_id);
                
                if (otpResult.success) {
                    this.showStatus('vodafone-status', 'success', t('payment.vodafone.otp_sent'));
                    
                    // Enable OTP input
                    const otpInput = document.getElementById('vodafone-otp');
                    if (otpInput) {
                        otpInput.disabled = false;
                        otpInput.focus();
                    }
                } else {
                    this.showStatus('vodafone-status', 'error', otpResult.message || t('payment.vodafone.otp_failed'));
                }
            } else {
                this.showStatus('vodafone-status', 'error', initiateResult.message || t('payment.vodafone.initiation_failed'));
            }
            
        } catch (error) {
            this.showStatus('vodafone-status', 'error', t('payment.general.error'));
            console.error('Vodafone OTP error:', error);
        } finally {
            this.hideLoading('vodafone');
        }
    }
    
    // API Methods
    async createInstaPayPayment(phoneNumber, accountName, orderId) {
        const response = await fetch('/core/api/payments/instapay.php?action=create_payment', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                amount: this.paymentAmount,
                phone_number: phoneNumber,
                customer_name: accountName,
                order_id: orderId
            })
        });
        
        return await response.json();
    }
    
    async initiateVodafonePayment(phoneNumber, orderId) {
        const response = await fetch('/core/api/payments/vodafone_cash.php?action=initiate_payment', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                amount: this.paymentAmount,
                phone_number: phoneNumber,
                order_id: orderId
            })
        });
        
        return await response.json();
    }
    
    async sendVodafoneOTP(phoneNumber, sessionId) {
        const response = await fetch('/core/api/payments/vodafone_cash.php?action=send_otp', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                phone_number: phoneNumber,
                session_id: sessionId
            })
        });
        
        return await response.json();
    }
    
    async verifyVodafonePayment(sessionId, otp, pin) {
        const response = await fetch('/core/api/payments/vodafone_cash.php?action=verify_payment', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            },
            body: JSON.stringify({
                session_id: sessionId,
                otp: otp,
                pin: pin
            })
        });
        
        return await response.json();
    }
    
    async checkPaymentStatus(method, paymentId) {
        const endpoint = method === 'instapay' ? 'instapay' : 'vodafone_cash';
        const response = await fetch(`/core/api/payments/${endpoint}.php?action=check_status&payment_id=${paymentId}`);
        return await response.json();
    }
    
    // Utility Methods
    startPaymentMonitoring(method, paymentId) {
        this.checkInterval = setInterval(async () => {
            try {
                const result = await this.checkPaymentStatus(method, paymentId);
                
                if (result.success && result.status === 'paid') {
                    clearInterval(this.checkInterval);
                    this.showPaymentSuccess(method, result.transaction_id);
                } else if (result.success && result.status === 'failed') {
                    clearInterval(this.checkInterval);
                    this.showStatus(method + '-status', 'error', t('payment.status.failed'));
                }
            } catch (error) {
                console.error('Payment status check error:', error);
            }
        }, 5000);
    }
    
    startPaymentTimer(method) {
        let timeLeft = 900; // 15 minutes
        const timerElement = document.getElementById(method + '-timer');
        
        if (!timerElement) return;
        
        this.timer = setInterval(() => {
            const minutes = Math.floor(timeLeft / 60);
            const seconds = timeLeft % 60;
            timerElement.textContent = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`;
            
            if (timeLeft <= 0) {
                clearInterval(this.timer);
                clearInterval(this.checkInterval);
                this.showStatus(method + '-status', 'error', t('payment.status.expired'));
            }
            
            timeLeft--;
        }, 1000);
    }
    
    showPaymentSuccess(method, transactionId) {
        clearInterval(this.timer);
        clearInterval(this.checkInterval);
        
        // Update payment data
        this.paymentData.status = 'paid';
        this.paymentData.transaction_id = transactionId;
        this.paymentData.payment_method = method;
        this.paymentData.paid_at = new Date().toISOString();
        
        localStorage.setItem('payment_data', JSON.stringify(this.paymentData));
        
        // Show success message
        Swal.fire({
            icon: 'success',
            title: t('payment.success.title'),
            text: t('payment.success.message'),
            confirmButtonText: t('payment.success.continue'),
            confirmButtonColor: '#28a745'
        }).then((result) => {
            if (result.isConfirmed) {
                // Redirect based on context
                const returnUrl = this.paymentData.return_url || '/app/client/dashboard.html';
                window.location.href = returnUrl + '?payment=success';
            }
        });
    }
    
    showLoading(method) {
        const submitButton = document.querySelector(`#${method}-form .btn-primary, #${method}-form .btn-success`);
        if (submitButton) {
            submitButton.disabled = true;
            submitButton.innerHTML = '<i class="fas fa-spinner fa-spin"></i> ' + t('payment.processing');
        }
    }
    
    hideLoading(method) {
        const submitButton = document.querySelector(`#${method}-form .btn-primary, #${method}-form .btn-success`);
        if (submitButton) {
            submitButton.disabled = false;
            
            if (method === 'instapay') {
                submitButton.innerHTML = '<i class="fas fa-mobile-alt"></i> ' + t('payment.instapay.pay');
            } else {
                submitButton.innerHTML = '<i class="fas fa-wallet"></i> ' + t('payment.vodafone.pay');
            }
        }
    }
    
    showStatus(elementId, type, message) {
        const statusElement = document.getElementById(elementId);
        if (!statusElement) return;
        
        statusElement.className = `status-message ${type}`;
        statusElement.textContent = message;
        statusElement.style.display = 'block';
        
        // Auto hide after 5 seconds
        setTimeout(() => {
            statusElement.style.display = 'none';
        }, 5000);
    }
    
    cancelPayment() {
        if (confirm(t('payment.cancel.confirm'))) {
            clearInterval(this.timer);
            clearInterval(this.checkInterval);
            
            const returnUrl = this.paymentData.cancel_url || '/app/client/dashboard.html';
            window.location.href = returnUrl;
        }
    }
    
    validatePhoneNumber(phone) {
        const phoneRegex = /^01[0-9]{9}$/;
        return phoneRegex.test(phone);
    }
    
    validateVodafoneNumber(phone) {
        // Vodafone numbers start with 010
        return /^010[0-9]{8}$/.test(phone);
    }
    
    formatCurrency(amount, currency) {
        return new Intl.NumberFormat('ar-EG', {
            style: 'currency',
            currency: currency,
            minimumFractionDigits: 2
        }).format(amount);
    }
}

// Initialize payment gateway
document.addEventListener('DOMContentLoaded', function() {
    window.paymentGateway = new PaymentGateway();
});

// Global functions for backward compatibility
window.selectPaymentMethod = function(method) {
    if (window.paymentGateway) {
        window.paymentGateway.selectPaymentMethod(method);
    }
};

window.processInstaPayPayment = function() {
    if (window.paymentGateway) {
        window.paymentGateway.processInstaPayPayment();
    }
};

window.processVodafonePayment = function() {
    if (window.paymentGateway) {
        window.paymentGateway.processVodafonePayment();
    }
};

window.requestVodafoneOTP = function() {
    if (window.paymentGateway) {
        window.paymentGateway.requestVodafoneOTP();
    }
};

window.cancelPayment = function() {
    if (window.paymentGateway) {
        window.paymentGateway.cancelPayment();
    }
};
