<?php
/**
 * M2C Product Bonus Integration
 *
 * Connects WooCommerce products to M2C AQY token bonuses.
 * When a customer purchases a bonus-eligible product, a QR code is
 * generated via the M2C Backend API and emailed to the buyer.
 *
 * @package M2C_Red_Envelope
 * @since   2.5.0
 */

defined('ABSPATH') || exit;

class M2C_Product_Bonus {

    /** @var self|null */
    private static $instance = null;

    /* ── Meta keys ─────────────────────────────────────── */
    const META_BONUS_ENABLED    = '_m2c_bonus_enabled';
    const META_BONUS_PRODUCT_ID = '_m2c_bonus_product_id';
    const META_BONUS_AMOUNT     = '_m2c_bonus_amount';
    const META_ORDER_PROCESSED  = '_m2c_bonus_processed';
    const META_ORDER_BONUSES    = '_m2c_bonus_data';
    const META_CUSTOMER_WALLET  = '_m2c_customer_wallet';

    /* ── Singleton ─────────────────────────────────────── */

    public static function instance() {
        if (null === self::$instance) {
            self::$instance = new self();
        }
        return self::$instance;
    }

    private function __construct() {
        $this->init_hooks();
    }

    /* ── Option helpers ────────────────────────────────── */

    private function get_api_url() {
        return rtrim(get_option('m2c_bonus_api_url', ''), '/');
    }

    private function get_api_key() {
        return get_option('m2c_bonus_api_key', '');
    }

    private function get_redeem_base_url() {
        return rtrim(get_option('m2c_bonus_redeem_url', ''), '/');
    }

    private function is_auto_redeem() {
        return get_option('m2c_bonus_auto_redeem', 'yes') === 'yes';
    }

    private function is_email_enabled() {
        return get_option('m2c_bonus_send_email', 'yes') === 'yes';
    }

    /* ================================================================
     *  HOOKS
     * ================================================================ */

    private function init_hooks() {
        // Settings
        add_action('admin_menu', [$this, 'add_settings_page']);
        add_action('admin_init', [$this, 'register_settings']);

        // Product meta box
        add_action('add_meta_boxes', [$this, 'add_bonus_meta_box']);
        add_action('woocommerce_process_product_meta', [$this, 'save_bonus_meta']);

        // Product display – badge
        add_action('woocommerce_single_product_summary', [$this, 'display_bonus_badge'], 25);
        add_action('woocommerce_after_shop_loop_item_title', [$this, 'display_bonus_badge_loop'], 15);

        // Cart – bonus info
        add_filter('woocommerce_get_item_data', [$this, 'display_bonus_in_cart'], 10, 2);

        // Checkout – wallet field
        add_action('woocommerce_after_order_notes', [$this, 'add_wallet_checkout_field']);
        add_action('woocommerce_checkout_update_order_meta', [$this, 'save_wallet_from_checkout']);

        // Order completion – generate & deliver bonus
        add_action('woocommerce_payment_complete', [$this, 'process_order_bonus']);
        add_action('woocommerce_order_status_completed', [$this, 'process_order_bonus']);

        // Order display
        add_action('woocommerce_order_details_after_order_table', [$this, 'display_bonus_in_customer_order']);
        add_action('woocommerce_admin_order_data_after_billing', [$this, 'display_bonus_in_admin_order']);

        // Products list column
        add_filter('manage_edit-product_columns', [$this, 'add_bonus_column']);
        add_action('manage_product_posts_custom_column', [$this, 'render_bonus_column'], 10, 2);

        // AJAX – resend email
        add_action('wp_ajax_m2c_resend_bonus_email', [$this, 'ajax_resend_bonus_email']);
    }

    /* ================================================================
     *  SETTINGS PAGE  (WooCommerce → AQY Bonus)
     * ================================================================ */

    public function add_settings_page() {
        add_submenu_page(
            'woocommerce',
            'M2C AQY Bonus Settings',
            '🎁 AQY Bonus',
            'manage_woocommerce',
            'm2c-aqy-bonus',
            [$this, 'render_settings_page']
        );
    }

    public function register_settings() {
        $fields = [
            'm2c_bonus_api_url'      => 'M2C Backend API URL',
            'm2c_bonus_api_key'      => 'API Key',
            'm2c_bonus_redeem_url'   => 'Consumer Redeem Base URL',
            'm2c_bonus_auto_redeem'  => 'Auto-redeem if wallet known',
            'm2c_bonus_send_email'   => 'Email QR code to buyer',
            'm2c_bonus_email_subject'=> 'Bonus Email Subject',
        ];
        foreach ($fields as $key => $label) {
            register_setting('m2c_bonus_settings', $key);
        }
    }

    public function render_settings_page() {
        $api_url    = $this->get_api_url();
        $api_key    = $this->get_api_key();
        $redeem_url = $this->get_redeem_base_url();
        $auto       = get_option('m2c_bonus_auto_redeem', 'yes');
        $email      = get_option('m2c_bonus_send_email', 'yes');
        $subject    = get_option('m2c_bonus_email_subject', '🎁 Your AQY Token Bonus from {store_name}');

        // Quick connectivity check
        $connected = false;
        if ($api_url && $api_key) {
            $test = $this->api_request('/api/product-bonus/dashboard');
            $connected = ($test && isset($test['success']) && $test['success']);
        }
        ?>
        <div class="wrap">
            <h1>🎁 M2C AQY Bonus Products</h1>
            <p>Connect WooCommerce products to AQY token bonuses. Customers who purchase qualifying products automatically receive bonus AQY token QR codes via email.</p>

            <?php if ($api_url && $api_key): ?>
                <div class="notice notice-<?php echo $connected ? 'success' : 'error'; ?> inline" style="margin:10px 0 20px;">
                    <p><?php echo $connected ? '✅ Connected to M2C Backend' : '❌ Cannot reach M2C Backend — check URL and API key'; ?></p>
                </div>
            <?php endif; ?>

            <form method="post" action="options.php">
                <?php settings_fields('m2c_bonus_settings'); ?>
                <table class="form-table">
                    <tr>
                        <th>M2C Backend URL</th>
                        <td>
                            <input type="url" name="m2c_bonus_api_url" value="<?php echo esc_attr($api_url); ?>" class="regular-text" placeholder="https://m2c.ab2bc.com">
                            <p class="description">Base URL of the M2C Backend (e.g. <code>http://localhost:3003</code> for dev)</p>
                        </td>
                    </tr>
                    <tr>
                        <th>API Key</th>
                        <td>
                            <input type="text" name="m2c_bonus_api_key" value="<?php echo esc_attr($api_key); ?>" class="regular-text" placeholder="admin_test_key_12345">
                            <p class="description">Admin API key for the M2C Backend</p>
                        </td>
                    </tr>
                    <tr>
                        <th>Redeem Base URL</th>
                        <td>
                            <input type="url" name="m2c_bonus_redeem_url" value="<?php echo esc_attr($redeem_url); ?>" class="regular-text" placeholder="https://m2c.ab2bc.com/redeem">
                            <p class="description">URL prefix for redemption links (code appended as <code>/REDEEM_CODE</code>)</p>
                        </td>
                    </tr>
                    <tr>
                        <th>Auto-redeem</th>
                        <td>
                            <label><input type="checkbox" name="m2c_bonus_auto_redeem" value="yes" <?php checked($auto, 'yes'); ?>> Automatically redeem bonus if customer provides a wallet address at checkout</label>
                        </td>
                    </tr>
                    <tr>
                        <th>Send Email</th>
                        <td>
                            <label><input type="checkbox" name="m2c_bonus_send_email" value="yes" <?php checked($email, 'yes'); ?>> Email the bonus QR code to the buyer after purchase</label>
                        </td>
                    </tr>
                    <tr>
                        <th>Email Subject</th>
                        <td>
                            <input type="text" name="m2c_bonus_email_subject" value="<?php echo esc_attr($subject); ?>" class="regular-text">
                            <p class="description">Use <code>{store_name}</code> as a placeholder</p>
                        </td>
                    </tr>
                </table>
                <?php submit_button(); ?>
            </form>
        </div>
        <?php
    }

    /* ================================================================
     *  PRODUCT META BOX
     * ================================================================ */

    public function add_bonus_meta_box() {
        add_meta_box(
            'm2c_aqy_bonus',
            '🎁 AQY Token Bonus',
            [$this, 'render_bonus_meta_box'],
            'product',
            'side',
            'high'
        );
    }

    public function render_bonus_meta_box($post) {
        wp_nonce_field('m2c_bonus_meta', '_m2c_bonus_nonce');
        $enabled    = get_post_meta($post->ID, self::META_BONUS_ENABLED, true);
        $product_id = get_post_meta($post->ID, self::META_BONUS_PRODUCT_ID, true);
        $amount     = get_post_meta($post->ID, self::META_BONUS_AMOUNT, true);
        ?>
        <p>
            <label>
                <input type="checkbox" name="m2c_bonus_enabled" value="yes" <?php checked($enabled, 'yes'); ?>>
                Enable AQY bonus for this product
            </label>
        </p>
        <p>
            <label style="display:block;margin-bottom:4px;font-weight:600;">Bonus Product ID</label>
            <input type="text" name="m2c_bonus_product_id" value="<?php echo esc_attr($product_id); ?>"
                   style="width:100%;" placeholder="UUID from M2C Admin console">
            <span class="description" style="display:block;margin-top:2px;">
                Create the bonus product in M2C Admin → Product Bonus → Products, then paste its ID here.
            </span>
        </p>
        <p>
            <label style="display:block;margin-bottom:4px;font-weight:600;">AQY Bonus Amount</label>
            <input type="number" name="m2c_bonus_amount" value="<?php echo esc_attr($amount); ?>"
                   step="0.000001" min="0" style="width:100%;" placeholder="e.g. 25.5">
            <span class="description" style="display:block;margin-top:2px;">AQY tokens the buyer receives per unit purchased</span>
        </p>
        <?php if ($product_id && $amount): ?>
            <div style="background:#f0fdf4;border:1px solid #bbf7d0;padding:8px 10px;border-radius:6px;margin-top:8px;">
                ✅ Bonus active: <strong><?php echo esc_html($amount); ?> AQY</strong> per purchase
            </div>
        <?php endif; ?>
        <?php
    }

    public function save_bonus_meta($post_id) {
        if (!isset($_POST['_m2c_bonus_nonce']) || !wp_verify_nonce($_POST['_m2c_bonus_nonce'], 'm2c_bonus_meta')) return;

        $enabled    = isset($_POST['m2c_bonus_enabled']) ? 'yes' : 'no';
        $product_id = sanitize_text_field($_POST['m2c_bonus_product_id'] ?? '');
        $amount     = floatval($_POST['m2c_bonus_amount'] ?? 0);

        update_post_meta($post_id, self::META_BONUS_ENABLED, $enabled);
        update_post_meta($post_id, self::META_BONUS_PRODUCT_ID, $product_id);
        update_post_meta($post_id, self::META_BONUS_AMOUNT, $amount);
    }

    /* ================================================================
     *  PRODUCT DISPLAY – BONUS BADGE
     * ================================================================ */

    public function display_bonus_badge() {
        global $product;
        if (!$product) return;
        $this->render_badge($product->get_id());
    }

    public function display_bonus_badge_loop() {
        global $product;
        if (!$product) return;
        $this->render_badge($product->get_id(), true);
    }

    private function render_badge($product_id, $compact = false) {
        if (get_post_meta($product_id, self::META_BONUS_ENABLED, true) !== 'yes') return;
        $amount = get_post_meta($product_id, self::META_BONUS_AMOUNT, true);
        if (!$amount || $amount <= 0) return;

        if ($compact) {
            // Shop loop – compact badge only
            $style = 'display:inline-block;background:linear-gradient(135deg,#667eea,#764ba2);color:#fff;padding:3px 10px;border-radius:12px;font-size:11px;font-weight:600;margin-top:6px;';
            echo '<div style="' . $style . '">🎁 Earn ' . esc_html(number_format((float)$amount, 2)) . ' AQY Tokens</div>';
            return;
        }

        // Single product page – badge + redemption instructions
        $formatted = esc_html(number_format((float)$amount, 2));
        ?>
        <div style="margin:16px 0;border:2px solid #667eea;border-radius:12px;padding:0;overflow:hidden;background:#fafafe;">
            <!-- Badge header -->
            <div style="background:linear-gradient(135deg,#667eea,#764ba2);color:#fff;padding:12px 20px;font-size:16px;font-weight:700;">
                🎁 Earn <?php echo $formatted; ?> AQY Tokens with this purchase!
            </div>
            <!-- Redemption steps -->
            <div style="padding:16px 20px;font-size:13px;line-height:1.7;color:#333;">
                <div style="font-weight:700;font-size:14px;margin-bottom:8px;color:#4a4a6a;">📋 How to Claim Your AQY Tokens</div>
                <ol style="margin:0 0 0 18px;padding:0;">
                    <li><strong>Purchase</strong> this product and complete checkout.</li>
                    <li>After payment confirmation, you'll receive a <strong>QR code</strong> via email (and in your order confirmation).</li>
                    <li>Join the <strong>M2C system</strong> using the <strong>Red Envelope Wallet</strong> at
                        <a href="https://re.ab2bc.com/" target="_blank" rel="noopener" style="color:#667eea;text-decoration:underline;font-weight:600;">re.ab2bc.com</a>
                        — works on any device (phone, tablet, desktop). Create or log into your M2C account.</li>
                    <li>In the wallet, tap <strong>"Scan QR"</strong> to scan the QR code from your order.</li>
                    <li><strong><?php echo $formatted; ?> AQY tokens</strong> will be credited as a reward and recorded in your M2C account.</li>
                </ol>
                <div style="margin-top:12px;padding:10px 14px;background:#f0f4ff;border-radius:8px;font-size:12px;color:#555;">
                    💡 <strong>Note:</strong> AQY tokens will be credited to your M2C account after scanning and can be redeemed when the AQY network is in production.
                </div>
            </div>
        </div>
        <?php
    }

    /* ================================================================
     *  CART – BONUS INFO
     * ================================================================ */

    public function display_bonus_in_cart($item_data, $cart_item) {
        $pid = $cart_item['product_id'] ?? 0;
        if (get_post_meta($pid, self::META_BONUS_ENABLED, true) !== 'yes') return $item_data;
        $amount = get_post_meta($pid, self::META_BONUS_AMOUNT, true);
        if (!$amount || $amount <= 0) return $item_data;

        $qty   = $cart_item['quantity'] ?? 1;
        $total = (float)$amount * (int)$qty;

        $item_data[] = [
            'key'   => '🎁 AQY Bonus',
            'value' => number_format($total, 2) . ' AQY tokens',
        ];
        return $item_data;
    }

    /* ================================================================
     *  CHECKOUT – WALLET ADDRESS FIELD
     * ================================================================ */

    public function add_wallet_checkout_field($checkout) {
        // Only show if cart has bonus-eligible products
        $has_bonus = false;
        if (WC()->cart) {
            foreach (WC()->cart->get_cart() as $item) {
                if (get_post_meta($item['product_id'], self::META_BONUS_ENABLED, true) === 'yes') {
                    $has_bonus = true;
                    break;
                }
            }
        }
        if (!$has_bonus) return;

        echo '<div id="m2c_wallet_field" style="margin-top:20px;">';
        echo '<h3 style="color:#667eea;">🎁 AQY Token Bonus</h3>';
        echo '<p style="color:#666;font-size:13px;">Your order includes products with AQY token bonuses! Provide your wallet address for instant redemption, or leave blank to receive a QR code via email.</p>';
        woocommerce_form_field('m2c_customer_wallet', [
            'type'        => 'text',
            'label'       => 'AQY/Sui Wallet Address (optional)',
            'placeholder' => '0x...',
            'required'    => false,
            'class'       => ['form-row-wide'],
            'input_class' => ['wc-enhanced-select'],
        ], $checkout->get_value('m2c_customer_wallet'));
        echo '</div>';
    }

    public function save_wallet_from_checkout($order_id) {
        if (!empty($_POST['m2c_customer_wallet'])) {
            $wallet = sanitize_text_field($_POST['m2c_customer_wallet']);
            $order  = wc_get_order($order_id);
            if ($order) {
                $order->update_meta_data(self::META_CUSTOMER_WALLET, $wallet);
                $order->save();
            }
        }
    }

    /* ================================================================
     *  ORDER PROCESSING – GENERATE & DELIVER BONUS
     * ================================================================ */

    public function process_order_bonus($order_id) {
        $order = wc_get_order($order_id);
        if (!$order) return;

        // Guard – only process once
        if ($order->get_meta(self::META_ORDER_PROCESSED)) return;

        $api_url = $this->get_api_url();
        $api_key = $this->get_api_key();
        if (empty($api_url) || empty($api_key)) return;

        $customer_email  = $order->get_billing_email();
        $customer_name   = $order->get_formatted_billing_full_name();
        $customer_wallet = $order->get_meta(self::META_CUSTOMER_WALLET);
        $all_bonuses     = [];

        foreach ($order->get_items() as $item) {
            $product_id = $item->get_product_id();
            if (get_post_meta($product_id, self::META_BONUS_ENABLED, true) !== 'yes') continue;

            $bonus_product_id = get_post_meta($product_id, self::META_BONUS_PRODUCT_ID, true);
            if (empty($bonus_product_id)) continue;

            $quantity = max(1, (int)$item->get_quantity());
            $bonus_amount = (float)get_post_meta($product_id, self::META_BONUS_AMOUNT, true);

            // Call M2C Backend to generate QR code(s)
            $response = $this->api_request('/api/product-bonus/qr-codes/generate', 'POST', [
                'productId'     => $bonus_product_id,
                'count'         => $quantity,
                'consumerEmail' => $customer_email,
                'consumerName'  => $customer_name,
                'metadata'      => [
                    'source'          => 'woocommerce',
                    'wc_order_id'     => $order->get_id(),
                    'wc_product_id'   => $product_id,
                    'wc_product_name' => $item->get_name(),
                    'store_url'       => home_url(),
                ],
            ]);

            if (!$response || empty($response['success'])) {
                $err = $response['error'] ?? 'Unknown error';
                $order->add_order_note(sprintf('❌ AQY bonus generation failed for "%s": %s', $item->get_name(), $err));
                continue;
            }

            $codes = $response['data'] ?? [];
            foreach ($codes as $code) {
                $entry = [
                    'product_name' => $item->get_name(),
                    'aqy_amount'   => $code['aqy_amount'] ?? $bonus_amount,
                    'redeem_code'  => $code['redeem_code'] ?? '',
                    'qr_code_id'   => $code['qr_code_id'] ?? '',
                    'qr_base64'    => $code['qr_base64'] ?? '',
                    'status'       => 'generated',
                ];

                // Auto-redeem if wallet supplied
                if ($this->is_auto_redeem() && !empty($customer_wallet) && !empty($entry['redeem_code'])) {
                    $redeem = $this->api_request(
                        '/api/product-bonus/redeem/' . $entry['redeem_code'],
                        'POST',
                        ['walletAddress' => $customer_wallet]
                    );
                    if ($redeem && !empty($redeem['redemption_id'])) {
                        $entry['status']        = 'redeemed';
                        $entry['redemption_id'] = $redeem['redemption_id'];
                    }
                }

                $all_bonuses[] = $entry;
            }
        }

        if (empty($all_bonuses)) return;

        // Persist
        $order->update_meta_data(self::META_ORDER_BONUSES, $all_bonuses);
        $order->update_meta_data(self::META_ORDER_PROCESSED, gmdate('Y-m-d H:i:s'));
        $order->save();

        // Order note
        $total_aqy  = array_sum(array_column($all_bonuses, 'aqy_amount'));
        $redeemed   = count(array_filter($all_bonuses, fn($b) => $b['status'] === 'redeemed'));
        $order->add_order_note(sprintf(
            '🎁 AQY Bonus: %s AQY for %d item(s). %s',
            number_format($total_aqy, 2),
            count($all_bonuses),
            $redeemed ? sprintf('%d auto-redeemed to wallet.', $redeemed) : 'QR code(s) emailed.'
        ));

        // Email
        if ($this->is_email_enabled()) {
            $this->send_bonus_email($order, $all_bonuses);
        }
    }

    /* ================================================================
     *  EMAIL DELIVERY
     * ================================================================ */

    private function send_bonus_email($order, $bonuses) {
        $to = $order->get_billing_email();
        if (empty($to)) return false;

        $subject = get_option('m2c_bonus_email_subject', '🎁 Your AQY Token Bonus from {store_name}');
        $subject = str_replace('{store_name}', get_bloginfo('name'), $subject);

        $html = $this->build_email_html($order, $bonuses);

        $headers = [
            'Content-Type: text/html; charset=UTF-8',
            'From: ' . get_bloginfo('name') . ' <' . get_option('admin_email') . '>',
        ];

        $sent = wp_mail($to, $subject, $html, $headers);

        $order->add_order_note($sent
            ? sprintf('📧 AQY bonus email sent to %s', $to)
            : sprintf('❌ Failed to send AQY bonus email to %s', $to)
        );

        return $sent;
    }

    /**
     * Build a professional HTML email with all bonus QR codes.
     */
    private function build_email_html($order, $bonuses) {
        $store   = esc_html(get_bloginfo('name'));
        $name    = esc_html($order->get_formatted_billing_full_name());
        $orderno = esc_html($order->get_order_number());
        $redeem_base = $this->get_redeem_base_url();
        $api_url = $this->get_api_url();
        $total_aqy = array_sum(array_column($bonuses, 'aqy_amount'));

        ob_start();
        ?>
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1.0"></head>
<body style="margin:0;padding:0;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Helvetica,Arial,sans-serif;background:#f4f4f7;">
<div style="max-width:600px;margin:0 auto;padding:20px;">

    <!-- Header -->
    <div style="background:linear-gradient(135deg,#667eea 0%,#764ba2 100%);padding:30px;text-align:center;border-radius:12px 12px 0 0;">
        <h1 style="color:#fff;margin:0;font-size:24px;">🎁 You Earned AQY Tokens!</h1>
        <p style="color:rgba(255,255,255,.9);margin:10px 0 0;font-size:15px;">Thank you for your purchase at <?php echo $store; ?></p>
    </div>

    <!-- Body -->
    <div style="background:#fff;padding:30px;border-left:1px solid #eee;border-right:1px solid #eee;">
        <p style="color:#333;">Hi <?php echo $name; ?>,</p>
        <p style="color:#555;">Great news! Your order <strong>#<?php echo $orderno; ?></strong> includes AQY token bonuses totalling
            <strong style="color:#667eea;"><?php echo number_format($total_aqy, 2); ?> AQY</strong>.
        </p>

        <?php foreach ($bonuses as $i => $bonus):
            $code   = esc_html($bonus['redeem_code'] ?? '');
            $amount = number_format((float)($bonus['aqy_amount'] ?? 0), 2);
            $pname  = esc_html($bonus['product_name'] ?? 'Product');
            $redeemed = ($bonus['status'] ?? '') === 'redeemed';

            // Build redeem URL
            $redeem_url = '';
            if ($redeem_base && $code) {
                $redeem_url = $redeem_base . '/' . $code;
            } elseif ($api_url && $code) {
                $redeem_url = $api_url . '/api/product-bonus/redeem/' . $code;
            }

            // QR image via external service (email-compatible)
            $qr_img_url = $redeem_url
                ? 'https://api.qrserver.com/v1/create-qr-code/?size=200x200&data=' . urlencode($redeem_url)
                : '';
        ?>
        <div style="background:#f8f9ff;border:1px solid rgba(102,126,234,.2);border-radius:10px;padding:24px;margin:20px 0;text-align:center;">
            <h3 style="color:#333;margin:0 0 4px;font-size:16px;"><?php echo $pname; ?></h3>
            <div style="font-size:32px;font-weight:bold;color:#667eea;margin:12px 0;"><?php echo $amount; ?> AQY</div>

            <?php if ($qr_img_url): ?>
                <img src="<?php echo esc_url($qr_img_url); ?>" width="200" height="200" alt="Bonus QR Code"
                     style="display:block;margin:10px auto;border-radius:8px;">
            <?php endif; ?>

            <?php if ($redeemed): ?>
                <p style="color:#22c55e;font-weight:bold;margin:12px 0 0;">✅ Automatically credited to your wallet</p>
            <?php else: ?>
                <p style="font-size:12px;color:#999;margin:8px 0 0;">Scan with Red Envelope Wallet or tap below</p>
                <?php if ($redeem_url): ?>
                    <a href="<?php echo esc_url($redeem_url); ?>"
                       style="display:inline-block;background:#667eea;color:#fff;padding:10px 28px;border-radius:8px;text-decoration:none;font-weight:600;margin-top:12px;">
                        Redeem Now
                    </a>
                <?php endif; ?>
            <?php endif; ?>

            <?php if ($code): ?>
                <p style="font-size:11px;color:#bbb;margin:12px 0 0;word-break:break-all;">Code: <?php echo $code; ?></p>
            <?php endif; ?>
        </div>
        <?php endforeach; ?>

        <!-- How to Redeem -->
        <div style="background:#f0fdf4;border:1px solid #bbf7d0;border-radius:8px;padding:16px;margin-top:24px;">
            <h4 style="margin:0 0 10px;color:#166534;font-size:14px;">How to Redeem</h4>
            <ol style="margin:0;padding-left:20px;color:#333;font-size:13px;line-height:1.8;">
                <li>Open the <strong>Red Envelope Wallet</strong> app</li>
                <li>Go to <strong>Scan QR</strong> and scan the code above</li>
                <li>Your AQY tokens will be added to your rewards balance</li>
                <li>Tokens transfer to your wallet when AQY mainnet launches</li>
            </ol>
        </div>

        <p style="color:#999;font-size:12px;margin-top:24px;">
            ℹ️ Each QR code can only be redeemed once. If you have trouble, contact the store or visit
            <a href="https://ab2bc.com" style="color:#667eea;">ab2bc.com</a>.
        </p>
    </div>

    <!-- Footer -->
    <div style="text-align:center;padding:20px;color:#999;font-size:12px;border-top:1px solid #eee;background:#fafafa;border-radius:0 0 12px 12px;">
        <p style="margin:0 0 4px;">Powered by M2C × World X Chain</p>
        <p style="margin:0;"><?php echo $store; ?></p>
    </div>

</div>
</body>
</html>
        <?php
        return ob_get_clean();
    }

    /* ================================================================
     *  DISPLAY BONUS IN ORDER (Customer My Account)
     * ================================================================ */

    public function display_bonus_in_customer_order($order) {
        $bonuses = $order->get_meta(self::META_ORDER_BONUSES);
        if (empty($bonuses) || !is_array($bonuses)) return;

        $redeem_base = $this->get_redeem_base_url();
        $api_url = $this->get_api_url();

        echo '<h2 style="color:#667eea;">🎁 AQY Token Bonuses</h2>';
        echo '<table class="woocommerce-table" style="width:100%;border-collapse:collapse;">';
        echo '<thead><tr><th style="text-align:left;padding:8px;border-bottom:2px solid #ddd;">Product</th><th style="text-align:center;padding:8px;border-bottom:2px solid #ddd;">AQY Amount</th><th style="text-align:center;padding:8px;border-bottom:2px solid #ddd;">Status</th><th style="text-align:center;padding:8px;border-bottom:2px solid #ddd;">QR Code</th></tr></thead><tbody>';

        foreach ($bonuses as $bonus) {
            $code   = $bonus['redeem_code'] ?? '';
            $amount = number_format((float)($bonus['aqy_amount'] ?? 0), 2);
            $pname  = esc_html($bonus['product_name'] ?? '');
            $status = $bonus['status'] ?? 'generated';
            $redeemed = $status === 'redeemed';

            $redeem_url = '';
            if ($redeem_base && $code) $redeem_url = $redeem_base . '/' . $code;
            elseif ($api_url && $code) $redeem_url = $api_url . '/api/product-bonus/redeem/' . $code;

            $qr_html = '';
            if (!empty($bonus['qr_base64'])) {
                $qr_html = '<img src="data:image/png;base64,' . esc_attr($bonus['qr_base64']) . '" width="80" height="80" style="border-radius:6px;">';
            } elseif ($redeem_url) {
                $qr_html = '<img src="https://api.qrserver.com/v1/create-qr-code/?size=80x80&data=' . urlencode($redeem_url) . '" width="80" height="80">';
            }

            $status_html = $redeemed
                ? '<span style="color:#22c55e;font-weight:600;">✅ Redeemed</span>'
                : '<span style="color:#667eea;font-weight:600;">📱 Scan to Redeem</span>';

            echo '<tr>';
            echo '<td style="padding:10px;border-bottom:1px solid #eee;">' . $pname . '</td>';
            echo '<td style="padding:10px;border-bottom:1px solid #eee;text-align:center;font-weight:bold;color:#667eea;">' . $amount . ' AQY</td>';
            echo '<td style="padding:10px;border-bottom:1px solid #eee;text-align:center;">' . $status_html . '</td>';
            echo '<td style="padding:10px;border-bottom:1px solid #eee;text-align:center;">' . $qr_html . '</td>';
            echo '</tr>';

            if (!$redeemed && $redeem_url) {
                echo '<tr><td colspan="4" style="padding:4px 10px 12px;border-bottom:1px solid #eee;text-align:center;">';
                echo '<a href="' . esc_url($redeem_url) . '" style="color:#667eea;font-size:12px;" target="_blank">Click to redeem online →</a>';
                echo '</td></tr>';
            }
        }

        echo '</tbody></table>';
    }

    /* ================================================================
     *  DISPLAY BONUS IN ADMIN ORDER
     * ================================================================ */

    public function display_bonus_in_admin_order($order) {
        $bonuses = $order->get_meta(self::META_ORDER_BONUSES);
        if (empty($bonuses) || !is_array($bonuses)) return;

        $total_aqy = array_sum(array_column($bonuses, 'aqy_amount'));

        echo '<div style="margin-top:16px;padding:12px;background:#f8f9ff;border:1px solid #667eea33;border-radius:8px;">';
        echo '<h3 style="margin:0 0 8px;color:#667eea;">🎁 AQY Bonus (' . count($bonuses) . ' code' . (count($bonuses) > 1 ? 's' : '') . ' — ' . number_format($total_aqy, 2) . ' AQY)</h3>';

        foreach ($bonuses as $bonus) {
            $status = ($bonus['status'] ?? 'generated') === 'redeemed' ? '✅ Redeemed' : '⏳ Pending';
            echo '<div style="padding:4px 0;font-size:13px;">';
            echo '<strong>' . esc_html($bonus['product_name'] ?? '') . '</strong> — ';
            echo number_format((float)($bonus['aqy_amount'] ?? 0), 2) . ' AQY — ';
            echo $status;
            if (!empty($bonus['redeem_code'])) {
                echo ' <code style="font-size:11px;background:#eee;padding:2px 6px;border-radius:3px;">' . esc_html(substr($bonus['redeem_code'], 0, 12)) . '…</code>';
            }
            echo '</div>';
        }

        // Resend email button
        echo '<div style="margin-top:10px;">';
        echo '<button type="button" class="button" onclick="m2cResendBonusEmail(' . $order->get_id() . ')">📧 Resend Bonus Email</button>';
        echo '<span id="m2c-resend-status" style="margin-left:10px;"></span>';
        echo '</div>';

        echo '</div>';

        // Inline JS for resend
        ?>
        <script>
        function m2cResendBonusEmail(orderId) {
            var btn = event.target;
            btn.disabled = true;
            btn.textContent = 'Sending…';
            jQuery.post(ajaxurl, {
                action: 'm2c_resend_bonus_email',
                order_id: orderId,
                _wpnonce: '<?php echo wp_create_nonce('m2c_resend_bonus'); ?>'
            }, function(r) {
                btn.disabled = false;
                btn.textContent = '📧 Resend Bonus Email';
                document.getElementById('m2c-resend-status').innerHTML =
                    r.success ? '<span style="color:green;">✅ Sent!</span>' : '<span style="color:red;">❌ ' + (r.data || 'Failed') + '</span>';
            });
        }
        </script>
        <?php
    }

    /* ================================================================
     *  AJAX – RESEND BONUS EMAIL
     * ================================================================ */

    public function ajax_resend_bonus_email() {
        check_ajax_referer('m2c_resend_bonus', '_wpnonce');

        if (!current_user_can('manage_woocommerce')) {
            wp_send_json_error('Unauthorized');
        }

        $order_id = intval($_POST['order_id'] ?? 0);
        $order    = wc_get_order($order_id);
        if (!$order) wp_send_json_error('Order not found');

        $bonuses = $order->get_meta(self::META_ORDER_BONUSES);
        if (empty($bonuses)) wp_send_json_error('No bonus data for this order');

        $sent = $this->send_bonus_email($order, $bonuses);
        $sent ? wp_send_json_success('Email sent') : wp_send_json_error('Email sending failed');
    }

    /* ================================================================
     *  PRODUCTS LIST – BONUS COLUMN
     * ================================================================ */

    public function add_bonus_column($columns) {
        $new = [];
        foreach ($columns as $key => $label) {
            $new[$key] = $label;
            if ($key === 'price') {
                $new['m2c_bonus'] = 'AQY Bonus';
            }
        }
        return $new;
    }

    public function render_bonus_column($column, $post_id) {
        if ($column !== 'm2c_bonus') return;

        $enabled = get_post_meta($post_id, self::META_BONUS_ENABLED, true);
        if ($enabled === 'yes') {
            $amount = get_post_meta($post_id, self::META_BONUS_AMOUNT, true);
            echo '<span style="background:#667eea22;color:#667eea;padding:2px 8px;border-radius:10px;font-weight:600;font-size:12px;">'
                . esc_html(number_format((float)$amount, 2)) . ' AQY</span>';
        } else {
            echo '<span style="color:#ccc;">—</span>';
        }
    }

    /* ================================================================
     *  API REQUEST HELPER
     * ================================================================ */

    /**
     * Make an authenticated request to the M2C Backend.
     *
     * @param  string       $endpoint  e.g. '/api/product-bonus/dashboard'
     * @param  string       $method    GET | POST | PUT | DELETE
     * @param  array|null   $body      JSON body (for POST/PUT)
     * @return array|null   Decoded JSON or null on failure
     */
    private function api_request($endpoint, $method = 'GET', $body = null) {
        $url = $this->get_api_url() . $endpoint;
        $key = $this->get_api_key();

        if (empty($url) || empty($key)) return null;

        $args = [
            'method'  => $method,
            'timeout' => 30,
            'headers' => [
                'Content-Type' => 'application/json',
                'x-api-key'    => $key,
            ],
        ];

        if ($body !== null && in_array($method, ['POST', 'PUT'])) {
            $args['body'] = wp_json_encode($body);
        }

        $response = wp_remote_request($url, $args);

        if (is_wp_error($response)) {
            error_log('[M2C Bonus] API error: ' . $response->get_error_message());
            return null;
        }

        $code = wp_remote_retrieve_response_code($response);
        $json = json_decode(wp_remote_retrieve_body($response), true);

        if ($code >= 400) {
            error_log(sprintf('[M2C Bonus] API %s %s → HTTP %d: %s', $method, $endpoint, $code, wp_remote_retrieve_body($response)));
        }

        return $json;
    }
}
