<?php

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

class Cregis_Return_Handler {
    private $api;
    private $logger;

    public function __construct() {
        $settings = get_option('cregis_payment_settings', array());
        $this->logger = new Cregis_Logger(isset($settings['debug']) ? $settings['debug'] : false);

        if (!empty($settings['project_id']) && !empty($settings['secret_key'])) {
            $this->api = new Cregis_API(
                $settings['project_id'],
                $settings['secret_key'],
                isset($settings['api_mode']) ? $settings['api_mode'] : 'test',
                isset($settings['api_url']) ? $settings['api_url'] : null,
                isset($settings['debug']) ? $settings['debug'] : false
            );
        }
    }

    /**
     * Initialize the return handler
     */
    public function init() {
        add_action('template_redirect', array($this, 'handle_return'), 1);
        add_action('wp_footer', array($this, 'maybe_render_popup'));
    }

    /**
     * Render popup on order detail page if cregis_notice parameter is present
     */
    public function maybe_render_popup() {
        if (!isset($_GET['cregis_notice'])) {
            return;
        }
        
        // Only show on order detail pages
        if (!is_wc_endpoint_url('view-order')) {
            return;
        }
        
        $notice_type = sanitize_text_field($_GET['cregis_notice']);
        
        if (!in_array($notice_type, array('underpayment', 'overpayment'))) {
            return;
        }
        
        $this->render_payment_mismatch_popup($notice_type);
    }

    /**
     * Render the payment mismatch popup
     */
    private function render_payment_mismatch_popup($type) {
        // Get current locale
        $locale = get_locale();
        
        if ($type === 'underpayment') {
            // Multi-language support for underpayment
            if (strpos($locale, 'zh_HK') === 0) {
                $title = '需要額外付款';
                $message = '收到的金額與訂單總額不匹配，因此您的商品暫時處於待處理狀態。請檢查您的電子郵件以繼續補款的後續步驟。';
            } elseif (strpos($locale, 'zh_TW') === 0) {
                $title = '需要額外付款';
                $message = '收到的金額與訂單總額不匹配，因此您的商品暫時處於待處理狀態。請檢查您的電子郵件以繼續補款的後續步驟。';
            } elseif (strpos($locale, 'zh_CN') === 0 || strpos($locale, 'zh') === 0) {
                $title = '需要额外付款';
                $message = '收到的金额与订单总额不匹配，因此您的商品暂时处于待处理状态。请检查您的电子邮件以继续补款的后续步骤。';
            } else {
                $title = __('Additional Payment Required', 'cregis-payment-for-woocommerce');
                $message = __('The amount received doesn\'t match your order total, so your item is temporarily on hold. Please check your email for next steps to resolve the balance.', 'cregis-payment-for-woocommerce');
            }
        } else {
            // Multi-language support for overpayment
            if (strpos($locale, 'zh_HK') === 0) {
                $title = '收到多付款';
                $message = '我們收到的金額超過訂單總額，因此您的商品暫時處於待處理狀態。請檢查您的電子郵件以完成部分退款的後續步驟。';
            } elseif (strpos($locale, 'zh_TW') === 0) {
                $title = '收到多付款';
                $message = '我們收到的金額超過訂單總額，因此您的商品暫時處於待處理狀態。請檢查您的電子郵件以完成部分退款的後續步驟。';
            } elseif (strpos($locale, 'zh_CN') === 0 || strpos($locale, 'zh') === 0) {
                $title = '收到多付款';
                $message = '我们收到的金额超过订单总额，因此您的商品暂时处于待处理状态。请检查您的电子邮件以完成部分退款的后续步骤。';
            } else {
                $title = __('Overpayment Received', 'cregis-payment-for-woocommerce');
                $message = __('We received more than the order total, so your item is temporarily on hold. Please check your email for next steps to complete the partial refund.', 'cregis-payment-for-woocommerce');
            }
        }
        
        // Multi-language support for close button
        if (strpos($locale, 'zh_HK') === 0 || strpos($locale, 'zh_TW') === 0) {
            $close_button = '關閉';
        } elseif (strpos($locale, 'zh_CN') === 0 || strpos($locale, 'zh') === 0) {
            $close_button = '关闭';
        } else {
            $close_button = 'Close';
        }
        
        ?>
        <style>
            /* Cregis Payment Mismatch Popup */
            @import url('https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@400;500;700;800&display=swap');
            
            .cregis-popup-overlay {
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background: rgba(0, 0, 0, 0.5);
                z-index: 999998;
                display: flex;
                justify-content: center;
                align-items: center;
                padding: 20px;
                animation: cregisFadeIn 0.3s ease;
            }
            
            @keyframes cregisFadeIn {
                from { opacity: 0; }
                to { opacity: 1; }
            }
            
            .cregis-popup-wrapper {
                position: relative;
                width: 100%;
                max-width: 520px;
                margin-top: 50px;
            }
            
            .cregis-popup-wrapper::after {
                content: '';
                position: absolute;
                bottom: -18px;
                left: 10%;
                width: 80%;
                height: 25px;
                background: rgba(0, 0, 0, 0.18);
                border-radius: 50%;
                filter: blur(12px);
                z-index: 1;
            }
            
            .cregis-popup-card {
                position: relative;
                z-index: 2;
                background-color: #ffffff;
                border-radius: 36px;
                padding: 32px 40px 40px;
                text-align: center;
                box-shadow: 0 10px 30px rgba(0, 0, 0, 0.05);
            }
            
            .cregis-icon-circle {
                width: 120px;
                height: 120px;
                background-color: #fdf5ea;
                border-radius: 50%;
                position: absolute;
                top: -60px;
                left: 50%;
                transform: translateX(-50%);
                display: flex;
                justify-content: center;
                align-items: center;
                box-shadow: 0 6px 16px rgba(0, 0, 0, 0.06);
                z-index: 11;
            }
            
            .cregis-icon-wrapper {
                position: relative;
                width: 90px;
                height: 90px;
                display: flex;
                justify-content: center;
                align-items: center;
            }
            
            .cregis-popup-content {
                margin-top: 50px;
            }
            
            .cregis-popup-title {
                font-family: 'Plus Jakarta Sans', -apple-system, BlinkMacSystemFont, sans-serif;
                font-size: 26px;
                font-weight: 800;
                color: #2b2b2b;
                margin-bottom: 14px;
                letter-spacing: -0.02em;
            }
            
            .cregis-popup-text {
                font-family: 'Plus Jakarta Sans', -apple-system, BlinkMacSystemFont, sans-serif;
                font-size: 14px;
                line-height: 1.6;
                color: #6c757d;
                max-width: 390px;
                margin: 0 auto 30px;
                font-weight: 500;
            }
            
            .cregis-action-btn {
                display: inline-flex;
                align-items: center;
                justify-content: center;
                gap: 8px;
                background-color: #000000;
                color: #ffffff;
                font-family: 'Plus Jakarta Sans', -apple-system, BlinkMacSystemFont, sans-serif;
                font-size: 16px;
                font-weight: 700;
                padding: 16px 36px;
                border: none;
                border-radius: 14px;
                cursor: pointer;
                box-shadow: 0 8px 18px rgba(0, 0, 0, 0.35);
                transition: all 0.2s ease;
                text-decoration: none;
                width: 100%;
                max-width: 260px;
            }
            
            .cregis-action-btn:hover {
                background-color: #333333;
                transform: translateY(-2px);
                box-shadow: 0 10px 22px rgba(0, 0, 0, 0.45);
            }
            
            .cregis-action-btn:active {
                transform: translateY(0);
            }
            
            @media (max-width: 600px) {
                .cregis-popup-card {
                    padding: 24px 20px 30px;
                    border-radius: 24px;
                }
                
                .cregis-popup-title {
                    font-size: 22px;
                }
                
                .cregis-popup-text {
                    font-size: 13px;
                }
            }
        </style>
        
        <div class="cregis-popup-overlay" id="cregis-payment-popup">
            <div class="cregis-popup-wrapper">
                <div class="cregis-popup-card">
                    <div class="cregis-icon-circle">
                        <div class="cregis-icon-wrapper">
                            <svg width="90" height="90" viewBox="0 0 100 100" fill="none" xmlns="http://www.w3.org/2000/svg">
                                <g filter="url(#shadow)">
                                    <circle cx="50" cy="56" r="34" fill="#D94314"/>
                                    <circle cx="50" cy="48" r="34" fill="#F05423"/>
                                    <circle cx="50" cy="48" r="30" stroke="#FFFFFF" stroke-width="2" opacity="0.3"/>
                                    <path d="M50 30V52" stroke="#FFFFFF" stroke-width="7" stroke-linecap="round"/>
                                    <circle cx="50" cy="64" r="4.5" fill="#FFFFFF"/>
                                </g>
                                <defs>
                                    <filter id="shadow" x="0" y="0" width="100" height="100" filterUnits="userSpaceOnUse">
                                        <feDropShadow dx="0" dy="4" stdDeviation="4" flood-opacity="0.18"/>
                                    </filter>
                                </defs>
                            </svg>
                        </div>
                    </div>
                    
                    <div class="cregis-popup-content">
                        <h2 class="cregis-popup-title"><?php echo esc_html($title); ?></h2>
                        <p class="cregis-popup-text"><?php echo esc_html($message); ?></p>
                        <button class="cregis-action-btn" onclick="document.getElementById('cregis-payment-popup').style.display='none'">
                            <?php echo esc_html($close_button); ?>
                        </button>
                    </div>
                </div>
            </div>
        </div>
        <?php
    }

    /**
     * Add body class for styling
     */
    public function add_body_class($classes) {
        if (isset($_GET['cregis_return']) && $_GET['cregis_return'] === '1') {
            $action = isset($_GET['cregis_action']) ? sanitize_text_field($_GET['cregis_action']) : '';
            if (in_array($action, array('thankyou', 'underpayment', 'overpayment'))) {
                $classes[] = 'cregis-return-page';
                $classes[] = 'cregis-' . $action;
            }
        }
        return $classes;
    }

    /**
     * Get the Cregis return URL for an order
     */
    public static function get_return_url($order_id) {
        $order = wc_get_order($order_id);
        $order_key = $order ? $order->get_order_key() : '';
        return add_query_arg(array(
            'cregis_return' => '1',
            'order_id' => $order_id,
            'key' => $order_key,
        ), home_url('/'));
    }

    /**
     * Handle return from Cregis payment
     */
    public function handle_return() {
        if (!isset($_GET['cregis_return']) || $_GET['cregis_return'] !== '1') {
            return;
        }

        $this->logger->info(sprintf('Return handler: START - cregis_return detected, full URL: %s', sanitize_text_field($_SERVER['REQUEST_URI'])));

        $action = isset($_GET['cregis_action']) ? sanitize_text_field($_GET['cregis_action']) : '';

        // If action is set, render the return page content with theme header/footer
        if (!empty($action)) {
            // Verify order ownership or valid order key for return page rendering
            $order_id = isset($_GET['order_id']) ? absint($_GET['order_id']) : 0;
            if (!$order_id) {
                $this->logger->info('Return handler: NO ORDER ID - redirect to cart');
                $this->redirect_to_cart(__('Invalid order.', 'cregis-payment-for-woocommerce'));
                return;
            }

            $order = wc_get_order($order_id);
            if (!$order) {
                $this->logger->info('Return handler: ORDER NOT FOUND - redirect to cart');
                $this->redirect_to_cart(__('Order not found.', 'cregis-payment-for-woocommerce'));
                return;
            }

            // Verify this is a Cregis order
            if ($order->get_payment_method() !== 'cregispay') {
                $this->logger->info(sprintf('Return handler: NOT CREGIS ORDER (method=%s) - returning', $order->get_payment_method()));
                return;
            }

            // Check order key for validity (validates ownership)
            $order_key = isset($_GET['key']) ? sanitize_text_field($_GET['key']) : '';
            if (!hash_equals($order->get_order_key(), $order_key)) {
                $this->logger->info(sprintf('Return handler: INVALID ORDER KEY for order_id=%d - redirect to cart', $order_id));
                $this->redirect_to_cart(__('Invalid order.', 'cregis-payment-for-woocommerce'));
                return;
            }

            $this->logger->info('Return handler: cregis_action set, rendering return page');
            $this->render_return_page_with_theme();
            exit;
        }

        // This is the initial return from Cregis - determine status and redirect
        $order_id = isset($_GET['order_id']) ? absint($_GET['order_id']) : 0;
        $this->logger->info(sprintf('Return handler: order_id=%d', $order_id));
        if (!$order_id) {
            $this->logger->info('Return handler: NO ORDER ID - redirect to cart');
            $this->redirect_to_cart(__('Invalid order.', 'cregis-payment-for-woocommerce'));
            return;
        }

        $order = wc_get_order($order_id);
        if (!$order) {
            $this->logger->info('Return handler: ORDER NOT FOUND - redirect to cart');
            $this->redirect_to_cart(__('Order not found.', 'cregis-payment-for-woocommerce'));
            return;
        }

        // Check if this is a Cregis order
        if ($order->get_payment_method() !== 'cregispay') {
            $this->logger->info(sprintf('Return handler: NOT CREGIS ORDER (method=%s) - returning', $order->get_payment_method()));
            return;
        }

        $cregis_order_id = $order->get_meta('_cregis_order_id');
        $merchant_order_id = $order->get_meta('_cregis_merchant_order_id');
        $saved_status = $order->get_meta('_cregis_payment_status');
        $this->logger->info(sprintf('Return handler: order_id=%d, cregis_order_id=%s, merchant_order_id=%s, saved_status=%s', $order_id, $cregis_order_id, $merchant_order_id, $saved_status));

        // Check WooCommerce order meta FIRST (webhook usually saves this already)
        if (!empty($saved_status) && $saved_status !== 'new') {
            $status = $saved_status;
            $this->logger->info(sprintf('Return handler: using saved status from meta: %s', $status));
        } else {
            // Meta is empty - try live status from Cregis API
            $this->logger->info('Return handler: meta empty, querying API');
            $status = $this->get_live_order_status($cregis_order_id, $order_id);
            $this->logger->info(sprintf('Return handler: API returned status=%s', $status));
        }

        // Update order metadata with latest status
        if ($status) {
            $order->update_meta_data('_cregis_payment_status', $status);
            $order->save();
        }

        // Clear cart for paid/partial/over payments
        if (in_array($status, array('paid', 'paid_partial', 'paid_over', 'paid_remain'))) {
            WC()->cart->empty_cart();
            $this->logger->info(sprintf('Return handler: cart cleared for order %d with status %s', $order_id, $status));
        }

        // Redirect based on payment status
        $this->logger->info(sprintf('Return handler: redirecting based on status=%s', $status));
        $this->redirect_based_on_status($status, $order_id);

        exit;
    }

    /**
     * Render the return page using the theme's actual header and footer
     * We fetch the homepage to get the real theme header/footer, then inject our content
     */
    private function render_return_page_with_theme() {
        $action = isset($_GET['cregis_action']) ? sanitize_text_field($_GET['cregis_action']) : '';
        if (!in_array($action, array('thankyou', 'underpayment', 'overpayment'))) {
            return;
        }

        $order_id = isset($_GET['order_id']) ? absint($_GET['order_id']) : 0;
        $order = $order_id ? wc_get_order($order_id) : null;

        // Register and enqueue the stylesheet
        wp_register_style('cregis-payment-return', CREGIS_PAYMENT_PLUGIN_URL . 'assets/css/cregis-return-page.css', array(), CREGIS_PAYMENT_VERSION);
        wp_enqueue_style('cregis-payment-return');

        // Get our payment content HTML (without inline CSS since we're using enqueued stylesheet)
        ob_start();
        $this->render_return_content($action, $order);
        $payment_content = ob_get_clean();

        // Use simple header/footer approach - more reliable than parsing homepage HTML
        $this->render_simple_header_footer($action, $order);
    }

    /**
     * Render page layout for block-based themes (like Assembler)
     * Extract header and footer block template parts, place content between them
     */
    private function render_block_theme_layout($html, $payment_content, $action) {
        // Find positions of key elements
        $header_end_pos = stripos($html, '</head>');
        $body_start_pos = stripos($html, '<body');

        if ($header_end_pos === false || $body_start_pos === false) {
            $this->render_simple_header_footer($action, null);
            return;
        }

        // $header_html = everything from start to </head> (inclusive)
        $header_html = substr($html, 0, $header_end_pos + 7);

        // $body_content = everything after the body tag's >
        $body_tag_end = strpos($html, '>', $body_start_pos);
        $body_content = substr($html, $body_tag_end + 1);

        // Now body_content starts right after <body...> and contains:
        // [header block template part]
        // [possibly more header stuff]
        // [content area - main or wp-block-post-content]
        // [footer block template part]

        // Find the header block's closing tag </header>
        $header_close_pos = stripos($body_content, '</header>');
        // Find the footer block's opening <footer
        $footer_start_pos = stripos($body_content, '<footer');

        if ($header_close_pos !== false && $footer_start_pos !== false && $header_close_pos < $footer_start_pos) {
            // Split body_content into:
            // 1. before first </header> - we want to keep this (it's the opening structure)
            // 2. the first </header> tag itself
            // 3. content between </header> and <footer> - THIS IS WHERE WE INSERT OUR CONTENT
            // 4. <footer> and everything after - footer block

            $before_first_header_close = substr($body_content, 0, $header_close_pos + strlen('</header>'));
            $middle_content = substr($body_content, $header_close_pos + strlen('</header>'), $footer_start_pos - ($header_close_pos + strlen('</header>')));
            $footer_block = substr($body_content, $footer_start_pos);

            // Clean scripts from footer
            $footer_block = preg_replace('/<script[^>]*>.*?<\/script>/is', '', $footer_block);
            $footer_block = preg_replace('/<noscript[^>]*>.*?<\/noscript>/is', '', $footer_block);

            // Output: head with enqueued styles, body tag with our classes, content before header close, our payment, footer
            echo wp_kses_post($header_html);
            echo '<body class="cregis-return-page cregis-' . esc_attr($action) . '">';
            echo wp_kses_post($before_first_header_close);
            echo '<div class="cregis-payment-wrapper">' . wp_kses_post($payment_content) . '</div>';
            echo wp_kses_post($footer_block);
            return;
        }

        // Fallback: try to find wp-block-post-content as the main content area
        $content_pattern = '/<div[^>]*class=["\'][^"\']*wp-block-post-content[^"\']*["\'][^>]*>.*?<\/div>/is';
        if (preg_match($content_pattern, $body_content, $content_match, PREG_OFFSET_CAPTURE)) {
            $content_start = $content_match[0][1];
            $content_end = $content_start + strlen($content_match[0][0]);

            $before_content = substr($body_content, 0, $content_start);
            $after_content = substr($body_content, $content_end);

            echo wp_kses_post($header_html);
            echo '<body class="cregis-return-page cregis-' . esc_attr($action) . '">';
            echo wp_kses_post($before_content);
            echo '<div class="cregis-payment-wrapper">' . wp_kses_post($payment_content) . '</div>';
            echo wp_kses_post($after_content);
            return;
        }

        // Last resort fallback
        $this->render_simple_header_footer($action, null);
    }

    /**
     * Fallback: Render with simple header/footer that matches the theme's default
     */
    private function render_simple_header_footer($action, $order) {
        $site_name = get_bloginfo('name');
        $site_url = home_url('/');
        $shop_url = wc_get_page_permalink('shop');
        $cart_url = wc_get_cart_url();
        $account_url = wc_get_page_permalink('myaccount');

        // Register and enqueue stylesheet
        wp_register_style('cregis-payment-return', CREGIS_PAYMENT_PLUGIN_URL . 'assets/css/cregis-return-page.css', array(), CREGIS_PAYMENT_VERSION);
        wp_enqueue_style('cregis-payment-return');

        // Get payment content without inline CSS (we'll use enqueued stylesheet)
        ob_start();
        $this->render_return_content($action, $order);
        $payment_content = ob_get_clean();

        ?>
<!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
    <meta charset="<?php bloginfo('charset'); ?>">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?php echo esc_html__('Payment Status', 'cregis-payment-for-woocommerce') . ' - ' . esc_html($site_name); ?></title>
    <link rel="stylesheet" href="<?php echo esc_url(CREGIS_PAYMENT_PLUGIN_URL . 'assets/css/cregis-return-page.css'); ?>?ver=<?php echo esc_attr(CREGIS_PAYMENT_VERSION); ?>">
    <?php wp_print_styles(); ?>
</head>
<body class="cregis-return-page cregis-<?php echo esc_attr($action); ?>">
<div id="page" class="site">
    <header id="masthead" class="site-header">
        <div class="header-inner">
            <div class="site-branding">
                <a href="<?php echo esc_url($site_url); ?>" class="site-logo-link">
                    <?php if (has_custom_logo()) : ?>
                        <?php the_custom_logo(); ?>
                    <?php else : ?>
                        <span class="site-title"><?php echo esc_html($site_name); ?></span>
                    <?php endif; ?>
                </a>
            </div>
            <nav id="site-navigation" class="main-navigation">
                <div class="menu-toggle" aria-controls="primary-menu" aria-expanded="false">
                    <span class="menu-toggle-text"><?php esc_html_e('Menu', 'cregis-payment-for-woocommerce'); ?></span>
                </div>
                <?php
                if (has_nav_menu('primary')) {
                    wp_nav_menu(array(
                        'theme_location' => 'primary',
                        'menu_id' => 'primary-menu',
                        'container' => false,
                        'fallback_cb' => false,
                    ));
                } else {
                    // Default menu links if no menu is set
                    echo '<ul id="primary-menu"><li><a href="' . esc_url($shop_url) . '">' . esc_html__('Shop', 'cregis-payment-for-woocommerce') . '</a></li>';
                    echo '<li><a href="' . esc_url($cart_url) . '">' . esc_html__('Cart', 'cregis-payment-for-woocommerce') . '</a></li>';
                    echo '<li><a href="' . esc_url($account_url) . '">' . esc_html__('My Account', 'cregis-payment-for-woocommerce') . '</a></li></ul>';
                }
                ?>
            </nav>
        </div>
    </header>

    <main id="main" class="site-main">
        <?php echo wp_kses_post($payment_content); ?>
    </main>

    <footer id="colophon" class="site-footer">
        <div class="footer-inner">
            <?php
            // Output footer widgets if available
            if (is_active_sidebar('footer-1')) {
                echo '<div class="footer-widgets">';
                dynamic_sidebar('footer-1');
                echo '</div>';
            }
            ?>
            <div class="site-info">
                <span>&copy; <?php echo date('Y'); ?> <?php echo esc_html($site_name); ?>.</span>
            </div>
        </div>
    </footer>
</div>
<?php wp_footer(); ?>
</body>
</html>
        <?php
    }

    /**
     * Get live order status from Cregis API
     */
    private function get_live_order_status($cregis_order_id, $order_id) {
        if (!$this->api) {
            $this->logger->error('API not initialized for status query');
            return null;
        }

        // Try with Cregis order ID first
        $status = $this->query_api_status($cregis_order_id);
        if (!empty($status)) {
            return $status;
        }

        // Fallback: try merchant order ID
        $order = wc_get_order($order_id);
        $merchant_order_id = $order->get_meta('_cregis_merchant_order_id');
        if (!empty($merchant_order_id)) {
            $this->logger->info(sprintf('Return handler: Cregis ID query failed, trying merchant order ID: %s', $merchant_order_id));
            $status = $this->query_api_status($merchant_order_id);
            if (!empty($status)) {
                return $status;
            }
        }

        // Last resort: check WooCommerce meta (webhook may have updated it)
        if ($order) {
            $saved_status = $order->get_meta('_cregis_payment_status');
            if (!empty($saved_status) && $saved_status !== 'new') {
                $this->logger->info(sprintf('Return handler: API failed, using meta status: %s', $saved_status));
                return $saved_status;
            }
        }

        return null;
    }

    /**
     * Query API for order status by order ID
     */
    private function query_api_status($order_id) {
        $this->logger->info(sprintf('Return handler: query_api_status called with ID=%s', $order_id));
        try {
            $response = $this->api->get_order_info($order_id);
            $this->logger->info(sprintf('Return handler: API response for ID=%s: %s', $order_id, json_encode($response)));
            if (isset($response['data']['status'])) {
                $status = $response['data']['status'];
                $this->logger->info(sprintf('Return handler: API status=%s for ID=%s', $status, $order_id));
                return $status;
            } else {
                $this->logger->info(sprintf('Return handler: API response has no status field for ID=%s', $order_id));
            }
        } catch (Exception $e) {
            $this->logger->error(sprintf('Error fetching order status from Cregis with ID %s: %s', $order_id, $e->getMessage()));
        }
        return null;
    }

    /**
     * Redirect based on payment status
     */
    private function redirect_based_on_status($status, $order_id) {
        $this->logger->info(sprintf('Return handler: redirect_based_on_status called with status=%s, order_id=%d', $status, $order_id));
        
        $order = wc_get_order($order_id);
        if (!$order) {
            $this->redirect_to_cart(__('Order not found.', 'cregis-payment-for-woocommerce'));
            exit;
        }
        
        switch ($status) {
            case 'paid':
                // Redirect to order detail page, no popup
                $this->logger->info(sprintf('Return handler: redirecting to order page for paid status'));
                wp_redirect($order->get_view_order_url());
                exit;

            case 'paid_partial':
                // Check if accept_all_underpaid is enabled
                $settings = get_option('cregis_payment_settings', array());
                $accept_all_underpaid = isset($settings['accept_all_underpaid']) && $settings['accept_all_underpaid'] === 'yes';
                
                if ($accept_all_underpaid) {
                    // If accept_all_underpaid is enabled, redirect without popup
                    $this->logger->info(sprintf('Return handler: accept_all_underpaid enabled, redirecting to order page without notice'));
                    wp_redirect($order->get_view_order_url());
                } else {
                    // Otherwise, redirect with popup notice
                    $this->logger->info(sprintf('Return handler: redirecting to order page with underpayment notice'));
                    wp_redirect(add_query_arg('cregis_notice', 'underpayment', $order->get_view_order_url()));
                }
                exit;

            case 'paid_over':
                // Check if accept_all_overpaid is enabled
                $settings = get_option('cregis_payment_settings', array());
                $accept_all_overpaid = isset($settings['accept_all_overpaid']) && $settings['accept_all_overpaid'] === 'yes';
                
                if ($accept_all_overpaid) {
                    // If accept_all_overpaid is enabled, redirect without popup
                    $this->logger->info(sprintf('Return handler: accept_all_overpaid enabled, redirecting to order page without notice'));
                    wp_redirect($order->get_view_order_url());
                } else {
                    // Otherwise, redirect with popup notice
                    $this->logger->info(sprintf('Return handler: redirecting to order page with overpayment notice'));
                    wp_redirect(add_query_arg('cregis_notice', 'overpayment', $order->get_view_order_url()));
                }
                exit;

            case 'expired':
                $this->redirect_to_cart(__('Your payment session has expired.', 'cregis-payment-for-woocommerce'));
                exit;

            case 'failed':
                $this->redirect_to_cart(__('Payment failed. Please try again.', 'cregis-payment-for-woocommerce'), 'error');
                exit;

            default:
                // For unknown or 'new' status, check if webhook has already updated the order meta
                $saved_status = $order->get_meta('_cregis_payment_status');
                if ($saved_status && $saved_status !== 'new') {
                    $this->redirect_based_on_status($saved_status, $order_id);
                    exit;
                }
                // No payment was made - user cancelled or order is still pending
                // Redirect to cart with a message
                wc_add_notice(__('Payment was not completed. Your order is still pending.', 'cregis-payment-for-woocommerce'), 'notice');
                wp_redirect(wc_get_cart_url());
                exit;
        }
    }

    /**
     * Get the WooCommerce thank-you page URL
     */
    private function get_thankyou_url($order_id) {
        return wc_get_endpoint_url('order-received', $order_id, wc_get_checkout_url());
    }

    /**
     * Redirect to the return info page
     */
    private function redirect_to_return_page($action, $order_id) {
        $order = wc_get_order($order_id);
        $order_key = $order ? $order->get_order_key() : '';
        $url = add_query_arg(array(
            'cregis_return' => '1',
            'cregis_action' => $action,
            'order_id' => $order_id,
            'key' => $order_key,
        ), home_url('/'));
        wp_redirect($url);
    }

    /**
     * Render the return page content - outputs the card UI
     *
     * @param string $action The action (thankyou, underpayment, overpayment)
     * @param WC_Order|false $order The order object or false
     */
    public function render_return_content($action, $order) {
        // Output content wrapper

        // Output content wrapper
        echo '<div class="cregis-return-wrap"><div class="cregis-return-card">';

        if (!$order) {
            // Invalid request
            echo '<div class="cregis-return-header">';
            echo '<div class="cregis-return-header-icon warning">!</div>';
            echo '<h1>' . esc_html__('Invalid Request', 'cregis-payment-for-woocommerce') . '</h1>';
            echo '<p>' . esc_html__('The payment request is invalid or has expired.', 'cregis-payment-for-woocommerce') . '</p>';
            echo '</div>';
            echo '<div class="cregis-return-body">';
            echo '<div class="cregis-actions">';
            echo '<a href="' . esc_url(wc_get_cart_url()) . '" class="cregis-btn cregis-btn-primary">' . esc_html__('Return to Cart', 'cregis-payment-for-woocommerce') . '</a>';
            echo '</div>';
            echo '</div>';
        } elseif ($action === 'thankyou') {
            echo '<div class="cregis-return-header">';
            echo '<div class="cregis-return-header-icon success">&#10003;</div>';
            echo '<h1>' . esc_html__('Payment Submitted', 'cregis-payment-for-woocommerce') . '</h1>';
            echo '<p>' . esc_html__('Your cryptocurrency payment has been received and is being processed.', 'cregis-payment-for-woocommerce') . '</p>';
            echo '</div>';
            echo '<div class="cregis-return-body">';
            echo '<div class="cregis-order-summary">';
            echo '<div class="cregis-order-row total">';
            echo '<span class="cregis-order-label">' . esc_html__('Order', 'cregis-payment-for-woocommerce') . '</span>';
            echo '<span class="cregis-order-value">#' . esc_html($order->get_id()) . '</span>';
            echo '</div>';
            echo '<div class="cregis-order-row">';
            echo '<span class="cregis-order-label">' . esc_html__('Total Amount', 'cregis-payment-for-woocommerce') . '</span>';
            echo '<span class="cregis-order-value">' . wp_kses_post($order->get_formatted_order_total()) . '</span>';
            echo '</div>';
            echo '<div class="cregis-order-row">';
            echo '<span class="cregis-order-label">' . esc_html__('Payment Status', 'cregis-payment-for-woocommerce') . '</span>';
            echo '<span class="cregis-order-value success">' . esc_html__('Processing', 'cregis-payment-for-woocommerce') . '</span>';
            echo '</div>';
            echo '</div>';
            echo '<div class="cregis-section">';
            echo '<div class="cregis-info-box success">';
            echo '<strong>' . esc_html__('Thank you!', 'cregis-payment-for-woocommerce') . '</strong><br>';
            echo esc_html__('Your order is being processed. You will receive an email confirmation shortly.', 'cregis-payment-for-woocommerce');
            echo '</div>';
            echo '</div>';
            echo '</div>';
        } elseif ($action === 'underpayment') {
            $order_total = $order->get_formatted_order_total();
            $payment_info = $this->get_payment_info_from_order($order);
            $received_amount = !empty($payment_info['Received Amount']) ? $payment_info['Received Amount'] : esc_html__('Pending', 'cregis-payment-for-woocommerce');

            echo '<div class="cregis-return-header">';
            echo '<div class="cregis-return-header-icon warning">!</div>';
            echo '<h1>' . esc_html__('Partial Payment Received', 'cregis-payment-for-woocommerce') . '</h1>';
            echo '<p>' . esc_html__('We received a partial payment. Additional action is required to complete your order.', 'cregis-payment-for-woocommerce') . '</p>';
            echo '</div>';
            echo '<div class="cregis-return-body">';
            echo '<div class="cregis-order-summary">';
            echo '<div class="cregis-order-row total">';
            echo '<span class="cregis-order-label">' . esc_html__('Order', 'cregis-payment-for-woocommerce') . '</span>';
            echo '<span class="cregis-order-value">#' . esc_html($order->get_id()) . '</span>';
            echo '</div>';
            echo '<div class="cregis-order-row">';
            echo '<span class="cregis-order-label">' . esc_html__('Order Total', 'cregis-payment-for-woocommerce') . '</span>';
            echo '<span class="cregis-order-value danger">' . wp_kses_post($order_total) . '</span>';
            echo '</div>';
            echo '<div class="cregis-order-row">';
            echo '<span class="cregis-order-label">' . esc_html__('Amount Received', 'cregis-payment-for-woocommerce') . '</span>';
            echo '<span class="cregis-order-value success">' . esc_html($received_amount) . '</span>';
            echo '</div>';
            echo '<div class="cregis-order-row">';
            echo '<span class="cregis-order-label">' . esc_html__('Amount Due', 'cregis-payment-for-woocommerce') . '</span>';
            echo '<span class="cregis-order-value danger">' . esc_html__('See order details', 'cregis-payment-for-woocommerce') . '</span>';
            echo '</div>';
            echo '</div>';
            echo '<div class="cregis-section">';
            echo '<div class="cregis-info-box danger">';
            echo '<strong>' . esc_html__('Action Required:', 'cregis-payment-for-woocommerce') . '</strong><br>';
            echo esc_html__('Please check your email for instructions on how to process the additional payment.', 'cregis-payment-for-woocommerce');
            echo '</div>';
            echo '</div>';
            echo '</div>';
        } elseif ($action === 'overpayment') {
            $order_total = $order->get_formatted_order_total();
            $payment_info = $this->get_payment_info_from_order($order);
            $received_amount = !empty($payment_info['Received Amount']) ? $payment_info['Received Amount'] : esc_html__('Pending', 'cregis-payment-for-woocommerce');

            echo '<div class="cregis-return-header">';
            echo '<div class="cregis-return-header-icon info">i</div>';
            echo '<h1>' . esc_html__('Overpayment Received', 'cregis-payment-for-woocommerce') . '</h1>';
            echo '<p>' . esc_html__('We received more than the order total. A refund will be processed.', 'cregis-payment-for-woocommerce') . '</p>';
            echo '</div>';
            echo '<div class="cregis-return-body">';
            echo '<div class="cregis-order-summary">';
            echo '<div class="cregis-order-row total">';
            echo '<span class="cregis-order-label">' . esc_html__('Order', 'cregis-payment-for-woocommerce') . '</span>';
            echo '<span class="cregis-order-value">#' . esc_html($order->get_id()) . '</span>';
            echo '</div>';
            echo '<div class="cregis-order-row">';
            echo '<span class="cregis-order-label">' . esc_html__('Order Total', 'cregis-payment-for-woocommerce') . '</span>';
            echo '<span class="cregis-order-value">' . wp_kses_post($order_total) . '</span>';
            echo '</div>';
            echo '<div class="cregis-order-row">';
            echo '<span class="cregis-order-label">' . esc_html__('Amount Received', 'cregis-payment-for-woocommerce') . '</span>';
            echo '<span class="cregis-order-value success">' . esc_html($received_amount) . '</span>';
            echo '</div>';
            echo '<div class="cregis-order-row">';
            echo '<span class="cregis-order-label">' . esc_html__('Refund Amount', 'cregis-payment-for-woocommerce') . '</span>';
            echo '<span class="cregis-order-value danger">' . esc_html__('See order details', 'cregis-payment-for-woocommerce') . '</span>';
            echo '</div>';
            echo '</div>';
            echo '<div class="cregis-section">';
            echo '<div class="cregis-info-box warning">';
            echo '<strong>' . esc_html__('Next Steps:', 'cregis-payment-for-woocommerce') . '</strong><br>';
            echo esc_html__('Please check your email for instructions on how to process the refund for the excess amount.', 'cregis-payment-for-woocommerce');
            echo '</div>';
            echo '</div>';
            echo '</div>';
        }

        // Action buttons for all states
        echo '<div class="cregis-return-body" style="padding-top:0;border-top:none;">';
        echo '<div class="cregis-actions">';
        echo '<a href="' . esc_url($order ? $order->get_view_order_url() : wc_get_cart_url()) . '" class="cregis-btn cregis-btn-primary">' . esc_html__('View Order Details', 'cregis-payment-for-woocommerce') . '</a>';
        echo '<a href="' . esc_url(wc_get_page_permalink('shop')) . '" class="cregis-btn cregis-btn-secondary">' . esc_html__('Continue Shopping', 'cregis-payment-for-woocommerce') . '</a>';
        echo '</div>';
        echo '</div>';

        echo '</div></div>'; // .cregis-return-card .cregis-return-wrap
    }

    /**
     * Get payment info from order notes
     */
    private function get_payment_info_from_order($order) {
        $info = array();
        $args = array(
            'post_id' => $order->get_id(),
            'type' => 'order_note',
            'status' => 'approve',
            'orderby' => 'comment_date',
            'order' => 'DESC'
        );
        $notes = get_comments($args);
        foreach ($notes as $note) {
            $content = $note->comment_content;
            if (strpos($content, 'Payment Time:') !== false || strpos($content, 'Partial Payment') !== false || strpos($content, 'First Payment') !== false) {
                $lines = explode("\n", $content);
                foreach ($lines as $line) {
                    $line = trim($line);
                    if (empty($line)) continue;
                    if (strpos($line, ':') !== false) {
                        list($key, $value) = explode(':', $line, 2);
                        $info[trim($key)] = trim($value);
                    }
                }
                break;
            }
        }
        return $info;
    }

    /**
     * Redirect to cart with a notice
     */
    private function redirect_to_cart($message, $type = 'notice') {
        if ($message) {
            wc_add_notice($message, $type);
        }
        wp_redirect(wc_get_cart_url());
    }
}
