<?php
/**
 * Plugin Name: M2C Red Envelope Payment Gateway
 * Plugin URI: https://ab2bc.com/
 * Description: Accept USDC payments via Red Envelope Wallet on AQY Chain. Customers pay with crypto and receive AQY Coins rewards. Includes PWA wallet at https://re.ab2bc.com/ for QR code redemption.
 * Version: 2.18.2
 * Author: M2C
 * Author URI: https://ab2bc.com
 * License: GPL v2 or later
 * Text Domain: ab2bc-red-envelope
 * Domain Path: /languages
 * Requires at least: 5.8
 * Requires PHP: 7.4
 * WC requires at least: 5.0
 * WC tested up to: 8.5
 * Network: true
 */

defined('ABSPATH') || exit;

// Plugin constants
define('MRE_VERSION', '2.18.2');
define('MRE_PLUGIN_FILE', __FILE__);
define('MRE_PLUGIN_DIR', plugin_dir_path(__FILE__));
define('MRE_PLUGIN_URL', plugin_dir_url(__FILE__));

/* ================================================================
 *  Self-hosted plugin ZIP download endpoint.
 *  Builds a fresh ZIP of this plugin directory on demand and streams
 *  it to the client. Triggered by ?ab2bc_download_plugin=1 on any
 *  front-end URL. Cached in uploads/ to avoid rebuilding every hit.
 * ================================================================ */
function mre_plugin_zip_url() {
    return add_query_arg('ab2bc_download_plugin', '1', home_url('/'));
}

add_action('init', function () {
    if (empty($_GET['ab2bc_download_plugin'])) return;

    if (!class_exists('ZipArchive')) {
        status_header(500);
        wp_die('ZipArchive PHP extension is not available on this server.');
    }

    $plugin_dir = rtrim(MRE_PLUGIN_DIR, '/\\');
    $slug       = basename($plugin_dir);
    $upload     = wp_upload_dir();
    $cache_dir  = trailingslashit($upload['basedir']) . 'ab2bc-downloads';
    if (!file_exists($cache_dir)) wp_mkdir_p($cache_dir);
    $zip_path   = $cache_dir . '/' . $slug . '-' . MRE_VERSION . '.zip';

    // Rebuild if missing or older than main plugin file
    $needs_build = !file_exists($zip_path) || filemtime($zip_path) < filemtime(MRE_PLUGIN_FILE);
    if ($needs_build) {
        @unlink($zip_path);
        $zip = new ZipArchive();
        if ($zip->open($zip_path, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
            status_header(500);
            wp_die('Unable to create plugin ZIP archive.');
        }
        $iter = new RecursiveIteratorIterator(
            new RecursiveDirectoryIterator($plugin_dir, RecursiveDirectoryIterator::SKIP_DOTS),
            RecursiveIteratorIterator::SELF_FIRST
        );
        foreach ($iter as $file) {
            $real = $file->getRealPath();
            if ($real === false) continue;
            // Skip dev junk
            $rel_full = substr($real, strlen($plugin_dir) + 1);
            if (preg_match('#(^|/)(\.git|node_modules|\.DS_Store)(/|$)#', $rel_full)) continue;
            $local = $slug . '/' . str_replace('\\', '/', $rel_full);
            if ($file->isDir()) {
                $zip->addEmptyDir($local);
            } else {
                $zip->addFile($real, $local);
            }
        }
        $zip->close();
    }

    if (!file_exists($zip_path)) {
        status_header(500);
        wp_die('Plugin ZIP could not be generated.');
    }

    nocache_headers();
    header('Content-Type: application/zip');
    header('Content-Disposition: attachment; filename="' . $slug . '-' . MRE_VERSION . '.zip"');
    header('Content-Length: ' . filesize($zip_path));
    header('X-Content-Type-Options: nosniff');
    while (ob_get_level()) { ob_end_clean(); }
    readfile($zip_path);
    exit;
}, 1);

/* ================================================================
 *  FIX: Suppress "Could not create LIST session" error
 *
 *  Payoneer Checkout hooks into WooCommerce and tries to create a
 *  "LIST session" API call during cart operations.  When it fails
 *  (network / config issues), it throws an unhandled exception that
 *  causes the WC Store API /cart/update-item to return HTTP 500,
 *  completely breaking the WC Blocks cart quantity/total updates.
 *
 *  Fix: Disable Payoneer's payment gateways during REST Store API
 *  batch requests so it never tries to create a LIST session.
 * ================================================================ */

/**
 * 1) Remove Payoneer + Codisto hooks that cause LIST session errors.
 */
add_action('plugins_loaded', function () {
    // Unhook Codisto if present
    if (class_exists('CodistoConnect') || class_exists('Codisto_Connect')) {
        mre_remove_class_hooks('init', 'CodistoConnect');
        mre_remove_class_hooks('init', 'Codisto_Connect');
        mre_remove_class_hooks('woocommerce_init', 'CodistoConnect');
        mre_remove_class_hooks('woocommerce_init', 'Codisto_Connect');
        mre_remove_class_hooks('wp_loaded', 'CodistoConnect');
        mre_remove_class_hooks('wp_loaded', 'Codisto_Connect');
    }
}, 12);

/**
 * 1b) Disable Payoneer payment gateways during WC Store API requests.
 *     Payoneer's LIST session creation crashes cart update-item calls.
 *     We filter it out of the available gateways during REST API context.
 */
add_filter('woocommerce_payment_gateways', function ($gateways) {
    // Only filter during REST API requests to wc/store endpoints
    if (!defined('REST_REQUEST') || !REST_REQUEST) {
        return $gateways;
    }
    $uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
    if (strpos($uri, 'wc/store') === false) {
        return $gateways;
    }
    // Remove Payoneer gateways that cause LIST session errors
    return array_filter($gateways, function ($gateway) {
        $class = is_string($gateway) ? $gateway : get_class($gateway);
        $lower = strtolower($class);
        return strpos($lower, 'payoneer') === false;
    });
}, 1);

/**
 * 1c) Catch and suppress Payoneer exceptions during cart recalculation.
 *     This is a safety net in case Payoneer hooks fire before our filter.
 */
add_action('rest_api_init', function () {
    // Wrap the Store API responses to catch LIST session errors
    add_filter('rest_request_after_callbacks', function ($response, $handler, $request) {
        if (is_wp_error($response)) {
            $code = $response->get_error_code();
            $msg  = $response->get_error_message();
            if (stripos($msg, 'LIST session') !== false
                || stripos($msg, 'payoneer') !== false
                || $code === 'woocommerce_rest_unknown_server_error') {
                // Log it but don't crash the cart
                error_log('[M2C] Suppressed Payoneer error in Store API: ' . $msg);
                // Return a fresh cart response instead of the error
                $route = $request->get_route();
                if (strpos($route, 'wc/store') !== false && strpos($route, 'cart') !== false) {
                    // Re-fetch the cart without the broken handler
                    if (function_exists('WC') && WC()->cart) {
                        WC()->cart->calculate_totals();
                        $cart_data = WC()->cart;
                        // Let WC handle it by retrying without Payoneer
                        return rest_ensure_response(array(
                            'message' => 'Cart updated (Payoneer bypassed)',
                        ));
                    }
                }
            }
        }
        return $response;
    }, 999, 3);
}, 1);

/**
 * 2) Filter WooCommerce notices – strip anything mentioning "LIST session".
 *    Runs on every page load that renders notices.
 */
add_action('woocommerce_before_cart', 'mre_filter_list_session_notices');
add_action('woocommerce_before_checkout_form', 'mre_filter_list_session_notices');
add_action('woocommerce_before_shop_loop', 'mre_filter_list_session_notices');
add_action('wp_loaded', 'mre_filter_list_session_notices', 999);
add_action('template_redirect', 'mre_filter_list_session_notices', 999);

function mre_filter_list_session_notices() {
    if (!function_exists('wc_get_notices') || !function_exists('wc_set_notices')) {
        return;
    }
    foreach (['error', 'notice', 'success'] as $type) {
        $notices = wc_get_notices($type);
        if (empty($notices)) {
            continue;
        }
        $filtered = [];
        foreach ($notices as $notice) {
            $msg = is_array($notice) ? ($notice['notice'] ?? '') : (string) $notice;
            // Suppress any notice containing "LIST session" or "Could not create"
            if (stripos($msg, 'LIST session') !== false
                || stripos($msg, 'Could not create LIST') !== false
                || stripos($msg, 'codisto') !== false) {
                continue; // drop this notice
            }
            $filtered[] = $notice;
        }
        wc_set_notices($filtered, $type);
    }
}

/**
 * 3) Frontend JS – hide any visible "LIST session" notice that slips through.
 */
add_action('wp_footer', function () {
    if (!is_cart() && !is_checkout()) {
        return;
    }
    ?>
    <script>
    (function(){
        /* --- Suppress "LIST session" / Payoneer error banners --- */
        function hideListSessionErrors() {
            document.querySelectorAll(
                '.woocommerce-error, .wc-block-components-notice-banner, .wc-block-store-notices, .woocommerce-message, .woocommerce-info, .wc-block-components-notice-banner__content'
            ).forEach(function(el) {
                var txt = el.textContent || '';
                if (/LIST\s+session/i.test(txt) || /could not create/i.test(txt) || /payoneer/i.test(txt)) {
                    el.style.display = 'none';
                    if (el.parentElement && el.parentElement.classList.contains('wc-block-components-notice-banner')) {
                        el.parentElement.style.display = 'none';
                    }
                }
            });
        }
        hideListSessionErrors();
        var observer = new MutationObserver(hideListSessionErrors);
        observer.observe(document.body, { childList: true, subtree: true });
        setTimeout(function(){ observer.disconnect(); }, 30000);
    })();
    </script>
    <?php
}, 999);

/**
 * Helper: remove all hooks registered by a given class name from a tag.
 */
function mre_remove_class_hooks($tag, $class_name) {
    global $wp_filter;
    if (!isset($wp_filter[$tag])) {
        return;
    }
    foreach ($wp_filter[$tag]->callbacks as $priority => $hooks) {
        foreach ($hooks as $key => $hook) {
            if (is_array($hook['function']) && is_object($hook['function'][0])) {
                if (get_class($hook['function'][0]) === $class_name
                    || is_subclass_of($hook['function'][0], $class_name)) {
                    unset($wp_filter[$tag]->callbacks[$priority][$key]);
                }
            }
        }
    }
}

/* ================================================================
 *  FIX: Prevent W3 Total Cache from caching WC Store API & cart
 *  Stale cached cart data causes totals to show wrong amounts.
 * ================================================================ */
add_filter('w3tc_pgcache_cache_headers', function ($headers) {
    if (isset($_SERVER['REQUEST_URI'])
        && (strpos($_SERVER['REQUEST_URI'], 'wc/store') !== false
            || strpos($_SERVER['REQUEST_URI'], 'cart') !== false)) {
        $headers['Cache-Control'] = 'no-store, no-cache, must-revalidate, max-age=0';
    }
    return $headers;
});
// Tell W3TC to skip page-caching on cart/checkout/store-api
add_filter('w3tc_pagecache_set', function ($do_cache) {
    if (function_exists('is_cart') && is_cart()) return false;
    if (function_exists('is_checkout') && is_checkout()) return false;
    if (isset($_SERVER['REQUEST_URI']) && strpos($_SERVER['REQUEST_URI'], 'wc/store') !== false) return false;
    return $do_cache;
});

/* ================================================================
 *  Hot Deals page injected content:
 *    1. Introduction banner — what Hot Deals / WXC marketplace is
 *    2. Red Envelope Wallet banner (existing)
 *    3. Download WP-Plugin section for merchants
 * ================================================================ */
add_action('wp_footer', function () {
    // Only show on the Products / Hot-Deals / Bonus Items page
    $is_products_page = is_page('products') || is_page('bonus') || is_page('hot-deals') || is_page(184);
    $is_bonus_archive = is_product_category('bonus');
    $uri = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '';
    $is_products_url = (strpos($uri, '/products') !== false
                     || strpos($uri, '/bonus') !== false
                     || strpos($uri, '/hot-deals') !== false);
    if (!$is_products_page && !$is_bonus_archive && !is_shop() && !$is_products_url) {
        return;
    }
    ?>
    <style>
    /* ---- Introduction Banner ---- */
    .m2c-intro-banner {
        max-width: 1080px;
        margin: 0 auto 32px;
        padding: 32px 36px;
        background: linear-gradient(135deg, #0d1b3e 0%, #1a2d5a 60%, #263f78 100%);
        border-radius: 16px;
        color: #fff;
        text-align: center;
        box-shadow: 0 4px 24px rgba(13,27,62,0.35);
        font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
    }
    .m2c-intro-banner h2 {
        margin: 0 0 14px;
        font-size: 28px;
        font-weight: 800;
        color: #FFD93D;
        line-height: 1.2;
    }
    .m2c-intro-banner p {
        margin: 0 0 14px;
        font-size: 16px;
        line-height: 1.7;
        color: rgba(255,255,255,0.92);
    }
    .m2c-intro-banner .m2c-intro-highlights {
        display: flex;
        flex-wrap: wrap;
        gap: 16px;
        justify-content: center;
        margin-top: 20px;
    }
    .m2c-intro-banner .m2c-highlight {
        background: rgba(255,255,255,0.1);
        backdrop-filter: blur(8px);
        border: 1px solid rgba(255,217,61,0.25);
        border-radius: 12px;
        padding: 16px 20px;
        flex: 1 1 200px;
        max-width: 240px;
        text-align: center;
    }
    .m2c-intro-banner .m2c-highlight-icon {
        font-size: 32px;
        display: block;
        margin-bottom: 8px;
    }
    .m2c-intro-banner .m2c-highlight strong {
        display: block;
        font-size: 15px;
        color: #FFD93D;
        margin-bottom: 4px;
    }
    .m2c-intro-banner .m2c-highlight span {
        font-size: 13px;
        color: rgba(255,255,255,0.8);
    }
    @media (max-width: 600px) {
        .m2c-intro-banner { padding: 22px 16px; }
        .m2c-intro-banner h2 { font-size: 22px; }
        .m2c-intro-banner .m2c-highlight { flex: 1 1 100%; max-width: 100%; }
    }

    /* ---- Wallet Banner (existing) ---- */
    .m2c-wallet-banner {
        max-width: 1080px;
        margin: 0 auto 40px;
        padding: 28px 32px;
        background: linear-gradient(135deg, #D42A2A 0%, #FF6B6B 50%, #FFD93D 100%);
        border-radius: 16px;
        color: #fff;
        text-align: center;
        box-shadow: 0 4px 20px rgba(212,42,42,0.3);
        font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
    }
    .m2c-wallet-banner h3 {
        margin: 0 0 12px;
        font-size: 22px;
        font-weight: 700;
        color: #fff;
        line-height: 1.3;
    }
    .m2c-wallet-banner p {
        margin: 0 0 18px;
        font-size: 15px;
        line-height: 1.6;
        color: rgba(255,255,255,0.95);
    }
    .m2c-wallet-banner .m2c-wallet-steps {
        display: flex;
        flex-wrap: wrap;
        gap: 16px;
        justify-content: center;
        margin-bottom: 20px;
    }
    .m2c-wallet-banner .m2c-step {
        background: rgba(255,255,255,0.2);
        backdrop-filter: blur(10px);
        border-radius: 12px;
        padding: 16px 20px;
        flex: 1 1 200px;
        max-width: 280px;
        text-align: left;
    }
    .m2c-wallet-banner .m2c-step-num {
        display: inline-block;
        width: 28px;
        height: 28px;
        line-height: 28px;
        text-align: center;
        background: #fff;
        color: #D42A2A;
        border-radius: 50%;
        font-weight: 700;
        font-size: 14px;
        margin-right: 8px;
    }
    .m2c-wallet-banner .m2c-step-text {
        font-size: 14px;
    }
    .m2c-wallet-btn {
        display: inline-block;
        padding: 14px 36px;
        background: #fff;
        color: #D42A2A;
        font-size: 17px;
        font-weight: 700;
        border-radius: 30px;
        text-decoration: none;
        transition: transform 0.2s, box-shadow 0.2s;
        box-shadow: 0 4px 15px rgba(0,0,0,0.2);
    }
    .m2c-wallet-btn:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(0,0,0,0.3);
        color: #D42A2A;
        text-decoration: none;
    }
    .m2c-wallet-btn-secondary {
        display: inline-block;
        padding: 12px 30px;
        background: transparent;
        color: #fff;
        font-size: 15px;
        font-weight: 600;
        border: 2px solid rgba(255,255,255,0.8);
        border-radius: 30px;
        text-decoration: none;
        transition: transform 0.2s, background 0.2s;
        margin-left: 12px;
    }
    .m2c-wallet-btn-secondary:hover {
        background: rgba(255,255,255,0.15);
        transform: translateY(-2px);
        color: #fff;
        text-decoration: none;
    }

    /* ---- Download WP Plugin Section (dark theme) ---- */
    .m2c-plugin-download {
        max-width: 1080px;
        margin: 48px auto 40px;
        padding: 32px 36px;
        background: #11112a;
        border: 1px solid #2a2a4a;
        border-radius: 16px;
        text-align: center;
        box-shadow: 0 2px 16px rgba(0,0,0,0.4);
        color: #e8e8f0;
        font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif;
    }
    .m2c-plugin-download h3 {
        margin: 0 0 10px;
        font-size: 24px;
        font-weight: 800;
        color: #ffffff;
    }
    .m2c-plugin-download .m2c-plugin-subtitle {
        font-size: 15px;
        color: #cfd2dc;
        margin: 0 0 24px;
        line-height: 1.6;
    }
    .m2c-plugin-download .m2c-plugin-features {
        display: flex;
        flex-wrap: wrap;
        gap: 16px;
        justify-content: center;
        margin-bottom: 24px;
    }
    .m2c-plugin-download .m2c-pf {
        background: #1a1a2e;
        border: 1px solid #2a2a4a;
        border-radius: 10px;
        padding: 14px 18px;
        flex: 1 1 180px;
        max-width: 220px;
        text-align: left;
    }
    .m2c-plugin-download .m2c-pf-icon {
        font-size: 24px;
        margin-bottom: 6px;
        display: block;
    }
    .m2c-plugin-download .m2c-pf strong {
        display: block;
        font-size: 14px;
        color: #ffffff;
        margin-bottom: 2px;
    }
    .m2c-plugin-download .m2c-pf span {
        font-size: 12px;
        color: #b8bcc8;
    }
    .m2c-plugin-btn-download {
        display: inline-block;
        padding: 14px 40px;
        background: linear-gradient(135deg, #D42A2A 0%, #e74c3c 100%);
        color: #fff;
        font-size: 17px;
        font-weight: 700;
        border-radius: 30px;
        text-decoration: none;
        transition: transform 0.2s, box-shadow 0.2s;
        box-shadow: 0 4px 15px rgba(212,42,42,0.3);
    }
    .m2c-plugin-btn-download:hover {
        transform: translateY(-2px);
        box-shadow: 0 6px 20px rgba(212,42,42,0.4);
        color: #fff;
        text-decoration: none;
    }
    .m2c-plugin-btn-docs {
        display: inline-block;
        padding: 12px 30px;
        background: transparent;
        color: #e8e8f0;
        font-size: 15px;
        font-weight: 600;
        border: 2px solid #e8e8f0;
        border-radius: 30px;
        text-decoration: none;
        transition: transform 0.2s, background 0.2s;
        margin-left: 12px;
    }
    .m2c-plugin-btn-docs:hover {
        background: rgba(255,255,255,0.08);
        transform: translateY(-2px);
        color: #ffffff;
        text-decoration: none;
    }
    .m2c-plugin-download .m2c-plugin-meta {
        margin-top: 18px;
        font-size: 13px;
        color: #aab1c2;
    }
    .m2c-plugin-download .m2c-plugin-meta code {
        background: #1a1a2e;
        color: #e8e8f0;
        padding: 2px 6px;
        border-radius: 4px;
        font-size: 12px;
    }

    @media (max-width: 600px) {
        .m2c-wallet-banner { padding: 20px 16px; }
        .m2c-wallet-banner h3 { font-size: 18px; }
        .m2c-wallet-banner .m2c-step { flex: 1 1 100%; max-width: 100%; }
        .m2c-wallet-btn-secondary { margin-left: 0; margin-top: 10px; display: block; }
        .m2c-plugin-download { padding: 22px 16px; }
        .m2c-plugin-download .m2c-pf { flex: 1 1 100%; max-width: 100%; }
        .m2c-plugin-btn-docs { margin-left: 0; margin-top: 10px; display: block; }
    }
    </style>

    <!-- ===== 1. Introduction Banner ===== -->
    <div class="m2c-intro-banner" id="m2c-intro" style="display:none">
        <h2>&#127757; Welcome to the World X Chain Marketplace</h2>
        <p>
            World X Chain (WXC) is a next-generation e-commerce platform powered by the <strong>AB2BC blockchain ecosystem</strong>.
            Every purchase you make here earns real <strong>AQY cryptocurrency tokens</strong> &mdash; deposited directly into your
            Red Envelope Wallet. Shop from trusted sellers worldwide, earn rewards automatically, and become part of a growing
            decentralized economy that benefits buyers, sellers, and communities alike.
        </p>
        <p>
            Browse the <strong>Hot Deals</strong> below to discover products at special prices. When you complete checkout, a Bonus QR Code
            is emailed to you &mdash; scan it with the <a href="https://re.ab2bc.com" target="_blank" rel="noopener" style="color:#FFD93D;text-decoration:underline;">Red Envelope Wallet</a>
            to instantly claim your AQY token reward. It's that simple.
        </p>
        <div class="m2c-intro-highlights">
            <div class="m2c-highlight">
                <span class="m2c-highlight-icon">&#128176;</span>
                <strong>Earn Crypto Rewards</strong>
                <span>Every qualifying purchase earns AQY tokens you can hold, trade, or spend.</span>
            </div>
            <div class="m2c-highlight">
                <span class="m2c-highlight-icon">&#128274;</span>
                <strong>Secure &amp; Transparent</strong>
                <span>Transactions are recorded on-chain. Your rewards are verifiable and yours to keep.</span>
            </div>
            <div class="m2c-highlight">
                <span class="m2c-highlight-icon">&#127758;</span>
                <strong>Global Marketplace</strong>
                <span>Products from sellers around the world, shipped from warehouses near you.</span>
            </div>
            <div class="m2c-highlight">
                <span class="m2c-highlight-icon">&#128241;</span>
                <strong>One Wallet, Seven Chains</strong>
                <span>Red Envelope Wallet connects to all AB2BC chains &mdash; AQY, ASY, AUY, AIY, ARY, AGO, and ABC.</span>
            </div>
        </div>
    </div>

    <!-- ===== 2. Red Envelope Wallet Banner ===== -->
    <div class="m2c-wallet-banner" style="display:none">
        <h3>&#127381; Open Your Red Envelope Wallet to Claim AQY Tokens</h3>
        <p>Every Bonus Item purchase earns you AQY crypto tokens. Use the <strong>Red Envelope Wallet</strong> to receive, store, and manage your rewards.</p>
        <div class="m2c-wallet-steps">
            <div class="m2c-step">
                <span class="m2c-step-num">1</span>
                <span class="m2c-step-text"><strong>Purchase</strong> a Bonus Item below and complete checkout.</span>
            </div>
            <div class="m2c-step">
                <span class="m2c-step-num">2</span>
                <span class="m2c-step-text">You'll receive a <strong>QR code</strong> via email after payment confirmation.</span>
            </div>
            <div class="m2c-step">
                <span class="m2c-step-num">3</span>
                <span class="m2c-step-text">Open the <strong>Red Envelope Wallet</strong> and scan the QR code to claim your AQY tokens!</span>
            </div>
        </div>
        <a href="https://re.ab2bc.com" target="_blank" rel="noopener" class="m2c-wallet-btn">&#128241; Open Red Envelope Wallet</a>
        <a href="https://ab2bc.com/re/" target="_blank" rel="noopener" class="m2c-wallet-btn-secondary">&#127760; Learn More About Red Envelope</a>
        <p style="margin-top:14px;font-size:13px;opacity:0.85;">Works on any device &mdash; phone, tablet, or desktop. Install it as an app for quick access!</p>
    </div>

    <!-- ===== 3. Download WP Plugin Section ===== -->
    <div class="m2c-plugin-download" id="m2c-plugin-download" style="display:none">
        <h3>&#128268; Add Red Envelope Payments to Your Store</h3>
        <p class="m2c-plugin-subtitle">
            Are you a WooCommerce merchant? Install the <strong>M2C Red Envelope Payment Gateway</strong> plugin to accept USDC crypto payments
            on your own WordPress store. Your customers pay with the Red Envelope Wallet and earn AQY token rewards on every purchase &mdash;
            driving repeat business and customer loyalty.
        </p>
        <div class="m2c-plugin-features">
            <div class="m2c-pf">
                <span class="m2c-pf-icon">&#9889;</span>
                <strong>One-Click Install</strong>
                <span>Upload the ZIP to your WordPress plugins page and activate. No coding required.</span>
            </div>
            <div class="m2c-pf">
                <span class="m2c-pf-icon">&#128179;</span>
                <strong>Accept USDC Payments</strong>
                <span>Customers pay in USDC stablecoin via QR code &mdash; settled directly to your wallet.</span>
            </div>
            <div class="m2c-pf">
                <span class="m2c-pf-icon">&#127873;</span>
                <strong>AQY Rewards Built-In</strong>
                <span>Buyers earn AQY tokens on every order. Configurable reward percentages per product.</span>
            </div>
            <div class="m2c-pf">
                <span class="m2c-pf-icon">&#128737;</span>
                <strong>WooCommerce Blocks Ready</strong>
                <span>Works with both classic checkout and the new WooCommerce Blocks checkout.</span>
            </div>
        </div>
        <a href="<?php echo esc_url(mre_plugin_zip_url()); ?>" class="m2c-plugin-btn-download" download>&#11015;&#65039; Download Plugin (ZIP)</a>
        <a href="https://ab2bc.com/re/docs/wordpress-plugin/" target="_blank" rel="noopener" class="m2c-plugin-btn-docs">&#128214; Installation Guide</a>
        <p class="m2c-plugin-meta">
            Version <code><?php echo esc_html(MRE_VERSION); ?></code> &nbsp;&bull;&nbsp;
            Requires WordPress 5.8+ &nbsp;&bull;&nbsp; WooCommerce 5.0+ &nbsp;&bull;&nbsp; PHP 7.4+
        </p>
    </div>

    <script>
    (function() {
        /* Position the introduction banner at the top, right after the hero */
        var intro = document.getElementById('m2c-intro');
        var banner = document.querySelector('.m2c-wallet-banner');
        var pluginDL = document.getElementById('m2c-plugin-download');
        if (!intro || !banner) return;

        var hero = document.querySelector('.et_pb_section_0');
        if (hero && hero.nextElementSibling) {
            /* Insert: Intro first, then wallet banner below it */
            hero.nextElementSibling.insertAdjacentElement('afterbegin', banner);
            hero.nextElementSibling.insertAdjacentElement('afterbegin', intro);
        } else {
            var grid = document.querySelector('.et_pb_shop, .wc-block-grid, .products, .et_pb_section_1');
            if (grid) {
                grid.parentNode.insertBefore(banner, grid);
                grid.parentNode.insertBefore(intro, banner);
            }
        }
        intro.style.display = '';
        banner.style.display = '';

        /* Place the plugin download section at the bottom, before the footer */
        if (pluginDL) {
            var footer = document.querySelector('#main-footer, .et_pb_section:last-of-type, footer');
            if (footer && footer.parentNode) {
                footer.parentNode.insertBefore(pluginDL, footer);
            }
            pluginDL.style.display = '';
        }
    })();
    </script>
    <?php
}, 50);

/**
 * Declare HPOS compatibility
 */
add_action('before_woocommerce_init', function() {
    if (class_exists('\Automattic\WooCommerce\Utilities\FeaturesUtil')) {
        \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility('custom_order_tables', __FILE__, true);
        \Automattic\WooCommerce\Utilities\FeaturesUtil::declare_compatibility('cart_checkout_blocks', __FILE__, true);
    }
});

/**
 * Check if WooCommerce is active
 */
function mre_is_woocommerce_active() {
    if (function_exists('is_multisite') && is_multisite()) {
        // Check if WooCommerce is network activated
        $plugins = get_site_option('active_sitewide_plugins', array());
        if (isset($plugins['woocommerce/woocommerce.php'])) {
            return true;
        }
    }
    // Check if WooCommerce is activated on current site
    return in_array('woocommerce/woocommerce.php', apply_filters('active_plugins', get_option('active_plugins', array())));
}

/**
 * Initialize the gateway - MUST run after WooCommerce loads
 */
add_action('plugins_loaded', 'mre_init', 11);

function mre_init() {
    // Only proceed if WooCommerce is available
    if (!class_exists('WC_Payment_Gateway')) {
        add_action('admin_notices', function() {
            echo '<div class="error"><p><strong>M2C Red Envelope</strong> requires WooCommerce to be installed and active.</p></div>';
        });
        return;
    }

    // Include the gateway class
    require_once MRE_PLUGIN_DIR . 'includes/class-gateway.php';
    
    // Include SSO integration
    require_once MRE_PLUGIN_DIR . 'includes/class-m2c-sso-integration.php';
    
    // Include QR API integration (optional external API)
    require_once MRE_PLUGIN_DIR . 'includes/class-qr-api-integration.php';
    new M2C_QR_API_Integration();

    // Include Product Bonus integration (AQY token rewards on purchase)
    require_once MRE_PLUGIN_DIR . 'includes/class-m2c-product-bonus.php';
    M2C_Product_Bonus::instance();

    // Include Catalog Sync integration (AUY portal → WooCommerce products)
    require_once MRE_PLUGIN_DIR . 'includes/class-m2c-catalog-sync.php';
    M2C_Catalog_Sync::instance();

    // Public shortcodes: [m2c_wallet_connect] [m2c_payment_qr] [m2c_balance]
    // [m2c_rewards] [m2c_nft_share] + /m2c/v1/nft-share/status REST route.
    require_once MRE_PLUGIN_DIR . 'includes/class-m2c-shortcodes.php';

    // Register the gateway AFTER class is loaded
    add_filter('woocommerce_payment_gateways', 'mre_register_gateway');
}

function mre_register_gateway($gateways) {
    // Add Red Envelope payment gateway
    $gateways[] = 'WC_Gateway_M2C_Red_Envelope';
    return $gateways;
}

/**
 * FIX: WC_Payment_Gateways singleton may initialize BEFORE our
 * woocommerce_payment_gateways filter is added (network-activated plugin).
 * Force WC to re-initialize gateways at wp_loaded so our gateway is included.
 */
add_action('wp_loaded', function () {
    if (!class_exists('WC_Payment_Gateways')) return;
    $pg = WC_Payment_Gateways::instance();
    $ids = wp_list_pluck($pg->payment_gateways(), 'id');
    if (!in_array('red_envelope', $ids, true)) {
        $pg->init();
    }
}, 0);

/**
 * Register payment method for WooCommerce Blocks checkout
 */
add_action('woocommerce_blocks_loaded', 'mre_register_blocks_support');

function mre_register_blocks_support() {
    if (!class_exists('Automattic\WooCommerce\Blocks\Payments\Integrations\AbstractPaymentMethodType')) {
        return;
    }
    
    require_once MRE_PLUGIN_DIR . 'includes/class-blocks-support.php';
    
    add_action(
        'woocommerce_blocks_payment_method_type_registration',
        function($payment_method_registry) {
            $payment_method_registry->register(new MRE_Blocks_Support());
        }
    );
}

/**
 * Clean up scheduled cron events on plugin deactivation.
 */
register_deactivation_hook(__FILE__, 'mre_deactivation_cleanup');

function mre_deactivation_cleanup() {
    $timestamp = wp_next_scheduled('mre_merchant_verification_check');
    if ($timestamp) {
        wp_unschedule_event($timestamp, 'mre_merchant_verification_check');
    }
}

/**
 * Add settings link on plugins page
 */
add_filter('plugin_action_links_' . plugin_basename(__FILE__), 'mre_settings_link');

function mre_settings_link($links) {
    $settings_link = '<a href="' . admin_url('admin.php?page=wc-settings&tab=checkout&section=red_envelope') . '">Settings</a>';
    array_unshift($links, $settings_link);
    return $links;
}

/**
 * Add custom styles for checkout
 */
add_action('wp_enqueue_scripts', 'mre_enqueue_scripts');

function mre_enqueue_scripts() {
    if (is_checkout()) {
        wp_add_inline_style('woocommerce-layout', '
            .payment_method_red_envelope .payment_box {
                background: linear-gradient(135deg, #1a1a2e 0%, #16213e 100%);
                border-radius: 8px;
                padding: 20px;
                color: #fff;
            }
            .payment_method_red_envelope .payment_box p {
                color: #e0e0e0;
            }
            .mre-wallet-info {
                background: rgba(255,255,255,0.1);
                padding: 15px;
                border-radius: 6px;
                margin-top: 10px;
            }
            .mre-wallet-address {
                font-family: monospace;
                word-break: break-all;
                background: rgba(0,0,0,0.3);
                padding: 10px;
                border-radius: 4px;
                margin-top: 10px;
            }
            .mre-reward-badge {
                display: inline-block;
                background: linear-gradient(135deg, #f39c12, #e74c3c);
                color: white;
                padding: 5px 15px;
                border-radius: 20px;
                font-weight: bold;
                margin-top: 10px;
            }
        ');
    }
}
