<?php
/**
 * M2C Red Envelope Payment Gateway
 * WooCommerce Payment Gateway Implementation
 */

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

class M2C_Red_Envelope_Payment_Gateway extends WC_Payment_Gateway {
    
    private $api;
    
    public function __construct() {
        $this->id = 'm2c_red_envelope';
        $this->icon = MRE_PLUGIN_URL . 'assets/images/m2c-icon.png';
        $this->has_fields = true;
        $this->method_title = __('Red Envelope Payment', 'ab2bc-red-envelope');
        $this->method_description = __('Accept cryptocurrency payments via Red Envelope Wallet on AQY Chain with QR codes. Supports USDC, AQY, and automatic AQY Coin reward distribution.', 'ab2bc-red-envelope');
        
        // Supports for WooCommerce
        $this->supports = array(
            'products',
            'refunds',
        );
        
        // Load settings
        $this->init_form_fields();
        $this->init_settings();
        
        // Gateway settings
        $this->title = $this->get_option('title');
        $this->description = $this->get_option('description');
        $this->enabled = $this->get_option('enabled');
        $this->merchant_wallet = $this->get_option('merchant_wallet_address');
        $this->commission_rate = $this->get_option('commission_rate', '7.5');
        $this->qr_expiry = $this->get_option('qr_expiry_minutes', '10');
        $this->supported_tokens = $this->get_option('supported_tokens', 'USDC');
        $this->default_token = $this->get_option('default_token', 'USDC');
        $this->enable_rewards = $this->get_option('enable_rewards', 'yes');
        
        // Initialize API client
        $this->api = new M2C_API_Client();
        
        // Hooks
        add_action('woocommerce_update_options_payment_gateways_' . $this->id, array($this, 'process_admin_options'));
        add_action('woocommerce_thankyou_' . $this->id, array($this, 'thankyou_page'));
        add_action('woocommerce_api_m2c_webhook', array($this, 'webhook_handler'));
    }
    
    /**
     * Initialize gateway settings form fields
     */
    public function init_form_fields() {
        $this->form_fields = array(
            'enabled' => array(
                'title' => __('Enable/Disable', 'ab2bc-red-envelope'),
                'type' => 'checkbox',
                'label' => __('Enable M2C Red Envelope Payment', 'ab2bc-red-envelope'),
                'default' => 'no',
            ),
            'title' => array(
                'title' => __('Title', 'ab2bc-red-envelope'),
                'type' => 'text',
                'description' => __('Payment method title that customers see during checkout.', 'ab2bc-red-envelope'),
                'default' => __('Red Envelope Payment', 'ab2bc-red-envelope'),
                'desc_tip' => true,
            ),
            'description' => array(
                'title' => __('Description', 'ab2bc-red-envelope'),
                'type' => 'textarea',
                'description' => __('Payment method description that customers see during checkout.', 'ab2bc-red-envelope'),
                'default' => __('Use Red Envelope Payment to pay via USDC (AQY Chain) and receive 60% of the AQY Coin rewards. You will receive AQY Coin reward to your Red Envelope Wallet in seconds as a receipt and a confirmation email when the order is shipped.', 'ab2bc-red-envelope'),
                'desc_tip' => true,
            ),
            'merchant_wallet_address' => array(
                'title' => __('Merchant Wallet Address', 'ab2bc-red-envelope'),
                'type' => 'text',
                'description' => __('Your Red Envelope Wallet address on AQY Chain where payments will be received.', 'ab2bc-red-envelope'),
                'default' => '',
                'desc_tip' => true,
                'custom_attributes' => array(
                    'required' => 'required',
                ),
            ),
            'commission_rate' => array(
                'title' => __('Commission Rate (%)', 'ab2bc-red-envelope'),
                'type' => 'number',
                'description' => __('Your merchant commission rate (e.g., 7.5 for 7.5%).', 'ab2bc-red-envelope'),
                'default' => '7.5',
                'desc_tip' => true,
                'custom_attributes' => array(
                    'step' => '0.1',
                    'min' => '0',
                    'max' => '100',
                ),
            ),
            'qr_expiry_minutes' => array(
                'title' => __('QR Code Expiry (minutes)', 'ab2bc-red-envelope'),
                'type' => 'number',
                'description' => __('How long the payment QR code remains valid.', 'ab2bc-red-envelope'),
                'default' => '10',
                'desc_tip' => true,
                'custom_attributes' => array(
                    'min' => '1',
                    'max' => '60',
                ),
            ),
            'supported_tokens' => array(
                'title' => __('Supported Tokens', 'ab2bc-red-envelope'),
                'type' => 'text',
                'description' => __('Comma-separated list of supported tokens (e.g., USDC).', 'ab2bc-red-envelope'),
                'default' => 'USDC',
                'desc_tip' => true,
            ),
            'default_token' => array(
                'title' => __('Default Token', 'ab2bc-red-envelope'),
                'type' => 'select',
                'description' => __('Default token for payment display.', 'ab2bc-red-envelope'),
                'default' => 'USDC',
                'options' => array(
                    'USDC' => 'USDC',
                    'AQY' => 'AQY',
                    'GC' => 'GC',
                ),
                'desc_tip' => true,
            ),
            'enable_rewards' => array(
                'title' => __('Enable AB2BC Rewards', 'ab2bc-red-envelope'),
                'type' => 'checkbox',
                'label' => __('Enable automatic AQY reward distribution', 'ab2bc-red-envelope'),
                'default' => 'yes',
                'description' => __('When enabled, customers receive AQY rewards on purchases.', 'ab2bc-red-envelope'),
            ),
            'api_settings' => array(
                'title' => __('API Configuration', 'ab2bc-red-envelope'),
                'type' => 'title',
                'description' => __('Configure AB2BC API endpoints.', 'ab2bc-red-envelope'),
            ),
            'm2c_api_url' => array(
                'title' => __('AB2BC API URL', 'ab2bc-red-envelope'),
                'type' => 'text',
                'description' => __('M2C Backend API base URL.', 'ab2bc-red-envelope'),
                'default' => 'http://192.168.0.4:3000/api',
                'desc_tip' => true,
            ),
            'genesis_api_url' => array(
                'title' => __('Genesis API URL', 'ab2bc-red-envelope'),
                'type' => 'text',
                'description' => __('Genesis API base URL for blockchain operations.', 'ab2bc-red-envelope'),
                'default' => 'http://192.168.0.4:3104/api',
                'desc_tip' => true,
            ),
            'explorer_url' => array(
                'title' => __('Explorer URL', 'ab2bc-red-envelope'),
                'type' => 'text',
                'description' => __('Blockchain explorer URL for transaction viewing.', 'ab2bc-red-envelope'),
                'default' => 'http://192.168.0.4:3108',
                'desc_tip' => true,
            ),
        );
    }
    
    /**
     * Payment fields on checkout page
     */
    public function payment_fields() {
        if ($this->description) {
            echo wpautop(wptexturize($this->description));
        }
        
        $tokens = array_map('trim', explode(',', $this->supported_tokens));
        ?>
        <div class="m2c-payment-fields">
            <p class="form-row form-row-wide">
                <label for="m2c_token"><?php _e('Payment Token', 'ab2bc-red-envelope'); ?> <span class="required">*</span></label>
                <select id="m2c_token" name="m2c_token" class="input-select">
                    <?php foreach ($tokens as $token): ?>
                        <option value="<?php echo esc_attr($token); ?>" <?php selected($token, $this->default_token); ?>>
                            <?php echo esc_html($token); ?>
                        </option>
                    <?php endforeach; ?>
                </select>
            </p>
            
            <p class="form-row form-row-wide">
                <label for="m2c_wallet_address"><?php _e('Your Red Envelope Wallet Address (Optional)', 'ab2bc-red-envelope'); ?></label>
                <input type="text" id="m2c_wallet_address" name="m2c_wallet_address" 
                       class="input-text" placeholder="0x..." 
                       pattern="^0x[a-fA-F0-9]{40,}$" />
                <small><?php _e('Enter your Red Envelope Wallet address to receive AQY Coin rewards automatically.', 'ab2bc-red-envelope'); ?></small>
            </p>
            
            <?php if ($this->enable_rewards === 'yes'): ?>
            <div class="m2c-rewards-info" style="background: #f0f9ff; border: 1px solid #0ea5e9; border-radius: 4px; padding: 12px; margin-top: 10px;">
                <p style="margin: 0; color: #0369a1; font-size: 14px;">
                    <strong>🎁 <?php _e('Earn AQY Coin Rewards!', 'ab2bc-red-envelope'); ?></strong><br>
                    <?php _e('Receive AQY Coin rewards instantly to your Red Envelope Wallet on AQY Chain!', 'ab2bc-red-envelope'); ?>
                </p>
            </div>
            <?php endif; ?>
        </div>
        <?php
    }
    
    /**
     * Validate payment fields
     */
    public function validate_fields() {
        if (empty($_POST['m2c_token'])) {
            wc_add_notice(__('Please select a payment token.', 'ab2bc-red-envelope'), 'error');
            return false;
        }
        
        $wallet_address = isset($_POST['m2c_wallet_address']) ? sanitize_text_field($_POST['m2c_wallet_address']) : '';
        
        if (!empty($wallet_address) && !preg_match('/^0x[a-fA-F0-9]{40,}$/', $wallet_address)) {
            wc_add_notice(__('Invalid wallet address format.', 'ab2bc-red-envelope'), 'error');
            return false;
        }
        
        return true;
    }
    
    /**
     * Process payment
     */
    public function process_payment($order_id) {
        $order = wc_get_order($order_id);
        
        // Get payment details
        $token = isset($_POST['m2c_token']) ? sanitize_text_field($_POST['m2c_token']) : $this->default_token;
        $customer_wallet = isset($_POST['m2c_wallet_address']) ? sanitize_text_field($_POST['m2c_wallet_address']) : '';
        
        // Save payment metadata
        $order->update_meta_data('_m2c_payment_token', $token);
        $order->update_meta_data('_m2c_customer_wallet', $customer_wallet);
        $order->update_meta_data('_m2c_merchant_wallet', $this->merchant_wallet);
        $order->update_meta_data('_m2c_commission_rate', $this->commission_rate);
        
        // Generate QR code
        $qr_generator = new M2C_QR_Generator();
        $qr_data = $qr_generator->generate_payment_qr(array(
            'order_id' => $order_id,
            'amount' => $order->get_total(),
            'token' => $token,
            'merchant_wallet' => $this->merchant_wallet,
            'customer_wallet' => $customer_wallet,
            'expiry_minutes' => $this->qr_expiry,
        ));
        
        if ($qr_data) {
            $order->update_meta_data('_m2c_qr_data', json_encode($qr_data));
            $order->update_meta_data('_m2c_qr_expiry', time() + ($this->qr_expiry * 60));
        }
        
        // Mark as pending payment
        $order->update_status('wc-awaiting-m2c', __('Awaiting AB2BC payment', 'ab2bc-red-envelope'));
        $order->save();
        
        // Reduce stock
        wc_reduce_stock_levels($order_id);
        
        // Empty cart
        WC()->cart->empty_cart();
        
        // Return success and redirect
        return array(
            'result' => 'success',
            'redirect' => $this->get_return_url($order),
        );
    }
    
    /**
     * Thank you page output
     */
    public function thankyou_page($order_id) {
        $order = wc_get_order($order_id);
        $qr_data_json = $order->get_meta('_m2c_qr_data');
        $qr_data = json_decode($qr_data_json, true);
        
        if (!$qr_data) {
            return;
        }
        
        $token = $order->get_meta('_m2c_payment_token');
        $amount = $order->get_total();
        $customer_wallet = $order->get_meta('_m2c_customer_wallet');
        $qr_expiry = $order->get_meta('_m2c_qr_expiry');
        $time_remaining = max(0, $qr_expiry - time());
        
        include MRE_PLUGIN_DIR . 'templates/payment-qr.php';
    }
    
    /**
     * Webhook handler for payment notifications
     */
    public function webhook_handler() {
        $webhook = new M2C_Webhook_Handler();
        $webhook->handle();
    }
    
    /**
     * Check if the gateway needs setup
     * Returns true if merchant wallet is not configured
     */
    public function needs_setup() {
        return empty($this->merchant_wallet);
    }
    
    /**
     * Get setup button label
     */
    public function get_setup_button_label() {
        return __('Complete Setup', 'ab2bc-red-envelope');
    }
    
    /**
     * Check if gateway is available
     */
    public function is_available() {
        // Gateway not available if wallet not configured
        if (empty($this->merchant_wallet)) {
            return false;
        }
        
        return parent::is_available();
    }
    
    /**
     * Admin options with setup wizard
     */
    public function admin_options() {
        $needs_setup = $this->needs_setup();
        
        if ($needs_setup) {
            ?>
            <div class="m2c-setup-wizard" style="background: linear-gradient(135deg, #E53935 0%, #C62828 100%); color: white; padding: 30px; border-radius: 8px; margin-bottom: 20px;">
                <h2 style="color: white; margin-top: 0;">🧧 <?php _e('Welcome to M2C Red Envelope Payment!', 'ab2bc-red-envelope'); ?></h2>
                <p style="font-size: 16px; opacity: 0.9;">
                    <?php _e('Complete the setup below to start accepting AQY Chain cryptocurrency payments with automatic reward distribution.', 'ab2bc-red-envelope'); ?>
                </p>
                <div style="background: rgba(255,255,255,0.15); padding: 15px; border-radius: 6px; margin-top: 15px;">
                    <h3 style="color: #FFD700; margin-top: 0;">📋 <?php _e('Quick Setup Checklist:', 'ab2bc-red-envelope'); ?></h3>
                    <ul style="list-style: none; padding: 0; margin: 0;">
                        <li style="padding: 8px 0; border-bottom: 1px solid rgba(255,255,255,0.2);">
                            <span style="color: <?php echo empty($this->merchant_wallet) ? '#ff6b6b' : '#90EE90'; ?>;">
                                <?php echo empty($this->merchant_wallet) ? '❌' : '✅'; ?>
                            </span>
                            <?php _e('Enter your Merchant AB2BC Receiving Account (Wallet Address)', 'ab2bc-red-envelope'); ?>
                        </li>
                        <li style="padding: 8px 0; border-bottom: 1px solid rgba(255,255,255,0.2);">
                            <span style="color: #90EE90;">✅</span>
                            <?php _e('Configure commission rate (default: 7.5%)', 'ab2bc-red-envelope'); ?>
                        </li>
                        <li style="padding: 8px 0; border-bottom: 1px solid rgba(255,255,255,0.2);">
                            <span style="color: #90EE90;">✅</span>
                            <?php _e('Select supported tokens (USDC, AQY)', 'ab2bc-red-envelope'); ?>
                        </li>
                        <li style="padding: 8px 0;">
                            <span style="color: #90EE90;">✅</span>
                            <?php _e('Enable AQY Coin rewards for customers', 'ab2bc-red-envelope'); ?>
                        </li>
                    </ul>
                </div>
            </div>
            <?php
        }
        
        // Show configuration status
        if (!$needs_setup) {
            ?>
            <div style="background: #d4edda; border: 1px solid #28a745; padding: 15px; border-radius: 6px; margin-bottom: 20px;">
                <h3 style="color: #155724; margin-top: 0;">✅ <?php _e('M2C Red Envelope is configured and ready!', 'ab2bc-red-envelope'); ?></h3>
                <p style="color: #155724; margin-bottom: 0;">
                    <?php _e('Merchant Wallet:', 'ab2bc-red-envelope'); ?> 
                    <code style="background: #fff; padding: 2px 8px; border-radius: 4px;"><?php echo esc_html(substr($this->merchant_wallet, 0, 10) . '...' . substr($this->merchant_wallet, -8)); ?></code>
                </p>
            </div>
            <?php
        }
        
        parent::admin_options();
    }
    
    /**
     * Get action links for the payments list
     */
    public function get_action_links() {
        $settings_url = admin_url('admin.php?page=wc-settings&tab=checkout&section=' . $this->id);
        
        if ($this->needs_setup()) {
            return array(
                'setup' => array(
                    'url' => $settings_url,
                    'text' => $this->get_setup_button_label(),
                ),
            );
        }
        
        return array(
            'settings' => array(
                'url' => $settings_url,
                'text' => __('Manage', 'ab2bc-red-envelope'),
            ),
        );
    }
}
