<?php
/**
 * Payment QR Code Template
 * Displays QR code for M2C payment on thank you page
 */

if (!defined('ABSPATH')) {
    exit;
}
?>

<div class="m2c-payment-container">
    <div class="m2c-payment-header">
        <h2><?php _e('Complete Your Payment', 'ab2bc-red-envelope'); ?></h2>
        <p><?php _e('Scan the QR code below with your Red Envelope Wallet to complete the payment on AQY Chain.', 'ab2bc-red-envelope'); ?></p>
    </div>
    
    <div class="m2c-payment-body">
        <!-- Seller & Purchase Info Banner -->
        <div class="m2c-seller-info" style="background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%); border-radius: 12px; padding: 16px; margin-bottom: 20px; border: 1px solid #f59e0b;">
            <div style="display: flex; align-items: center; gap: 12px;">
                <div style="width: 48px; height: 48px; background: #f59e0b; border-radius: 50%; display: flex; align-items: center; justify-content: center;">
                    <span style="font-size: 24px;">🏪</span>
                </div>
                <div>
                    <h3 style="margin: 0 0 4px 0; font-size: 16px; color: #92400e;"><?php _e('Seller:', 'ab2bc-red-envelope'); ?> <?php echo esc_html(get_bloginfo('name')); ?></h3>
                    <p style="margin: 0; font-size: 14px; color: #b45309;">
                        <?php _e('Order', 'ab2bc-red-envelope'); ?> #<?php echo $order_id; ?> • 
                        <?php echo $order->get_item_count(); ?> <?php _e('item(s)', 'ab2bc-red-envelope'); ?> • 
                        <strong><?php echo $amount; ?> <?php echo $token; ?></strong>
                    </p>
                </div>
            </div>
            <?php 
            // Show order items summary
            $items = $order->get_items();
            if (!empty($items)): 
            ?>
            <div style="margin-top: 12px; padding-top: 12px; border-top: 1px solid #f59e0b;">
                <p style="margin: 0 0 8px 0; font-size: 12px; color: #92400e; font-weight: 600;"><?php _e('Purchase Details:', 'ab2bc-red-envelope'); ?></p>
                <ul style="margin: 0; padding-left: 20px; font-size: 13px; color: #b45309;">
                <?php foreach ($items as $item): ?>
                    <li><?php echo esc_html($item->get_name()); ?> × <?php echo $item->get_quantity(); ?></li>
                <?php endforeach; ?>
                </ul>
            </div>
            <?php endif; ?>
        </div>
        
        <!-- QR Code Section -->
        <div class="m2c-qr-section">
            <div class="m2c-qr-wrapper">
                <div id="m2c-qr-code"></div>
                <div class="m2c-qr-overlay" id="m2c-qr-overlay" style="display: none;">
                    <div class="m2c-qr-overlay-content">
                        <div class="m2c-spinner"></div>
                        <p><?php _e('Payment Processing...', 'ab2bc-red-envelope'); ?></p>
                    </div>
                </div>
            </div>
            
            <!-- Timer -->
            <div class="m2c-timer" id="m2c-timer">
                <svg width="20" height="20" viewBox="0 0 20 20" fill="none">
                    <path d="M10 5V10L13 13" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
                    <circle cx="10" cy="10" r="8" stroke="currentColor" stroke-width="2" fill="none"/>
                </svg>
                <span id="m2c-timer-text"><?php echo gmdate('i:s', $time_remaining); ?></span>
            </div>
        </div>
        
        <!-- Payment Details -->
        <div class="m2c-payment-details">
            <h3><?php _e('Payment Details', 'ab2bc-red-envelope'); ?></h3>
            
            <div class="m2c-detail-row">
                <span class="m2c-detail-label"><?php _e('Order Number:', 'ab2bc-red-envelope'); ?></span>
                <span class="m2c-detail-value">#<?php echo $order_id; ?></span>
            </div>
            
            <div class="m2c-detail-row">
                <span class="m2c-detail-label"><?php _e('Amount:', 'ab2bc-red-envelope'); ?></span>
                <span class="m2c-detail-value m2c-amount"><?php echo $amount; ?> <?php echo $token; ?></span>
            </div>
            
            <?php if (!empty($customer_wallet)): ?>
            <div class="m2c-detail-row">
                <span class="m2c-detail-label"><?php _e('Your Wallet:', 'ab2bc-red-envelope'); ?></span>
                <span class="m2c-detail-value m2c-wallet">
                    <?php echo substr($customer_wallet, 0, 10) . '...' . substr($customer_wallet, -8); ?>
                </span>
            </div>
            <?php endif; ?>
            
            <div class="m2c-detail-row">
                <span class="m2c-detail-label"><?php _e('Payment Token:', 'ab2bc-red-envelope'); ?></span>
                <span class="m2c-detail-value">
                    <span class="m2c-token-badge m2c-token-<?php echo strtolower($token); ?>">
                        <?php echo $token; ?>
                    </span>
                </span>
            </div>
            
            <!-- Rewards Info -->
            <?php if (get_option('m2c_enable_rewards') === 'yes' && !empty($customer_wallet)): ?>
            <div class="m2c-rewards-banner">
                <div class="m2c-rewards-icon">🎁</div>
                <div class="m2c-rewards-content">
                    <h4><?php _e('You\'ll Earn AQY Coin Rewards!', 'ab2bc-red-envelope'); ?></h4>
                    <p><?php _e('You\'ll receive AQY Coin rewards instantly to your Red Envelope Wallet after payment.', 'ab2bc-red-envelope'); ?></p>
                </div>
            </div>
            <?php endif; ?>
            
            <!-- Instructions -->
            <div class="m2c-instructions">
                <h4><?php _e('How to Pay:', 'ab2bc-red-envelope'); ?></h4>
                <ol>
                    <li><?php _e('Open your Red Envelope Wallet app', 'ab2bc-red-envelope'); ?></li>
                    <li><?php _e('Tap the "Scan" button', 'ab2bc-red-envelope'); ?></li>
                    <li><?php _e('Scan this QR code', 'ab2bc-red-envelope'); ?></li>
                    <li><?php _e('Confirm the transaction on AQY Chain', 'ab2bc-red-envelope'); ?></li>
                    <li><?php _e('Wait for payment confirmation', 'ab2bc-red-envelope'); ?></li>
                </ol>
            </div>
            
            <!-- Status -->
            <div class="m2c-status" id="m2c-payment-status">
                <div class="m2c-status-indicator m2c-status-pending">
                    <div class="m2c-status-dot"></div>
                    <span><?php _e('Waiting for payment...', 'ab2bc-red-envelope'); ?></span>
                </div>
            </div>
        </div>
    </div>
    
    <!-- Alternative Payment Method -->
    <div class="m2c-alternative-payment">
        <details>
            <summary><?php _e('Can\'t scan the QR code?', 'ab2bc-red-envelope'); ?></summary>
            <div class="m2c-manual-payment">
                <p><?php _e('You can manually enter the payment details in your wallet:', 'ab2bc-red-envelope'); ?></p>
                <div class="m2c-copy-field">
                    <label><?php _e('Merchant Address:', 'ab2bc-red-envelope'); ?></label>
                    <div class="m2c-copy-input">
                        <input type="text" readonly value="<?php echo esc_attr($order->get_meta('_m2c_merchant_wallet')); ?>" id="merchant-address">
                        <button class="m2c-copy-btn" onclick="copyToClipboard('merchant-address')">
                            <?php _e('Copy', 'ab2bc-red-envelope'); ?>
                        </button>
                    </div>
                </div>
                <div class="m2c-copy-field">
                    <label><?php _e('Transaction ID:', 'ab2bc-red-envelope'); ?></label>
                    <div class="m2c-copy-input">
                        <input type="text" readonly value="<?php echo esc_attr($qr_data['payload']['transaction_id']); ?>" id="transaction-id">
                        <button class="m2c-copy-btn" onclick="copyToClipboard('transaction-id')">
                            <?php _e('Copy', 'ab2bc-red-envelope'); ?>
                        </button>
                    </div>
                </div>
            </div>
        </details>
    </div>
</div>

<script>
jQuery(document).ready(function($) {
    // Generate QR Code
    var qrData = <?php echo json_encode($qr_data); ?>;
    var qrString = JSON.stringify(qrData);
    
    new QRCode(document.getElementById('m2c-qr-code'), {
        text: qrString,
        width: 280,
        height: 280,
        colorDark: '#000000',
        colorLight: '#ffffff',
        correctLevel: QRCode.CorrectLevel.H
    });
    
    // Timer countdown
    var timeRemaining = <?php echo $time_remaining; ?>;
    var timerInterval = setInterval(function() {
        timeRemaining--;
        if (timeRemaining <= 0) {
            clearInterval(timerInterval);
            $('#m2c-timer').html('<span style="color: #ef4444;"><?php _e('QR Code Expired', 'ab2bc-red-envelope'); ?></span>');
            $('#m2c-qr-overlay').show();
            return;
        }
        
        var minutes = Math.floor(timeRemaining / 60);
        var seconds = timeRemaining % 60;
        $('#m2c-timer-text').text(
            String(minutes).padStart(2, '0') + ':' + String(seconds).padStart(2, '0')
        );
    }, 1000);
    
    // Check payment status periodically
    var statusCheckInterval = setInterval(function() {
        $.ajax({
            url: m2c_params.ajax_url,
            type: 'POST',
            data: {
                action: 'm2c_check_payment_status',
                nonce: m2c_params.nonce,
                order_id: <?php echo $order_id; ?>
            },
            success: function(response) {
                if (response.success && response.data.is_paid) {
                    clearInterval(statusCheckInterval);
                    clearInterval(timerInterval);
                    
                    // Show success message
                    $('#m2c-payment-status').html(
                        '<div class="m2c-status-indicator m2c-status-success">' +
                        '<div class="m2c-status-dot"></div>' +
                        '<span><?php _e('Payment Successful!', 'ab2bc-red-envelope'); ?></span>' +
                        '</div>'
                    );
                    
                    // Show rewards if applicable
                    if (response.data.distribution && response.data.distribution.consumer_aqy > 0) {
                        var rewardsHtml = '<div class="m2c-success-rewards">' +
                            '<h4>🎉 <?php _e('You Earned AQY Rewards!', 'ab2bc-red-envelope'); ?></h4>' +
                            '<p class="m2c-rewards-amount">' + response.data.distribution.consumer_aqy.toFixed(4) + ' AQY</p>' +
                            '</div>';
                        $('#m2c-payment-status').append(rewardsHtml);
                    }
                    
                    // Show explorer link
                    if (response.data.tx_hash) {
                        var explorerHtml = '<div class="m2c-explorer-link">' +
                            '<a href="' + response.data.explorer_link + '" target="_blank">' +
                            '<?php _e('View Transaction', 'ab2bc-red-envelope'); ?> →' +
                            '</a>' +
                            '</div>';
                        $('#m2c-payment-status').append(explorerHtml);
                    }
                    
                    // Show overlay
                    $('#m2c-qr-overlay .m2c-qr-overlay-content').html(
                        '<div class="m2c-success-icon">✓</div>' +
                        '<p><?php _e('Payment Received!', 'ab2bc-red-envelope'); ?></p>'
                    );
                    $('#m2c-qr-overlay').show();
                    
                    // Reload page after 3 seconds
                    setTimeout(function() {
                        location.reload();
                    }, 3000);
                }
            }
        });
    }, m2c_params.check_interval);
});

function copyToClipboard(elementId) {
    var element = document.getElementById(elementId);
    element.select();
    document.execCommand('copy');
    
    // Show feedback
    var btn = element.nextElementSibling;
    var originalText = btn.textContent;
    btn.textContent = '<?php _e('Copied!', 'ab2bc-red-envelope'); ?>';
    setTimeout(function() {
        btn.textContent = originalText;
    }, 2000);
}
</script>
