<?php
/**
 * EONSR AEO Agent Purchase & License Management Page
 *
 * Handles product selection, license details, cancellation, and payment processing.
 */

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

// ==============================================================================
// HANDLE FORM SUBMISSIONS (CANCEL LICENSE)
// ==============================================================================

if ( isset( $_POST['eonsr_aeo_action'] ) && $_POST['eonsr_aeo_action'] === 'cancel_license' ) {
    
    // --- SECURITY FIX: Sanitize, Unslash & Verify Nonce ---
    // 1. Check if nonce is set.
    // 2. Unslash and Sanitize the input (Fixes MissingUnslash & InputNotSanitized warnings).
    $eonsr_aeo_nonce = isset( $_POST['_wpnonce'] ) ? sanitize_key( wp_unslash( $_POST['_wpnonce'] ) ) : '';

    // 3. Verify the nonce against the action name defined in your form.
    if ( ! wp_verify_nonce( $eonsr_aeo_nonce, 'eonsr_aeo_cancel_action' ) ) {
        wp_die( 'Security check failed. Please refresh and try again.' );
    }
    // ----------------------------------------------------

    if ( current_user_can( 'manage_options' ) ) {
        
        // 1. Get License Key
        $eonsr_aeo_license_key = get_option( 'eonsr_aeo_agent_license_key' );
        
        // 1.1 Call API to Cancel
        if ( $eonsr_aeo_license_key ) {            
            $eonsr_aeo_api_url = EONSR_AEO_AGENT_API_URL . '/api/v1/license/cancel/' . $eonsr_aeo_license_key;
            
            $eonsr_aeo_response = wp_remote_request( $eonsr_aeo_api_url, array(
                'method'    => 'PATCH',
                'timeout'   => 15,
                'headers'   => array(
                    'Content-Type' => 'application/json'
                ),
                'body'      => '{}' 
            ));

            if ( is_wp_error( $eonsr_aeo_response ) ) {
                // --- DEBUG FIX: Whitelist error_log ---
                // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
                error_log( 'EONSR AEO Agent: Cancel API Failed: ' . $eonsr_aeo_response->get_error_message() );
            }
        }

        // 2. Clear Local Data
        delete_option( 'eonsr_aeo_agent_license_status' );
        delete_option( 'eonsr_aeo_agent_license_key' );
        delete_option( 'eonsr_aeo_agent_user_email' );
        delete_option( 'eonsr_aeo_agent_license_details' );
        delete_option( 'eonsr_aeo_agent_license_features' );
        delete_option( 'eonsr_aeo_agent_selected_languages' );
        delete_option( 'eonsr_aeo_agent_selected_countries' );
        delete_option( 'eonsr_aeo_agent_setup_completed' ); 
        
        // Redirect with success message
        $eonsr_aeo_redirect_url = add_query_arg(
            array(
                'page'    => 'eonsr_aeo_agent_purchase',
                'status'  => 'success',
                'message' => urlencode( 'Đã huỷ license thành công!' )
            ),
            admin_url( 'admin.php' )
        );
        
        wp_safe_redirect( $eonsr_aeo_redirect_url );
        exit;
    }
}

// ==============================================================================
// MAIN PAGE CONTENT
// ==============================================================================

function eonsr_aeo_agent_purchase_page_content() {
    // --- FIX START: Define variables used in the footer script to prevent Undefined Variable errors ---
    $license_status  = get_option( 'eonsr_aeo_agent_license_status' );
    $has_license_key = get_option( 'eonsr_aeo_agent_license_key' );
    // --- FIX END ---
    ?>
    <div class="wrap eonsr-aeo-agent-purchase-wrap">
        <!-- Header Section -->
        <div class="eonsr-aeo-header">
            <div class="header-badge">⚡ ƯU ĐÃI ĐẶC BIỆT</div>
            <h1>Nâng cấp Gói EONSR AEO AGENT</h1>
            <p class="eonsr-aeo-subtitle">Tối ưu hóa AEO chuyên nghiệp - Tăng thứ hạng website của bạn</p>
        </div>

        <!-- Notification Handling -->
        <?php
        // FIX LINE 137: Added nonce verification with proper comment
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Display-only logic, no data modification
        if ( isset( $_GET['status'] ) ) {

            // FIX: Unslash before sanitization
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Display-only logic
            $eonsr_status = sanitize_key( wp_unslash( $_GET['status'] ) );

            if ( $eonsr_status === 'error' ) {

                $eonsr_error_message = 'Đã có lỗi xảy ra, vui lòng thử lại.';

                // FIX: Ignore NonceVerification for message display
                // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Display-only logic
                if ( isset( $_GET['message'] ) ) {
                    // FIX: Unslash before sanitizing
                    // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Display-only logic
                    $eonsr_error_message = sanitize_text_field( wp_unslash( $_GET['message'] ) );
                }

                ?>
                <div class="eonsr-aeo-notice eonsr-aeo-notice-error">
                    <svg width="20" height="20" viewBox="0 0 20 20" fill="currentColor" aria-hidden="true">
                        <path fill-rule="evenodd"
                              d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z"
                              clip-rule="evenodd"/>
                    </svg>

                    <span><?php echo esc_html( $eonsr_error_message ); ?></span>
                </div>
                <?php
            }
        }

        // FIX: Ignore NonceVerification for status check
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Display-only logic
        if ( isset( $_GET['status'] ) && 'success' === $_GET['status'] ) {
            
            // FIX: Unslash before sanitization and urldecode. 
            // We ignore nonce here because this is just displaying a flash message from a redirect.
            // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Display-only logic, no data modification
            $eonsr_aeo_raw_message = isset( $_GET['message'] ) ? sanitize_text_field( wp_unslash( $_GET['message'] ) ) : '';
            $eonsr_aeo_success_message = $eonsr_aeo_raw_message ? sanitize_text_field( wp_unslash( urldecode( $eonsr_aeo_raw_message ) ) ) : 'Thao tác thành công!';
            
            echo '<div class="eonsr-aeo-notice eonsr-aeo-notice-success" style="position: relative;">
                <svg width="20" height="20" viewBox="0 0 20 20" fill="currentColor">
                    <path fill-rule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clip-rule="evenodd"/>
                </svg>
                <span>' . esc_html( $eonsr_aeo_success_message ) . '</span>
                <button type="button" class="eonsr-aeo-notice-close" onclick="this.parentElement.style.display=\'none\'" style="position: absolute; right: 20px; top: 50%; transform: translateY(-50%); background: none; border: none; color: #065f46; cursor: pointer; font-size: 24px; line-height: 1; padding: 0; width: 24px; height: 24px; display: flex; align-items: center; justify-content: center; opacity: 0.6; transition: opacity 0.3s;" onmouseover="this.style.opacity=1" onmouseout="this.style.opacity=0.6">×</button>
            </div>';
        }
        ?>

        <!-- View Router -->
        <?php
        // FIX: Ignore NonceVerification Missing with proper explanation
        // phpcs:ignore WordPress.Security.NonceVerification.Missing -- View router only, actual action verifies nonce internally
        if ( isset( $_POST['action'] ) && 'show_payment_options' === $_POST['action'] ) {
            eonsr_aeo_agent_display_payment_options();
        } else {
            eonsr_aeo_agent_display_product_info();
        }
        ?>
    </div>
    <?php
}

// ==============================================================================
// HELPER FUNCTIONS
// ==============================================================================

/**
 * Get the stored license key from database
 */
function eonsr_aeo_get_stored_license_key() {
    return get_option( 'eonsr_aeo_agent_license_key' );
}

/**
 * Retrieve license details from the API
 *
 * @param string $license_key
 * @return object|null License details object or null on failure
 */
function eonsr_aeo_get_license_details_from_api( $license_key ) {
    if ( empty( $license_key ) ) {
        return null;
    }
    
    $api_url = EONSR_AEO_AGENT_API_URL . '/api/v1/license/details/' . urlencode($license_key);
    $response = wp_remote_get( $api_url, [
        'timeout' => 20,
        'headers' => [
            'Content-Type' => 'application/json'
        ]
    ]);
    
    if ( is_wp_error( $response ) ) {
        // FIX: Whitelist error_log
        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
        error_log( 'EONSR AEO License API Error: ' . $response->get_error_message() );
        return null;
    }
    
    $response_code = wp_remote_retrieve_response_code( $response );
    if ( $response_code !== 200 ) {
        // FIX: Whitelist error_log
        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
        error_log( 'EONSR AEO License API Error: Response code ' . $response_code );
        return null;
    }
    
    $body = wp_remote_retrieve_body( $response );
    $result = json_decode( $body );
    
    if ( ! $result || ! isset( $result->success ) || ! $result->success ) {
        // FIX: Whitelist error_log
        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
        error_log( 'EONSR AEO License API Error: Invalid response' );
        return null;
    }
    
    return $result->license ?? null;
}

// ==============================================================================
// DISPLAY: PRODUCT SELECTION
// ==============================================================================

function eonsr_aeo_agent_display_product_info() {
    $license_key = eonsr_aeo_get_stored_license_key();
    $current_license = null;
    
    if ( $license_key ) {
        $current_license = eonsr_aeo_get_license_details_from_api( $license_key );
    }
    
    $current_product_name = $current_license ? $current_license->productName : null;
    $license_status = get_option( 'eonsr_aeo_agent_license_status' );

    // Call API to get products
    $api_url = EONSR_AEO_AGENT_API_URL . '/api/v1/product';
    $response = wp_remote_get( $api_url, ['timeout' => 20] );

    if ( is_wp_error( $response ) || wp_remote_retrieve_response_code( $response ) !== 200 ) {
        echo '<div class="eonsr-aeo-notice eonsr-aeo-notice-error"><span>Không thể tải danh sách sản phẩm.</span></div>';
        return;
    }

    $body = wp_remote_retrieve_body( $response );
    $result = json_decode( $body );
    $products = $result->data ?? [];

    // Separate Main Plans and Addons
    $main_plans = [];
    $addons = [];

    foreach ( $products as $product ) {
        if ( stripos( $product->name, 'Logo' ) !== false || stripos( $product->name, 'Addon' ) !== false ) {
            $addons[] = $product;
        } else {
            $main_plans[] = $product;
        }
    }

    ?>
    <form method="POST" action="" id="form-select-product">
        <input type="hidden" name="action" value="show_payment_options">
        <?php wp_nonce_field( 'eonsr_aeo_purchase_step1_nonce', 'eonsr_aeo_purchase_nonce' ); ?>

        <!-- HEADER STATUS BAR -->
        <?php if ( $current_license ): 
             $days_left = $current_license->daysUntilExpiry;
             $expiry_date = wp_date( 'd/m/Y', strtotime( $current_license->expiryDate ) );
        ?>
        <!-- <div class="eonsr-aeo-status-bar">
            <div class="status-icon">
                <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="10"></circle><line x1="12" y1="16" x2="12" y2="12"></line><line x1="12" y1="8" x2="12.01" y2="8"></line></svg>
            </div>
            <div class="status-content">
                Bạn đang dùng gói <strong><?php echo esc_html( $current_license->productName ); ?></strong> 
                <span class="status-dot"></span> Còn <strong><?php echo esc_html( $days_left ); ?> ngày</strong> (Hết hạn: <?php echo esc_html( $expiry_date ); ?>)
            </div>
        </div> -->
        <?php endif; ?>

        <div class="eonsr-aeo-layout-container">
            <!-- LEFT COLUMN: PLANS LIST -->
            <div class="plans-grid">
                <?php 
                foreach ( $main_plans as $index => $product ) : 
                    $is_current_plan = ( $current_product_name && $product->name === $current_product_name );
                    
                    // Logic CSS for card
                    $card_class = 'plan-card';
                    if ( $is_current_plan ) {
                        $card_class .= ' is-current'; // Class for current plan
                    }
                    
                    // Logic checked: If not current plan, check first available
                    $checked_attr = ( ! $is_current_plan && $index === 0 ) ? 'checked' : '';
                    if ( $is_current_plan ) $checked_attr = ''; // Current plan not auto-checked

                    // Calculate Discount
                    $discount = 0;
                    if ( $product->originalPrice > $product->price ) {
                        $discount = round( ( ( $product->originalPrice - $product->price ) / $product->originalPrice ) * 100 );
                    }
                ?>
                <div class="<?php echo esc_attr( $card_class ); ?>" onclick="selectPlan('<?php echo esc_attr( $product->_id ); ?>', this)">
                        <?php if ( $is_current_plan ): ?>
                            <div class="current-plan-badge">Đang sử dụng</div>
                        <?php endif; ?>

                        <div class="card-body">
                            <!-- Radio Input (Hidden) -->
                            <input type="radio" 
                                   id="radio_<?php echo esc_attr( $product->_id ); ?>"
                                   name="selected_product_id" 
                                   value="<?php echo esc_attr( $product->_id ); ?>" 
                                   data-price="<?php echo esc_attr( $product->price ); ?>"
                                   class="plan-radio-hidden"
                                   <?php echo esc_attr( $checked_attr ); ?> 
                                   <?php echo $is_current_plan ? 'disabled' : ''; ?>>

                            <div class="card-top">
                                <h3 class="plan-name"><?php echo esc_html( $product->name ); ?></h3>
                                <div class="radio-visual"></div>
                            </div>

                            <div class="card-price-group">
                                <span class="price-amount"><?php echo number_format( $product->price, 0, ',', '.' ); ?></span>
                                <span class="price-currency">đ</span>
                                <?php if ( $product->originalPrice > $product->price ): ?>
                                    <span class="price-del"><?php echo number_format( $product->originalPrice, 0, ',', '.' ); ?></span>
                                <?php endif; ?>
                            </div>

                            <!-- Addons Divider -->
                            <?php if ( ! empty( $addons ) ): ?>
                                <div class="card-divider"></div>
                                <div class="addons-wrapper">
                                    <div class="addons-label">TÙY CHỌN MUA KÈM:</div>
                                    <?php foreach ( $addons as $addon ): 
                                        $addon_discount = 0;
                                        if ( $addon->originalPrice > $addon->price ) {
                                            $addon_discount = round( ( ( $addon->originalPrice - $addon->price ) / $addon->originalPrice ) * 100 );
                                        }
                                    ?>
                                        <div class="addon-row" onclick="event.stopPropagation();">
                                            <label class="addon-inner">
                                                <div class="addon-left">
                                                    <input type="checkbox" 
                                                           name="selected_addon_ids[]" 
                                                           value="<?php echo esc_attr( $addon->_id ); ?>"
                                                           data-price="<?php echo esc_attr( $addon->price ); ?>"
                                                           class="addon-checkbox"
                                                           <?php echo $is_current_plan ? 'disabled' : ''; ?>>
                                                    <span class="addon-text"><?php echo esc_html( $addon->name ); ?></span>
                                                </div>
                                                
                                                <div class="addon-right">
                                                    <span class="addon-price">+<?php echo number_format( $addon->price, 0, ',', '.' ); ?></span>
                                                    <?php if ( $addon_discount > 0 ): ?>
                                                        <span class="addon-badge">-<?php echo esc_html( $addon_discount ); ?>%</span>
                                                    <?php endif; ?>
                                                </div>
                                            </label>
                                        </div>
                                    <?php endforeach; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>

            <!-- RIGHT COLUMN: CHECKOUT FORM -->
            <div class="sidebar-info">
                <div class="form-card sticky-sidebar">
                    <!-- Security Badge -->
                    <div class="security-badge">
                        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>
                        Secure Checkout
                    </div>

                    <h2 class="sidebar-title">Thông tin thanh toán</h2>
                    
                    <!-- Input: Name -->
                    <div class="form-group">
                        <label>Họ và Tên</label>
                        <div class="input-with-icon">
                            <span class="input-icon">
                                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
                            </span>
                            <input type="text" name="user_name" placeholder="Ví dụ: Nguyễn Văn A" required>
                        </div>
                    </div>

                    <!-- Input: Email -->
                    <div class="form-group">
                        <label>Email nhận License</label>
                        <div class="input-with-icon">
                            <span class="input-icon">
                                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>
                            </span>
                            <input type="email" name="user_email" value="<?php echo esc_attr( $current_license->userEmail ?? '' ); ?>" placeholder="name@example.com" required>
                        </div>
                    </div>
                    
                    <!-- Divider -->
                    <div class="form-divider"></div>

                    <!-- Total Price -->
                    <div class="total-section-modern">
                        <div class="total-label">Tổng thanh toán</div>
                        <div class="total-value" id="display-total-price">0 đ</div>
                    </div>

                    <!-- Checkout Button -->
                    <button type="submit" id="btn-process-payment" class="button-hero">
                        <span>Tiếp tục thanh toán</span>
                        <svg width="18" height="18" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M14 5l7 7m0 0l-7 7m7-7H3"/></svg>
                    </button>
                    
                    <!-- Cancel Link -->
                    <?php if ( ! empty( $license_status ) && $license_status === 'activated' ): ?>
                        <div class="cancel-link-wrapper">
                            <button type="button" id="btn-cancel-license" class="link-cancel">
                                <svg width="14" height="14" fill="none" stroke="currentColor" stroke-width="2" viewBox="0 0 24 24"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>
                                Huỷ kích hoạt License
                            </button>
                        </div>
                    <?php endif; ?>
                </div>
                
                <!-- Trust Footer -->
                <div class="payment-trust-footer">
                    <span class="trust-item"><svg width="12" height="12" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2" fill="none"><rect x="1" y="4" width="22" height="16" rx="2" ry="2"/><line x1="1" y1="10" x2="23" y2="10"/></svg> Thanh toán an toàn</span>
                    <span class="trust-item"><svg width="12" height="12" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2" fill="none"><path d="M22 11.08V12a10 10 0 1 1-5.93-9.14"/><polyline points="22 4 12 14.01 9 11.01"/></svg> Kích hoạt ngay</span>
                </div>
            </div>
        </div>
    </form>
    
    <!-- Hidden Form for Cancellation -->
    <form id="form-cancel-license" method="POST" style="display:none;">
        <input type="hidden" name="eonsr_aeo_action" value="cancel_license">
        <?php wp_nonce_field( 'eonsr_aeo_cancel_action', '_wpnonce' ); ?>
    </form>
    <?php
}

// ==============================================================================
// DISPLAY: PAYMENT OPTIONS (STEP 2)
// ==============================================================================

function eonsr_aeo_agent_display_payment_options() {
    // FIX: Unslash and Sanitize Nonce before verification
    $eonsr_aeo_nonce = isset( $_POST['eonsr_aeo_purchase_nonce'] ) ? sanitize_key( wp_unslash( $_POST['eonsr_aeo_purchase_nonce'] ) ) : '';

    if ( ! wp_verify_nonce( $eonsr_aeo_nonce, 'eonsr_aeo_purchase_step1_nonce' ) ) {
        echo '<div class="eonsr-aeo-notice eonsr-aeo-notice-error"><span>Lỗi bảo mật. Vui lòng thử lại.</span></div>';
        return;
    }

    // FIX: Added isset(), wp_unslash(), and sanitization for all inputs
    $eonsr_aeo_user_name = isset( $_POST['user_name'] ) ? sanitize_text_field( wp_unslash( $_POST['user_name'] ) ) : '';
    $eonsr_aeo_user_email = isset( $_POST['user_email'] ) ? sanitize_email( wp_unslash( $_POST['user_email'] ) ) : '';
    $eonsr_aeo_selected_product_id = isset( $_POST['selected_product_id'] ) ? sanitize_text_field( wp_unslash( $_POST['selected_product_id'] ) ) : '';
    
    // FIX: Handle Array Input (Addon IDs)
    $eonsr_aeo_selected_addon_ids = [];
    if ( isset( $_POST['selected_addon_ids'] ) && is_array( $_POST['selected_addon_ids'] ) ) {
        // Sanitize each item in the array
        $eonsr_aeo_selected_addon_ids = array_map( 'sanitize_text_field', wp_unslash( $_POST['selected_addon_ids'] ) );
    }

    // --- RE-FETCH DATA FROM API FOR SECURITY (CALCULATE PRICE) ---
    $eonsr_aeo_api_url = EONSR_AEO_AGENT_API_URL . '/api/v1/product';
    $eonsr_aeo_response = wp_remote_get( $eonsr_aeo_api_url, ['timeout' => 20] );
    
    if ( is_wp_error( $eonsr_aeo_response ) ) {
        echo '<div class="eonsr-aeo-notice eonsr-aeo-notice-error"><span>Lỗi kết nối Server.</span></div>'; 
        return;
    }

    $eonsr_aeo_products = json_decode( wp_remote_retrieve_body( $eonsr_aeo_response ) )->data ?? [];
    
    $eonsr_aeo_main_product = null;
    $eonsr_aeo_addon_products = [];
    $eonsr_aeo_total_price = 0;

    // Find Main Plan & Addons in product list
    foreach ( $eonsr_aeo_products as $eonsr_aeo_p ) {
        // Check main plan
        if ( $eonsr_aeo_p->_id === $eonsr_aeo_selected_product_id ) {
            $eonsr_aeo_main_product = $eonsr_aeo_p;
            $eonsr_aeo_total_price += $eonsr_aeo_p->price;
        }
        // Check addons
        if ( in_array( $eonsr_aeo_p->_id, $eonsr_aeo_selected_addon_ids ) ) {
            $eonsr_aeo_addon_products[] = $eonsr_aeo_p;
            $eonsr_aeo_total_price += $eonsr_aeo_p->price;
        }
    }

    if ( ! $eonsr_aeo_main_product ) {
        echo '<div class="eonsr-aeo-notice eonsr-aeo-notice-error"><span>Không tìm thấy sản phẩm.</span></div>';
        return;
    }

    ?>
    <div class="payment-container">
        <h2>Xác nhận thanh toán</h2>
        
        <div class="order-summary">
            <h3>Chi tiết đơn hàng</h3>
            
            <!-- Main Plan Display -->
            <div class="summary-row">
                <span class="summary-label" style="font-weight:700; color:#1e293b;"><?php echo esc_html( $eonsr_aeo_main_product->name ); ?></span>
                <span class="summary-value">
                    <?php 
                    // --- FIX: Check if currency exists, default to VND to avoid Warning ---
                    $currency = isset( $eonsr_aeo_main_product->currency ) ? $eonsr_aeo_main_product->currency : 'VND';
                    echo number_format( $eonsr_aeo_main_product->price, 0, ',', '.' ) . ' ' . esc_html( $currency ); 
                    ?>
                </span>
            </div>

            <!-- Add-ons Display (if any) -->
            <?php if ( ! empty( $eonsr_aeo_addon_products ) ): ?>
                <?php foreach ( $eonsr_aeo_addon_products as $eonsr_aeo_addon ): ?>
                    <div class="summary-row" style="background: #f8fafc; padding: 8px 12px; border-radius: 6px; margin-top: 5px;">
                        <span class="summary-label" style="font-size: 13px; display:flex; align-items:center; gap:5px;">
                            <span style="color:#10b981">✓</span> <?php echo esc_html( $eonsr_aeo_addon->name ); ?>
                        </span>
                        <span class="summary-value" style="font-size: 13px;">+<?php echo number_format( $eonsr_aeo_addon->price, 0, ',', '.' ); ?></span>
                    </div>
                <?php endforeach; ?>
            <?php endif; ?>

            <div class="summary-row" style="border-top: 2px dashed #e2e8f0; margin-top: 15px; padding-top: 15px;">
                <span class="summary-label">Khách hàng:</span>
                <span class="summary-value"><?php echo esc_html( $eonsr_aeo_user_name ); ?> <br> <small style="color:#64748b"><?php echo esc_html( $eonsr_aeo_user_email ); ?></small></span>
            </div>

            <div class="summary-row total-row" style="margin-top: 10px;">
                <span class="summary-label" style="font-size: 18px;">Tổng cộng:</span>
                <span class="summary-value" style="font-size: 24px; color:#10b981;"><?php echo number_format( $eonsr_aeo_total_price, 0, ',', '.' ); ?> VND</span>
            </div>
        </div>

        <p class="payment-methods-title">Phương thức thanh toán</p>
        
        <div class="payment-options">
            <div class="payment-method">
                <form method="POST" action="<?php echo esc_url( admin_url( 'admin-post.php' ) ); ?>">
                    <input type="hidden" name="action" value="eonsr_aeo_process_paypal">
                    
                    <!-- Main Product ID -->
                    <input type="hidden" name="product_id" value="<?php echo esc_attr( $eonsr_aeo_main_product->_id ); ?>">
                    
                    <!-- Addon IDs List (comma separated) -->
                    <input type="hidden" name="addon_ids" value="<?php echo esc_attr( implode( ',', $eonsr_aeo_selected_addon_ids ) ); ?>">
                    
                    <input type="hidden" name="user_name" value="<?php echo esc_attr( $eonsr_aeo_user_name ); ?>">
                    <input type="hidden" name="user_email" value="<?php echo esc_attr( $eonsr_aeo_user_email ); ?>">
                    
                    <!-- Important: Send Total Amount (Main + Addons) -->
                    <input type="hidden" name="amount" value="<?php echo esc_attr( $eonsr_aeo_total_price ); ?>">
                    
                    <?php wp_nonce_field( 'eonsr_aeo_paypal_nonce', '_wpnonce_paypal' ); ?>
                    <button type="submit" title="Thanh toán qua PayPal">
                        <img src="<?php echo esc_url( EONSR_AEO_AGENT_URL . 'assets/img/Paypal.png' ); ?>" alt="PayPal">
                    </button>
                </form>
            </div>
        </div>

        <div class="back-button-wrapper">
            <button type="button" onclick="history.back()" class="button button-secondary">← Chọn lại gói</button>
        </div>
    </div>
    <?php
}