<?php
/**
 * Helper Functions
 */

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

function seaxpay_get_config() {
    $wc_settings = get_option('woocommerce_seaxpay_settings', array());
    
    $config = new stdClass();
    $config->api_url = SEAXPAY_API_URL;
    $config->api_key = $wc_settings['api_key'] ?? '';
    $config->api_secret = $wc_settings['api_secret'] ?? '';
    $config->webhook_secret = $wc_settings['webhook_secret'] ?? '';
    $config->merchant_no = $wc_settings['merchant_no'] ?? null;
    $config->test_mode = ($wc_settings['test_mode'] ?? 'yes') === 'yes' ? 1 : 0;
    $config->default_coin = $wc_settings['default_coin'] ?? 'USDT';
    $config->default_network = $wc_settings['default_network'] ?? 'TRC20';
    $config->auto_complete_order = ($wc_settings['auto_complete_order'] ?? 'yes') === 'yes' ? 1 : 0;
    
    return $config;
}


function seaxpay_sanitize_log_payload($data) {
    if (is_array($data)) {
        return seaxpay_sanitize_for_log($data);
    }
    if (is_string($data)) {
        return sanitize_text_field(substr($data, 0, 500));
    }
    return $data;
}

function seaxpay_log($log_type, $message, $wc_order_id = null, $platform_order_no = null, $request_data = null, $response_data = null) {
    global $wpdb;

    if ($request_data !== null) {
        $request_data = seaxpay_sanitize_log_payload($request_data);
    }
    if ($response_data !== null) {
        $response_data = seaxpay_sanitize_log_payload($response_data);
    }

    $ip_address = isset($_SERVER['REMOTE_ADDR']) ? sanitize_text_field(wp_unslash($_SERVER['REMOTE_ADDR'])) : null;

    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    $wpdb->insert(
        "{$wpdb->prefix}seaxpay_logs",
        array(
            'log_type' => $log_type,
            'wc_order_id' => $wc_order_id,
            'platform_order_no' => $platform_order_no,
            'message' => $message,
            'request_data' => $request_data ? wp_json_encode($request_data) : null,
            'response_data' => $response_data ? wp_json_encode($response_data) : null,
            'ip_address' => $ip_address
        )
    );
}

function seaxpay_enqueue_payment_page_assets($order, $is_expired, $platform_address, $expire_time, $selected_coin, $platform_order_no) {
    wp_enqueue_style('seaxpay-payment-page', SEAXPAY_PLUGIN_URL . 'assets/css/payment-page.css', array(), SEAXPAY_VERSION);
    wp_enqueue_script('seaxpay-qrcode-js', SEAXPAY_PLUGIN_URL . 'assets/js/qrcode.min.js', array(), '1.0.0', true);
    wp_enqueue_script('seaxpay-payment-page', SEAXPAY_PLUGIN_URL . 'assets/js/payment-page.js', array('jquery', 'seaxpay-qrcode-js'), SEAXPAY_VERSION, true);

    wp_localize_script('seaxpay-payment-page', 'seaxpayL10n', array(
        'ajax_url' => admin_url('admin-ajax.php'),
        'nonce' => wp_create_nonce('seaxpay_payment'),
        'copied' => __('Copied!', 'paystarsea-crypto-payment-gateway'),
        'waitingPayment' => __('Waiting for payment...', 'paystarsea-crypto-payment-gateway'),
        'paymentSuccess' => __('Payment successful!', 'paystarsea-crypto-payment-gateway'),
        'paymentExpired' => __('Payment has expired', 'paystarsea-crypto-payment-gateway'),
        'checkingStatus' => __('Checking payment status...', 'paystarsea-crypto-payment-gateway'),
        'qrCodeUnavailable' => __('QR code could not be loaded. Please copy the payment address manually.', 'paystarsea-crypto-payment-gateway'),
    ));

    wp_localize_script('seaxpay-payment-page', 'seaxpayPageData', array(
        'address' => $platform_address,
        'expireTime' => $expire_time,
        'coin' => $selected_coin,
        'returnUrl' => $order->get_checkout_order_received_url(),
        'platformOrderNo' => $platform_order_no,
        'isExpired' => $is_expired,
        'checkoutUrl' => wc_get_checkout_url(),
    ));

    wp_localize_script('seaxpay-payment-page', 'seaxpayPageL10n', array(
        'expired' => __('Expired', 'paystarsea-crypto-payment-gateway'),
        'paymentExpiredStatus' => '❌ ' . __('Payment expired. Please create a new order.', 'paystarsea-crypto-payment-gateway'),
        'paymentExpiredTitle' => __('Payment Expired', 'paystarsea-crypto-payment-gateway'),
        'paymentExpiredMessage' => __('This payment order has expired. For security reasons, the payment address is no longer available.', 'paystarsea-crypto-payment-gateway'),
        'returnCheckout' => __('Return to Checkout', 'paystarsea-crypto-payment-gateway'),
        'partialPayment' => __('Partial payment received. Please send the remaining:', 'paystarsea-crypto-payment-gateway'),
        'paymentSuccessRedirect' => '✅ ' . __('Payment successful! Redirecting...', 'paystarsea-crypto-payment-gateway'),
        'paymentFailed' => '❌ ' . __('Payment failed.', 'paystarsea-crypto-payment-gateway'),
        'waitingPayment' => '🔄 ' . __('Waiting for payment...', 'paystarsea-crypto-payment-gateway'),
        'checking' => '🔄 ' . __('Checking...', 'paystarsea-crypto-payment-gateway'),
        'copied' => __('Copied!', 'paystarsea-crypto-payment-gateway'),
        'amountCopiedAlert' => __('Amount copied! Please send EXACTLY this amount to complete payment.', 'paystarsea-crypto-payment-gateway'),
    ));
}

function seaxpay_get_order_by_platform_no($platform_order_no) {
    global $wpdb;
    
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    return $wpdb->get_row($wpdb->prepare(
        "SELECT * FROM {$wpdb->prefix}seaxpay_orders WHERE platform_order_no = %s",
        $platform_order_no
    ));
}

function seaxpay_get_order_by_wc_id($wc_order_id) {
    global $wpdb;
    
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    return $wpdb->get_row($wpdb->prepare(
        "SELECT * FROM {$wpdb->prefix}seaxpay_orders WHERE wc_order_id = %d",
        $wc_order_id
    ));
}

function seaxpay_update_order_status($platform_order_no, $status, $additional_data = array()) {
    global $wpdb;
    
    $update_data = array_merge(
        array('status' => $status),
        $additional_data
    );
    
    // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching
    $wpdb->update(
        "{$wpdb->prefix}seaxpay_orders",
        $update_data,
        array('platform_order_no' => $platform_order_no)
    );
}

function seaxpay_format_crypto_amount($amount, $decimals = 6) {
    return rtrim(rtrim(number_format($amount, $decimals, '.', ''), '0'), '.');
}

function seaxpay_format_crypto_amount_for_display($amount) {
    if (empty($amount)) {
        return $amount;
    }

    $amount_str = (string) $amount;
    $amount_str = rtrim($amount_str, '0');
    $amount_str = rtrim($amount_str, '.');

    return $amount_str;
}

function seaxpay_sanitize_for_log($data) {
    if (!is_array($data)) {
        return $data;
    }

    $sanitized = array();
    $sensitive_keys = array('api_key', 'api_secret', 'signature', 'webhook_secret', 'platform_address', 'customer_address');

    foreach ($data as $key => $value) {
        if (in_array($key, $sensitive_keys, true)) {
            $sanitized[$key] = '***REDACTED***';
            continue;
        }
        if (is_array($value)) {
            $sanitized[$key] = seaxpay_sanitize_for_log($value);
        } elseif (is_numeric($value)) {
            $sanitized[$key] = $value;
        } else {
            $sanitized[$key] = sanitize_text_field((string) $value);
        }
    }

    return $sanitized;
}

function seaxpay_get_supported_coins() {
    $config = seaxpay_get_config();
    $merchant_no = !empty($config->merchant_no) ? $config->merchant_no : null;
    
    if (!$merchant_no) {
        return seaxpay_get_default_coins();
    }
    
    $cache_key = 'seaxpay_supported_coins_' . $merchant_no;
    $cached = get_transient($cache_key);
    
    if ($cached !== false) {
        return $cached;
    }
    
    try {
        $api_client = new SeaXPay_API_Client();
        $coins_data = $api_client->get_supported_coins($merchant_no);
        
        $enabled_coins_json = get_option('seaxpay_enabled_coins_' . $merchant_no, '');
        $enabled_networks_json = get_option('seaxpay_enabled_networks_' . $merchant_no, '');
        
        $enabled_coins_json = stripslashes($enabled_coins_json);
        $enabled_networks_json = stripslashes($enabled_networks_json);
        
        $enabled_coins = json_decode($enabled_coins_json, true);
        $enabled_networks = json_decode($enabled_networks_json, true);
        
        if (empty($enabled_coins) || !is_array($enabled_coins)) {
            return array();
        }
        

        $supported_coins = array();
        
        foreach ($coins_data as $coin_config) {
            $coin = $coin_config['coin'];
            $network = $coin_config['network'];
    
            if (!isset($enabled_coins[$coin]) || $enabled_coins[$coin] !== true) {
                continue;
            }
            
            if (!isset($enabled_networks[$coin][$network]) || $enabled_networks[$coin][$network] !== true) {
                continue;
            }
            
            if (!isset($supported_coins[$coin])) {
                $supported_coins[$coin] = array(
                    'name' => $coin_config['coinName'] ?? $coin,
                    'icon' => seaxpay_get_coin_icon($coin),
                    'networks' => array()
                );
            }
            
            $supported_coins[$coin]['networks'][$network] = array(
                'name' => $coin_config['networkName'] ?? $network,
                'icon' => seaxpay_get_network_icon($network),
                'min_amount_usd' => isset($coin_config['minAmountUsd']) ? floatval($coin_config['minAmountUsd']) : null,
                'recommended' => !empty($coin_config['recommendedForEcommerce']) || (($coin_config['priority'] ?? 0) == 1)
            );
        }
        
        if (!empty($supported_coins)) {
            set_transient($cache_key, $supported_coins, HOUR_IN_SECONDS);
        }
        
        return $supported_coins;
        
    } catch (Exception $e) {
        seaxpay_log('error', 'Failed to get supported coins from API: ' . $e->getMessage(), null, null, null, null);
        return array();
    }
}

function seaxpay_get_default_coins() {
    return array(
        'USDT' => array(
            'name' => 'USDT',
            'icon' => SEAXPAY_PLUGIN_URL . 'assets/images/coins/usdt.png',
            'networks' => array(
                'TRC20' => array(
                    'name' => 'TRON Network',
                    'icon' => SEAXPAY_PLUGIN_URL . 'assets/images/networks/tron.png',
                    'recommended' => true
                )
            )
        )
    );
}

function seaxpay_get_coin_icon($coin) {
    $coin_lower = strtolower($coin);
    $icon_path = SEAXPAY_PLUGIN_DIR . 'assets/images/coins/' . $coin_lower . '.png';
    
    if (file_exists($icon_path)) {
        return SEAXPAY_PLUGIN_URL . 'assets/images/coins/' . $coin_lower . '.png';
    }
    
    return SEAXPAY_PLUGIN_URL . 'assets/images/coins/default.png';
}

function seaxpay_get_network_icon($network) {
    $network_icons = array(
        'TRC20' => 'tron.png',
        'ERC20' => 'ethereum.png',
        'BEP20' => 'bsc.png',
        'Polygon' => 'polygon.png',
        'Bitcoin' => 'bitcoin.png',
        'Ethereum' => 'ethereum.png',
        'Solana' => 'solana.png',
        'BTC' => 'bitcoin.png'
    );
    
    $icon_file = $network_icons[$network] ?? 'default.png';
    return SEAXPAY_PLUGIN_URL . 'assets/images/networks/' . $icon_file;
}

function seaxpay_generate_qrcode_url($data) {
    return '';
}

function seaxpay_is_order_expired($expire_time) {
    if (empty($expire_time)) {
        return false;
    }
    
    $expire_timestamp = strtotime($expire_time . ' UTC');
    $current_timestamp = time();
    
    return $current_timestamp > $expire_timestamp;
}

function seaxpay_get_time_remaining($expire_time) {
    if (empty($expire_time)) {
        return 0;
    }
    
    $expire_timestamp = strtotime($expire_time . ' UTC');
    $current_timestamp = time();
    
    $remaining = $expire_timestamp - $current_timestamp;
    
    return max(0, $remaining);
}

function seaxpay_format_time_remaining($seconds) {
    if ($seconds <= 0) {
        return __('Expired', 'paystarsea-crypto-payment-gateway');
    }
    
    $minutes = floor($seconds / 60);
    $secs = $seconds % 60;
    
    return sprintf('%02d:%02d', $minutes, $secs);
}
