<?php
/**
 * QR Payment API Integration
 * Optional integration with external qr-payment-api service
 * For multi-site centralized QR code management
 */

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

class M2C_QR_API_Integration {
    
    private $api_endpoint;
    private $api_key;
    private $api_secret;
    private $merchant_id;
    
    public function __construct() {
        // Get settings from gateway
        $gateway_settings = get_option('woocommerce_red_envelope_settings', array());
        $this->api_endpoint = isset($gateway_settings['qr_api_endpoint']) ? $gateway_settings['qr_api_endpoint'] : '';
        $this->api_key = isset($gateway_settings['qr_api_key']) ? $gateway_settings['qr_api_key'] : '';
        $this->api_secret = isset($gateway_settings['qr_api_secret']) ? $gateway_settings['qr_api_secret'] : '';
        $this->merchant_id = isset($gateway_settings['qr_api_merchant_id']) ? $gateway_settings['qr_api_merchant_id'] : '';
        
        // Register shortcodes
        add_shortcode('m2c_payment_qr', array($this, 'payment_qr_shortcode'));
        add_shortcode('m2c_storefront_qr', array($this, 'storefront_qr_shortcode'));
        
        // Register AJAX handler for API QR generation
        add_action('wp_ajax_mre_generate_api_qr', array($this, 'ajax_generate_qr'));
        add_action('wp_ajax_nopriv_mre_generate_api_qr', array($this, 'ajax_generate_qr'));
        
        // Register REST endpoint for webhook from qr-payment-api
        add_action('rest_api_init', array($this, 'register_rest_endpoints'));
    }
    
    /**
     * Register REST endpoints
     */
    public function register_rest_endpoints() {
        // Webhook endpoint for qr-payment-api notifications
        register_rest_route('m2c/v1', '/qr-api-webhook', array(
            'methods' => 'POST',
            'callback' => array($this, 'handle_qr_api_webhook'),
            'permission_callback' => array($this, 'verify_qr_api_signature'),
        ));
    }
    
    /**
     * Check if QR API is configured
     */
    public function is_configured() {
        return !empty($this->api_endpoint) && !empty($this->api_key);
    }
    
    /**
     * Generate signed request to QR API
     */
    private function api_request($method, $endpoint, $data = null) {
        if (!$this->is_configured()) {
            return new WP_Error('not_configured', 'QR Payment API is not configured');
        }
        
        $url = rtrim($this->api_endpoint, '/') . '/api/v1' . $endpoint;
        $timestamp = time();
        
        $args = array(
            'method' => $method,
            'headers' => array(
                'Content-Type' => 'application/json',
                'X-API-Key' => $this->api_key,
                'X-Timestamp' => $timestamp,
            ),
            'timeout' => 30,
        );
        
        // Generate signature if we have API secret
        if (!empty($this->api_secret) && $data) {
            $signature_payload = $timestamp . json_encode($data);
            $signature = hash_hmac('sha256', $signature_payload, $this->api_secret);
            $args['headers']['X-Signature'] = $signature;
        }
        
        if ($data && in_array($method, array('POST', 'PUT', 'PATCH'))) {
            $args['body'] = json_encode($data);
        }
        
        $response = wp_remote_request($url, $args);
        
        if (is_wp_error($response)) {
            error_log('[M2C QR API] Request error: ' . $response->get_error_message());
            return $response;
        }
        
        $body = wp_remote_retrieve_body($response);
        $result = json_decode($body, true);
        
        if (json_last_error() !== JSON_ERROR_NONE) {
            return new WP_Error('invalid_response', 'Invalid JSON response from QR API');
        }
        
        return $result;
    }
    
    /**
     * Generate QR code via API
     * 
     * @param float $amount Payment amount
     * @param string $order_id Order ID
     * @param array $options Additional options
     * @return array|WP_Error
     */
    public function generate_qr($amount, $order_id, $options = array()) {
        $data = array_merge(array(
            'amount' => floatval($amount),
            'currency' => 'USDC',
            'orderId' => $order_id,
            'format' => 'base64',
            'size' => 300,
            'includeBanner' => true,
            'expiryMinutes' => 30,
        ), $options);
        
        return $this->api_request('POST', '/qr/generate', $data);
    }
    
    /**
     * Verify QR code status
     * 
     * @param string $qr_id QR code ID
     * @return array|WP_Error
     */
    public function verify_qr($qr_id) {
        return $this->api_request('GET', '/qr/verify/' . $qr_id);
    }
    
    /**
     * Payment QR shortcode for embedding in pages
     * 
     * Usage: [m2c_payment_qr amount="99.00" order_id="12345" product="Widget"]
     */
    public function payment_qr_shortcode($atts) {
        $atts = shortcode_atts(array(
            'amount' => 0,
            'order_id' => '',
            'product' => '',
            'description' => '',
            'email' => '',
            'expiry' => 30,
        ), $atts);
        
        if (!$this->is_configured()) {
            return '<div class="mre-error">QR Payment API is not configured. Please configure it in WooCommerce &gt; Settings &gt; Payments &gt; Red Envelope.</div>';
        }
        
        if (empty($atts['amount']) || $atts['amount'] <= 0) {
            return '<div class="mre-error">Amount is required for payment QR code.</div>';
        }
        
        // Generate unique order ID if not provided
        if (empty($atts['order_id'])) {
            $atts['order_id'] = 'SC-' . time() . '-' . wp_rand(1000, 9999);
        }
        
        // Generate QR code
        $result = $this->generate_qr($atts['amount'], $atts['order_id'], array(
            'productName' => $atts['product'],
            'description' => $atts['description'],
            'customerEmail' => $atts['email'],
            'expiryMinutes' => intval($atts['expiry']),
        ));
        
        if (is_wp_error($result)) {
            return '<div class="mre-error">Failed to generate QR code: ' . esc_html($result->get_error_message()) . '</div>';
        }
        
        if (!isset($result['success']) || !$result['success']) {
            $error = isset($result['error']) ? $result['error'] : 'Unknown error';
            return '<div class="mre-error">QR API Error: ' . esc_html($error) . '</div>';
        }
        
        $data = $result['data'];
        $gateway_settings = get_option('woocommerce_red_envelope_settings', array());
        $reward_percent = isset($gateway_settings['reward_percent']) ? $gateway_settings['reward_percent'] : '60';
        $reward_amount = floatval($atts['amount']) * (floatval($reward_percent) / 100);
        
        ob_start();
        ?>
        <div class="mre-payment-widget" data-qr-id="<?php echo esc_attr($data['qrId']); ?>" 
             style="background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%); color: white; padding: 30px; border-radius: 12px; max-width: 500px; margin: 20px auto;">
            
            <h3 style="color: #f39c12; margin-top: 0; text-align: center;">📱 Complete Your Payment</h3>
            
            <div style="display: flex; flex-wrap: wrap; gap: 20px; align-items: flex-start; justify-content: center;">
                <!-- QR Code -->
                <div style="text-align: center;">
                    <div style="background: white; padding: 15px; border-radius: 10px; display: inline-block;">
                        <img src="<?php echo esc_attr($data['qrCode']); ?>" alt="Payment QR Code" style="width: 200px; height: 200px;">
                    </div>
                    <p style="color: #aaa; font-size: 12px; margin-top: 10px;">Scan with Red Envelope Wallet</p>
                </div>
                
                <!-- Order Details -->
                <div style="flex: 1; min-width: 200px;">
                    <div style="background: rgba(255,255,255,0.1); padding: 15px; border-radius: 8px; margin-bottom: 15px;">
                        <h4 style="color: #f39c12; margin: 0 0 10px 0;">🛒 Order Summary</h4>
                        <?php if (!empty($atts['product'])) : ?>
                        <p style="margin: 5px 0; color: #e0e0e0;"><?php echo esc_html($atts['product']); ?></p>
                        <?php endif; ?>
                        <p style="margin: 5px 0; color: #aaa; font-size: 12px;">Order #<?php echo esc_html($atts['order_id']); ?></p>
                    </div>
                    
                    <div style="background: rgba(255,255,255,0.1); padding: 15px; border-radius: 8px; margin-bottom: 15px;">
                        <p style="color: #aaa; margin: 0;">Amount to Pay:</p>
                        <p style="color: #4CAF50; font-size: 24px; font-weight: bold; margin: 5px 0;"><?php echo number_format($atts['amount'], 2); ?> USDC</p>
                    </div>
                    
                    <div style="background: linear-gradient(135deg, #f39c12, #e74c3c); padding: 12px 20px; border-radius: 20px; text-align: center;">
                        <span style="color: white; font-weight: bold;">🎁 Your Reward: <?php echo number_format($reward_amount, 2); ?> AQY Coins</span>
                    </div>
                </div>
            </div>
            
            <!-- Expiry Timer -->
            <div style="text-align: center; margin-top: 20px; padding-top: 15px; border-top: 1px solid rgba(255,255,255,0.1);">
                <p style="color: #aaa; font-size: 12px; margin: 0;">
                    QR expires in: <span class="mre-countdown" data-expires="<?php echo esc_attr($data['expiresAt']); ?>"><?php echo intval($data['expiresIn'] / 60); ?> minutes</span>
                </p>
            </div>
        </div>
        
        <style>
        .mre-error {
            background: #f8d7da;
            color: #721c24;
            padding: 15px;
            border-radius: 8px;
            margin: 20px 0;
        }
        </style>
        <?php
        return ob_get_clean();
    }
    
    /**
     * AJAX handler for generating QR code
     */
    public function ajax_generate_qr() {
        check_ajax_referer('mre_generate_qr', 'nonce');
        
        $amount = floatval($_POST['amount'] ?? 0);
        $order_id = sanitize_text_field($_POST['order_id'] ?? '');
        $product = sanitize_text_field($_POST['product'] ?? '');
        
        if ($amount <= 0) {
            wp_send_json_error(array('message' => 'Invalid amount'));
            return;
        }
        
        $result = $this->generate_qr($amount, $order_id, array(
            'productName' => $product,
        ));
        
        if (is_wp_error($result)) {
            wp_send_json_error(array('message' => $result->get_error_message()));
            return;
        }
        
        if (!isset($result['success']) || !$result['success']) {
            wp_send_json_error(array('message' => $result['error'] ?? 'Unknown error'));
            return;
        }
        
        wp_send_json_success($result['data']);
    }
    
    /**
     * Verify webhook signature from qr-payment-api
     */
    public function verify_qr_api_signature($request) {
        $gateway_settings = get_option('woocommerce_red_envelope_settings', array());
        $webhook_secret = isset($gateway_settings['qr_api_webhook_secret']) ? $gateway_settings['qr_api_webhook_secret'] : '';
        
        if (empty($webhook_secret)) {
            error_log('[M2C QR API] Webhook secret not configured');
            return false;
        }
        
        $signature = $request->get_header('X-Signature');
        $timestamp = $request->get_header('X-Timestamp');
        
        if (empty($signature) || empty($timestamp)) {
            error_log('[M2C QR API] Missing signature or timestamp');
            return false;
        }
        
        // Check timestamp is within 5 minutes
        if (abs(time() - intval($timestamp)) > 300) {
            error_log('[M2C QR API] Timestamp too old');
            return false;
        }
        
        // Verify signature
        $body = $request->get_body();
        $expected = hash_hmac('sha256', $timestamp . $body, $webhook_secret);
        
        return hash_equals($expected, $signature);
    }
    
    /**
     * Handle webhook from qr-payment-api
     */
    public function handle_qr_api_webhook($request) {
        $data = $request->get_json_params();
        
        error_log('[M2C QR API Webhook] Received: ' . json_encode($data));
        
        $event = $data['event'] ?? '';
        $payload = $data['payload'] ?? array();
        
        switch ($event) {
            case 'payment.completed':
                return $this->handle_payment_completed($payload);
                
            case 'payment.expired':
                return $this->handle_payment_expired($payload);
                
            case 'payment.failed':
                return $this->handle_payment_failed($payload);
                
            default:
                error_log('[M2C QR API Webhook] Unknown event: ' . $event);
                return new WP_REST_Response(array('received' => true), 200);
        }
    }
    
    /**
     * Handle completed payment from API
     */
    private function handle_payment_completed($payload) {
        $order_id = $payload['orderId'] ?? '';
        $tx_hash = $payload['transactionHash'] ?? '';
        $amount = $payload['amount'] ?? 0;
        
        error_log('[M2C QR API] Payment completed for order: ' . $order_id);
        
        // Try to find WooCommerce order
        $order = $this->find_order_by_id($order_id);
        
        if ($order) {
            // Update order status
            $order->payment_complete($tx_hash);
            $order->add_order_note(sprintf(
                __('Payment completed via QR API. TX: %s', 'ab2bc-red-envelope'),
                $tx_hash
            ));
            
            // Store transaction info
            $order->update_meta_data('_mre_tx_hash', $tx_hash);
            $order->update_meta_data('_mre_payment_status', 'completed');
            $order->update_meta_data('_mre_payment_timestamp', time());
            $order->save();
        }
        
        return new WP_REST_Response(array('success' => true, 'orderId' => $order_id), 200);
    }
    
    /**
     * Handle expired payment
     */
    private function handle_payment_expired($payload) {
        $order_id = $payload['orderId'] ?? '';
        
        error_log('[M2C QR API] Payment expired for order: ' . $order_id);
        
        $order = $this->find_order_by_id($order_id);
        
        if ($order && $order->get_status() === 'pending') {
            $order->update_status('cancelled', __('Payment QR code expired', 'ab2bc-red-envelope'));
        }
        
        return new WP_REST_Response(array('success' => true, 'orderId' => $order_id), 200);
    }
    
    /**
     * Handle failed payment
     */
    private function handle_payment_failed($payload) {
        $order_id = $payload['orderId'] ?? '';
        $reason = $payload['reason'] ?? 'Unknown';
        
        error_log('[M2C QR API] Payment failed for order: ' . $order_id . ' - ' . $reason);
        
        $order = $this->find_order_by_id($order_id);
        
        if ($order && $order->get_status() === 'pending') {
            $order->update_status('failed', sprintf(
                __('Payment failed: %s', 'ab2bc-red-envelope'),
                $reason
            ));
        }
        
        return new WP_REST_Response(array('success' => true, 'orderId' => $order_id), 200);
    }
    
    /**
     * Find order by ID or order number
     */
    private function find_order_by_id($order_id) {
        // Try direct lookup
        $order = wc_get_order($order_id);
        if ($order) {
            return $order;
        }
        
        // Search by order number in recent orders
        foreach (wc_get_orders(array('limit' => 100)) as $recent_order) {
            if ($recent_order->get_order_number() == $order_id) {
                return $recent_order;
            }
        }
        
        // Check if it's a shortcode-generated order (SC- prefix)
        if (strpos($order_id, 'SC-') === 0) {
            // These are non-WooCommerce orders, log for custom handling
            error_log('[M2C QR API] Shortcode order received: ' . $order_id);
            do_action('m2c_shortcode_payment_completed', $order_id);
            return null;
        }
        
        return null;
    }
    
    /**
     * Storefront QR shortcode for merchants to display at their store/website
     * This generates a STATIC QR code that customers can scan anytime
     * 
     * Usage: [m2c_storefront_qr] or [m2c_storefront_qr size="300" show_reward="yes"]
     * 
     * The generated QR code links to the store and allows customers to:
     * - Send payments directly to the merchant wallet
     * - Optionally pre-fill amounts
     * 
     * Options:
     * - size: QR code size in pixels (default: 250)
     * - show_reward: Show reward percentage badge (default: yes)
     * - title: Custom title (default: "Pay with Red Envelope")
     * - print: Show print button (default: yes)
     * - download: Show download button (default: yes)
     */
    public function storefront_qr_shortcode($atts) {
        $atts = shortcode_atts(array(
            'size' => 250,
            'show_reward' => 'yes',
            'title' => 'Pay with Red Envelope',
            'print' => 'yes',
            'download' => 'yes',
        ), $atts);
        
        // Get merchant wallet from gateway settings
        $gateway_settings = get_option('woocommerce_red_envelope_settings', array());
        $merchant_wallet = isset($gateway_settings['merchant_wallet']) ? $gateway_settings['merchant_wallet'] : '';
        $reward_percent = isset($gateway_settings['reward_percent']) ? $gateway_settings['reward_percent'] : '60';
        $store_name = get_bloginfo('name');
        
        if (empty($merchant_wallet)) {
            return '<div class="mre-error" style="background: #fff3cd; color: #856404; padding: 15px; border-radius: 8px;">
                <strong>⚠️ Setup Required:</strong> Please configure your Merchant Wallet Address in WooCommerce &gt; Settings &gt; Payments &gt; Red Envelope.
            </div>';
        }
        
        // Generate storefront QR data - this is a simple format for wallets to recognize
        $qr_data = array(
            'a' => 'store',             // action: storefront
            'v' => '1.0',               // version
            'n' => $store_name,         // store name
            't' => $merchant_wallet,    // to (wallet address)
            'rp' => intval($reward_percent), // reward percentage
            'u' => home_url(),          // store URL
        );
        
        $qr_json = json_encode($qr_data, JSON_UNESCAPED_SLASHES);
        $size = intval($atts['size']);
        $qr_url = "https://api.qrserver.com/v1/create-qr-code/?size={$size}x{$size}&data=" . urlencode($qr_json) . "&format=png&margin=10";
        
        // Unique ID for this QR instance
        $qr_id = 'mre-storefront-' . wp_rand(10000, 99999);
        
        ob_start();
        ?>
        <div id="<?php echo esc_attr($qr_id); ?>" class="mre-storefront-qr" 
             style="background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%); color: white; padding: 30px; border-radius: 12px; max-width: 400px; margin: 20px auto; text-align: center;">
            
            <h3 style="color: #f39c12; margin: 0 0 20px 0;">📱 <?php echo esc_html($atts['title']); ?></h3>
            
            <!-- Store Name -->
            <p style="color: #e0e0e0; margin: 0 0 15px 0; font-size: 18px; font-weight: bold;">
                <?php echo esc_html($store_name); ?>
            </p>
            
            <!-- QR Code -->
            <div style="background: white; padding: 20px; border-radius: 12px; display: inline-block; margin-bottom: 15px;" class="mre-qr-container">
                <img src="<?php echo esc_url($qr_url); ?>" alt="Store Payment QR Code" style="width: <?php echo esc_attr($size); ?>px; height: <?php echo esc_attr($size); ?>px;" class="mre-qr-image"/>
            </div>
            
            <p style="color: #aaa; font-size: 13px; margin: 0 0 15px 0;">
                Scan with <strong>Red Envelope Wallet</strong> to pay
            </p>
            
            <?php if ($atts['show_reward'] === 'yes') : ?>
            <!-- Reward Badge -->
            <div style="background: linear-gradient(135deg, #f39c12, #e74c3c); padding: 10px 25px; border-radius: 25px; display: inline-block; margin-bottom: 20px;">
                <span style="color: white; font-weight: bold; font-size: 16px;">🎁 Earn <?php echo esc_html($reward_percent); ?>% AQY Coins Reward!</span>
            </div>
            <?php endif; ?>
            
            <!-- Action Buttons -->
            <div style="display: flex; justify-content: center; gap: 10px; flex-wrap: wrap;">
                <?php if ($atts['print'] === 'yes') : ?>
                <button type="button" onclick="mreStorefrontPrint('<?php echo esc_attr($qr_id); ?>')" 
                        style="background: rgba(255,255,255,0.1); border: 1px solid rgba(255,255,255,0.3); color: white; padding: 10px 20px; border-radius: 8px; cursor: pointer; font-size: 14px;">
                    🖨️ Print QR
                </button>
                <?php endif; ?>
                
                <?php if ($atts['download'] === 'yes') : ?>
                <a href="<?php echo esc_url($qr_url); ?>" download="<?php echo esc_attr(sanitize_title($store_name)); ?>-payment-qr.png" 
                   style="background: rgba(255,255,255,0.1); border: 1px solid rgba(255,255,255,0.3); color: white; padding: 10px 20px; border-radius: 8px; text-decoration: none; font-size: 14px;">
                    💾 Download QR
                </a>
                <?php endif; ?>
            </div>
            
            <!-- Merchant Wallet (truncated) -->
            <p style="color: #666; font-size: 11px; margin-top: 20px; word-break: break-all;">
                Wallet: <?php echo esc_html(substr($merchant_wallet, 0, 10) . '...' . substr($merchant_wallet, -8)); ?>
            </p>
        </div>
        
        <script>
        function mreStorefrontPrint(containerId) {
            var container = document.getElementById(containerId);
            var qrImg = container.querySelector('.mre-qr-image');
            var storeName = container.querySelector('p').innerText;
            
            var printWindow = window.open('', '_blank');
            printWindow.document.write('<html><head><title>M2C Payment QR Code</title>');
            printWindow.document.write('<style>body { font-family: Arial, sans-serif; text-align: center; padding: 40px; }');
            printWindow.document.write('h1 { color: #333; margin-bottom: 10px; }');
            printWindow.document.write('p { color: #666; margin: 10px 0; }');
            printWindow.document.write('.qr { margin: 20px auto; }');
            printWindow.document.write('.reward { background: linear-gradient(135deg, #f39c12, #e74c3c); color: white; padding: 15px 30px; border-radius: 30px; display: inline-block; margin: 20px 0; font-weight: bold; }');
            printWindow.document.write('.instructions { margin-top: 30px; padding: 20px; border: 2px dashed #ddd; border-radius: 10px; }');
            printWindow.document.write('</style></head><body>');
            printWindow.document.write('<h1>📱 Pay with Red Envelope Wallet</h1>');
            printWindow.document.write('<h2>' + storeName + '</h2>');
            printWindow.document.write('<div class="qr"><img src="' + qrImg.src + '" width="300" height="300" /></div>');
            printWindow.document.write('<div class="reward">🎁 Earn <?php echo esc_js($reward_percent); ?>% AQY Coins Reward!</div>');
            printWindow.document.write('<div class="instructions">');
            printWindow.document.write('<p><strong>How to Pay:</strong></p>');
            printWindow.document.write('<p>1. Open <strong>Red Envelope Wallet</strong> app</p>');
            printWindow.document.write('<p>2. Tap the camera icon 📷 to scan this QR code</p>');
            printWindow.document.write('<p>3. Enter the amount and confirm payment</p>');
            printWindow.document.write('<p>4. Receive your AQY Coins reward instantly!</p>');
            printWindow.document.write('</div>');
            printWindow.document.write('<p style="margin-top:30px; color:#999; font-size:12px;">Powered by M2C Red Envelope</p>');
            printWindow.document.write('</body></html>');
            printWindow.document.close();
            printWindow.focus();
            setTimeout(function() { printWindow.print(); }, 500);
        }
        </script>
        <?php
        return ob_get_clean();
    }
}
