<?php
/**
 * EONSR AEO Agent - Payment Handlers
 *
 * Handles payment processing for ZaloPay and PayPal integrations.
 * Includes form submission hooks, API communication, and callback handling.
 *
 * @package EONSR_AEO_Agent
 */

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

// Register Hooks
add_action('admin_post_eonsr_aeo_process_zalopay', 'eonsr_aeo_handle_zalopay_payment');
add_action('admin_post_eonsr_aeo_process_paypal', 'eonsr_aeo_handle_paypal_payment');
add_action('admin_init', 'eonsr_aeo_handle_paypal_return_callback');

/* ==========================================================================
   SECTION 1: ZALOPAY HANDLER
   ========================================================================== */

/**
 * Handle ZaloPay Payment Request.
 *
 * Validates request, prepares data payload, calls Node.js API,
 * and redirects user to payment gateway.
 */
function eonsr_aeo_handle_zalopay_payment()
{
    // 1. Security Check
    if (
        !current_user_can('manage_options') ||
        !isset($_POST['_wpnonce_zalopay']) ||
        !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wpnonce_zalopay'])), 'eonsr_aeo_zalopay_nonce')
    ) {
        wp_die('Yêu cầu không hợp lệ.');
    }

    // 2. Sanitize Input
    $user_name  = isset($_POST['user_name']) ? sanitize_text_field(wp_unslash($_POST['user_name'])) : '';
    $user_email = isset($_POST['user_email']) ? sanitize_email(wp_unslash($_POST['user_email'])) : '';
    $product_id = isset($_POST['product_id']) ? sanitize_text_field(wp_unslash($_POST['product_id'])) : '';
    $domain     = site_url();

    // 3. Prepare Payload
    $api_url = EONSR_AEO_AGENT_API_URL . '/api/v1/zaloPay/create-payment';

    $body = [
        'productIds' => [$product_id], // Send as array per React standard
        'userInfo'   => [
            'email'  => $user_email,
            'name'   => $user_name,
            'domain' => $domain,
        ],
        'source'     => 'plugin',
    ];

    $args = [
        'body'    => wp_json_encode($body),
        'headers' => ['Content-Type' => 'application/json'],
        'timeout' => 30,
        'method'  => 'POST',
    ];

    // 4. Call API
    $response = wp_remote_post($api_url, $args);

    // 5. Handle Response
    $redirect_url = admin_url('admin.php?page=eonsr_aeo_agent_purchase');

    if (is_wp_error($response)) {
        $error_message = $response->get_error_message();
        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for payment gateway debugging
        error_log('[EONSR AEO Payment] ZaloPay Connection Error: ' . $error_message);
        
        $redirect_url = add_query_arg([
            'status'  => 'error',
            'message' => urlencode('Lỗi kết nối API: ' . $error_message)
        ], $redirect_url);

    } else {
        $response_code = wp_remote_retrieve_response_code($response);
        $response_body = json_decode(wp_remote_retrieve_body($response), true);

        if ($response_code === 200 && !empty($response_body['success']) && !empty($response_body['payUrl'])) {
            // Success: Redirect to Gateway
            wp_safe_redirect($response_body['payUrl']);
            exit;
        } else {
            // API Error
            $error_msg = $response_body['message'] ?? 'Lỗi không xác định từ server thanh toán.';
            
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for API error tracking
            error_log('[EONSR AEO Payment] ZaloPay API Error: ' . $error_msg);

            $redirect_url = add_query_arg([
                'status'  => 'error',
                'message' => urlencode($error_msg)
            ], $redirect_url);
        }
    }

    wp_safe_redirect($redirect_url);
    exit;
}

/* ==========================================================================
   SECTION 2: PAYPAL HANDLER
   ========================================================================== */

/**
 * Handle PayPal Payment Request (One-Click Upgrade).
 *
 * Supports single product and multiple addons.
 * Passes `isUpgrade` flag to backend for auto-activation handling.
 */
/**
 * Handle PayPal Payment Request (One-Click Upgrade).
 * FIXED: Added Debug Logging & Robust Link Detection
 */
function eonsr_aeo_handle_paypal_payment()
{
    // 1. Security Check
    if (
        !current_user_can('manage_options') ||
        !isset($_POST['_wpnonce_paypal']) ||
        !wp_verify_nonce(sanitize_text_field(wp_unslash($_POST['_wpnonce_paypal'])), 'eonsr_aeo_paypal_nonce')
    ) {
        wp_die('Yêu cầu không hợp lệ (Nonce failed).');
    }

    // 2. Sanitize Data
    $user_name     = isset($_POST['user_name']) ? sanitize_text_field(wp_unslash($_POST['user_name'])) : '';
    $user_email    = isset($_POST['user_email']) ? sanitize_email(wp_unslash($_POST['user_email'])) : '';
    $product_id    = isset($_POST['product_id']) ? sanitize_text_field(wp_unslash($_POST['product_id'])) : '';
    $addon_ids_str = isset($_POST['addon_ids']) ? sanitize_text_field(wp_unslash($_POST['addon_ids'])) : '';
    $amount        = isset($_POST['amount']) ? sanitize_text_field(wp_unslash($_POST['amount'])) : 0;

    // 3. Process Product IDs
    $product_ids = [$product_id];
    
    if (!empty($addon_ids_str)) {
        $addon_ids   = explode(',', $addon_ids_str);
        $addon_ids   = array_filter($addon_ids);
        $product_ids = array_merge($product_ids, $addon_ids);
    }

    $is_upgrade = true; 

    // 4. Call Backend API
    $api_url = EONSR_AEO_AGENT_API_URL . '/api/v1/paypal/create-payment';

    $body = [
        'productIds' => $product_ids,
        'userInfo'   => [
            'email'     => $user_email,
            'name'      => $user_name,
            'domain'    => site_url(),
            'isUpgrade' => $is_upgrade
        ],
        'amount'     => $amount, // Gửi thêm amount để log bên server dễ check
        'source'     => 'plugin'
    ];

    $response = wp_remote_post($api_url, [
        'method'  => 'POST',
        'body'    => json_encode($body),
        'headers' => ['Content-Type' => 'application/json'],
        'timeout' => 45
    ]);

    // 5. Handle Response
    $redirect_url_error = admin_url('admin.php?page=eonsr_aeo_agent_purchase');

    if (is_wp_error($response)) {
        $error_message = $response->get_error_message();
        // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- PayPal connection debugging
        error_log('[EONSR DEBUG] PayPal Connection Error: ' . $error_message);
        
        wp_safe_redirect(add_query_arg(
            ['status' => 'error', 'message' => urlencode('Lỗi kết nối API: ' . $error_message)],
            $redirect_url_error
        ));
        exit;
    }

    $body_str = wp_remote_retrieve_body($response);
    $result   = json_decode($body_str, true);

    if (isset($result['success']) && $result['success']) {
        // Find Approval Link (Logic mở rộng để bắt được mọi trường hợp)
        $approve_link = '';

        // Case 1: approvalUrl nằm ngay ngoài
        if (!empty($result['approvalUrl'])) {
            $approve_link = $result['approvalUrl'];
        }
        // Case 2: paymentUrl (một số server dùng key này)
        elseif (!empty($result['paymentUrl'])) {
            $approve_link = $result['paymentUrl'];
        }
        // Case 3: Nằm trong object order -> links (Chuẩn PayPal SDK)
        elseif (isset($result['order']['links'])) {
            foreach ($result['order']['links'] as $link) {
                if ($link['rel'] === 'approve' || $link['rel'] === 'payer-action') {
                    $approve_link = $link['href'];
                    break;
                }
            }
        }
        // Case 4: Trả về thẳng url
        elseif (!empty($result['url'])) {
            $approve_link = $result['url'];
        }

        if ($approve_link) {
            // phpcs:ignore WordPress.Security.SafeRedirect.wp_redirect_wp_redirect -- Chuyển hướng đến cổng thanh toán PayPal
            wp_redirect($approve_link);
            exit;
        } else {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- PayPal approval link detection failure tracking
            error_log('[EONSR DEBUG] Không tìm thấy Link PayPal trong phản hồi.');
        }
    }

    // Fallback Error
    $msg = $result['message'] ?? 'Không nhận được link thanh toán từ Server.';
    
    wp_safe_redirect(add_query_arg(
        ['status' => 'error', 'message' => urlencode($msg)],
        $redirect_url_error
    ));
    exit;
}

/* ==========================================================================
   SECTION 3: CALLBACK HANDLING (RETURN URL)
   ========================================================================== */

/**
 * Handle PayPal Return Callback (Capture Order).
 *
 * Triggered when user returns from PayPal after payment.
 * Calls backend to capture payment and auto-activates license.
 */
function eonsr_aeo_handle_paypal_return_callback()
{
    // Validate Query Params
    // phpcs:disable WordPress.Security.NonceVerification.Recommended
    if (
        isset($_GET['page']) && 
        sanitize_text_field(wp_unslash($_GET['page'])) === 'eonsr_aeo_agent' &&
        isset($_GET['paypal_return']) && 
        isset($_GET['token'])
    ) {
        $order_id = sanitize_text_field(wp_unslash($_GET['token']));
        // phpcs:enable WordPress.Security.NonceVerification.Recommended

        // 1. Call Capture API (Node.js)
        $api_url = EONSR_AEO_AGENT_API_URL . '/api/v1/paypal/capture-order/' . $order_id;

        $response = wp_remote_post($api_url, [
            'method'  => 'POST',
            'headers' => ['Content-Type' => 'application/json'],
            'body'    => '{}', // Empty JSON object is required
            'timeout' => 60
        ]);

        if (is_wp_error($response)) {
            
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log -- Logging for capture failures
            error_log('[EONSR AEO Payment] Capture Connection Error: ' . $response->get_error_message());
            
            // FIX: Added esc_html() to sanitize the error message before outputting
            wp_die('Lỗi kết nối khi kích hoạt: ' . esc_html($response->get_error_message()));
        }

        $body          = json_decode(wp_remote_retrieve_body($response), true);
        $response_code = wp_remote_retrieve_response_code($response);

        if ($response_code !== 200) {
            // phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log, WordPress.PHP.DevelopmentFunctions.error_log_print_r -- Logging full response for debugging
            error_log('[EONSR AEO Payment] Capture Failed: ' . print_r($body, true));
        }

        // 2. Process Result
        if (isset($body['success']) && $body['success']) {

            // A. Auto-Activate (Upgrade Flow)
            if (isset($body['activation']) && !empty($body['activation'])) {
                $act = $body['activation'];

                // Reset Settings before applying new plan
                eonsr_aeo_reset_plugin_settings();

                // Save New License Data
                update_option('eonsr_aeo_agent_license_key', $act['licenseKey']);
                update_option('eonsr_aeo_agent_license_status', 'activated');
                update_option('eonsr_aeo_agent_license_plan', strtolower($act['planType']));

                // Save Details & Features
                $act['valid'] = true;
                update_option('eonsr_aeo_agent_license_details', $act);

                if (isset($act['features'])) {
                    update_option('eonsr_aeo_agent_license_features', $act['features']);
                }

                // Refresh Cache
                delete_transient('eonsr_aeo_agent_recheck_license');
                set_transient('eonsr_aeo_agent_recheck_license', 'true', 12 * HOUR_IN_SECONDS);

                // Redirect with Success Message
                wp_safe_redirect(admin_url('admin.php?page=eonsr_aeo_agent&status=success&message=' . urlencode('🚀 Nâng cấp thành công! Cài đặt đã được làm mới.')));
                exit;
            } 
            
            // B. Manual Activation Fallback
            else {
                $key = isset($body['licenseKeys'][0]) ? $body['licenseKeys'][0] : '';
                wp_safe_redirect(admin_url('admin.php?page=eonsr_aeo_agent_license&status=manual&key=' . $key));
                exit;
            }

        } else {
            // Failure
            $msg = $body['message'] ?? 'Giao dịch thất bại (Server Error).';
            wp_die('Lỗi thanh toán: ' . esc_html($msg));
        }
    }
}

/**
 * Reset Plugin Settings (Factory Reset).
 *
 * Used during upgrades to force user to re-configure based on new plan limits.
 */
function eonsr_aeo_reset_plugin_settings()
{
    $options_to_delete = [
        'eonsr_aeo_agent_setup_completed',      // Reset Wizard
        'eonsr_aeo_agent_selected_languages',   // Reset Langs
        'eonsr_aeo_agent_selected_countries',   // Reset Countries
        'eonsr_aeo_agent_keywords',             // Reset Keywords
        'eonsr_aeo_agent_schedule_settings',    // Reset Schedule
        'eonsr_aeo_agent_tone_voice',           // Reset Tone
        'eonsr_aeo_agent_license_features',     // Reset Features
    ];

    foreach ($options_to_delete as $option) {
        delete_option($option);
    }
}