<?php
/**
 * PayStarSea Payment Gateway
 * 
 * WooCommerce payment gateway implementation
 */

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

// phpcs:ignore WordPress.NamingConventions.PrefixAllGlobals.NonPrefixedClassFound
class WC_Gateway_SeaxPay extends WC_Payment_Gateway {
    
    public function __construct() {
        $this->id = 'seaxpay';
        $this->icon = SEAXPAY_PLUGIN_URL . 'assets/images/paystarsea-logo.png';
        $this->has_fields = false;
        $this->method_title = __('PayStarSea Crypto Payment', 'paystarsea-crypto-payment-gateway');
        $this->method_description = __('Accept cryptocurrency payments (USDT, BTC, ETH) via PayStarSea payment gateway.', 'paystarsea-crypto-payment-gateway');
        
        $this->supports = array(
            'products'
        );
        
        $this->init_form_fields();
        $this->init_settings();
        
        $this->enabled = $this->get_option('enabled');
        $title_opt = $this->get_option('title');
        $this->title = !empty($title_opt) ? sanitize_text_field($title_opt) : __('Cryptocurrency Payment', 'paystarsea-crypto-payment-gateway');
        $desc_opt = $this->get_option('description');
        $this->description = !empty($desc_opt) ? wp_kses_post($desc_opt) : __('Pay with USDT, BTC, ETH and other cryptocurrencies', 'paystarsea-crypto-payment-gateway');
        
        add_action('woocommerce_update_options_payment_gateways_' . $this->id, array($this, 'process_admin_options'));
        add_action('woocommerce_api_seaxpay_payment', array($this, 'payment_page'));
        add_action('wp_enqueue_scripts', array($this, 'payment_scripts'));
        
        if (!$this->is_valid_for_use()) {
            $this->enabled = 'no';
            add_action('admin_notices', array($this, 'currency_unsupported_notice'));
        }
    }

    public function currency_unsupported_notice() {
        if (!current_user_can('manage_woocommerce')) {
            return;
        }

        $screen = function_exists('get_current_screen') ? get_current_screen() : null;
        if (!$screen || $screen->id !== 'woocommerce_page_wc-settings') {
            return;
        }

        // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        if (!isset($_GET['tab']) || sanitize_text_field(wp_unslash($_GET['tab'])) !== 'checkout') {
            return;
        }

        ?>
        <div class="notice notice-error is-dismissible">
            <p><?php esc_html_e('Current WooCommerce store currency is not supported by PayStarSea Crypto Payment Gateway', 'paystarsea-crypto-payment-gateway'); ?></p>
        </div>
        <?php
    }
    
    public function is_valid_for_use() {
        $supported_currencies = apply_filters('seaxpay_supported_currencies', array(
            'USD', 'EUR', 'GBP', 'JPY', 'CNY', 'HKD', 'SGD', 'AUD', 'CAD',
            'CHF', 'SEK', 'NOK', 'DKK', 'NZD', 'ZAR', 'BRL', 'MXN', 'INR',
            'KRW', 'TWD', 'THB', 'MYR', 'IDR', 'PHP', 'VND'
        ));
        
        if (in_array(get_woocommerce_currency(), $supported_currencies)) {
            return true;
        }
        return false;
    }
    
    public function init_form_fields() {
        $this->form_fields = array(
            'enabled' => array(
                'title' => __('Enable/Disable', 'paystarsea-crypto-payment-gateway'),
                'type' => 'checkbox',
                'label' => __('Enable PayStarSea Crypto Payment', 'paystarsea-crypto-payment-gateway'),
                'default' => 'yes'
            ),
            'title' => array(
                'title' => __('Title', 'paystarsea-crypto-payment-gateway'),
                'type' => 'text',
                'description' => __('Payment method title that customers see during checkout.', 'paystarsea-crypto-payment-gateway'),
                'default' => __('Cryptocurrency Payment', 'paystarsea-crypto-payment-gateway'),
                'desc_tip' => true
            ),
            'description' => array(
                'title' => __('Description', 'paystarsea-crypto-payment-gateway'),
                'type' => 'textarea',
                'description' => __('Payment method description that customers see during checkout.', 'paystarsea-crypto-payment-gateway'),
                'default' => __('Pay with USDT, BTC, ETH and other cryptocurrencies', 'paystarsea-crypto-payment-gateway'),
                'desc_tip' => true
            ),
            'quick_links' => array(
                'title' => __('Quick Links', 'paystarsea-crypto-payment-gateway'),
                'type' => 'title',
                'description' => sprintf(
                    __('After installing the plugin, please register and log in to the merchant dashboard to obtain the API credentials required below.', 'paystarsea-crypto-payment-gateway') . '<br/>'
                    . '<a href="%s" target="_blank" style="text-decoration:none;">&#x1f517; ' . __('Merchant Dashboard', 'paystarsea-crypto-payment-gateway') . '</a>'
                    . '&nbsp;&nbsp;&nbsp;&nbsp;'
                    . '<a href="%s" target="_blank" style="text-decoration:none;">&#x1f310; ' . __('Official Website', 'paystarsea-crypto-payment-gateway') . '</a>',
                    'https://merchant.paystarsea.com',
                    'https://www.paystarsea.com'
                )
            ),
            'api_settings' => array(
                'title' => __('API Settings', 'paystarsea-crypto-payment-gateway'),
                'type' => 'title',
                'description' => __('Configure your PayStarSea API credentials.', 'paystarsea-crypto-payment-gateway')
            ),
            'api_key' => array(
                'title' => __('API Key', 'paystarsea-crypto-payment-gateway') . ' <span style="color:red;">*</span>',
                'type' => 'text',
                'description' => __('Your PayStarSea API Key. You can find this in your PayStarSea merchant dashboard.', 'paystarsea-crypto-payment-gateway'),
                'desc_tip' => false,
                'custom_attributes' => array('required' => 'required')
            ),
            'api_secret' => array(
                'title' => __('API Secret', 'paystarsea-crypto-payment-gateway') . ' <span style="color:red;">*</span>',
                'type' => 'password',
                'description' => __('Your PayStarSea API Secret. Keep this secure and never share it.', 'paystarsea-crypto-payment-gateway'),
                'desc_tip' => false,
                'custom_attributes' => array('required' => 'required')
            ),
            'webhook_secret' => array(
                'title' => __('Webhook Secret', 'paystarsea-crypto-payment-gateway') . ' <span style="color:red;">*</span>',
                'type' => 'text',
                'description' => __('Webhook signature secret for verifying payment notifications. This must match the webhook secret in your PayStarSea merchant weebhook settings.', 'paystarsea-crypto-payment-gateway'),
                'desc_tip' => false,
                'custom_attributes' => array('required' => 'required')
            ),
            'merchant_no' => array(
                'title' => __('Merchant No', 'paystarsea-crypto-payment-gateway') . ' <span style="color:red;">*</span>',
                'type' => 'text',
                'description' => __('Your PayStarSea Merchant No. This is used to filter available cryptocurrencies based on your wallet configuration.', 'paystarsea-crypto-payment-gateway'),
                'desc_tip' => false,
                'custom_attributes' => array('required' => 'required')
            ),
            'enabled_coins' => array(
                'title' => __('Enabled Coins', 'paystarsea-crypto-payment-gateway'),
                'type' => 'enabled_coins',
                'description' => __('Toggle ON/OFF to enable or disable each cryptocurrency.', 'paystarsea-crypto-payment-gateway')
            ),
            'enabled_networks' => array(
                'title' => __('Enabled Networks', 'paystarsea-crypto-payment-gateway'),
                'type' => 'enabled_networks',
                'description' => __('Toggle ON/OFF to enable or disable networks for each enabled coin.', 'paystarsea-crypto-payment-gateway')
            ),
            'payment_settings' => array(
                'title' => __('Payment Settings', 'paystarsea-crypto-payment-gateway'),
                'type' => 'title',
                'description' => __('Configure payment behavior.', 'paystarsea-crypto-payment-gateway')
            ),
            'auto_complete_order' => array(
                'title' => __('Auto Complete Order', 'paystarsea-crypto-payment-gateway'),
                'type' => 'checkbox',
                'label' => __('Automatically complete order after payment confirmed', 'paystarsea-crypto-payment-gateway'),
                'default' => 'yes',
                'description' => __('If enabled, orders will be automatically marked as completed after payment confirmation.', 'paystarsea-crypto-payment-gateway')
            ),
        );
    }
    
    public function generate_enabled_coins_html($key, $data) {
        $defaults = array(
            'title' => '',
            'description' => '',
        );
        $data = wp_parse_args($data, $defaults);
        
        ob_start();
        ?>
        <tr valign="top">
            <th scope="row" class="titledesc">
                <label><?php echo wp_kses_post($data['title']); ?></label>
            </th>
            <td class="forminp">
                <div id="seaxpay-coins-list" class="seaxpay-toggle-container">
                    <p class="seaxpay-loading"><?php esc_html_e('Enter Merchant No above to load available coins.', 'paystarsea-crypto-payment-gateway'); ?></p>
                </div>
                <?php if ($data['description']) : ?>
                    <p class="description"><?php echo wp_kses_post($data['description']); ?></p>
                <?php endif; ?>
            </td>
        </tr>
        <?php
        return ob_get_clean();
    }
    
    public function generate_enabled_networks_html($key, $data) {
        $defaults = array(
            'title' => '',
            'description' => '',
        );
        $data = wp_parse_args($data, $defaults);
        
        ob_start();
        ?>
        <tr valign="top">
            <th scope="row" class="titledesc">
                <label><?php echo wp_kses_post($data['title']); ?></label>
            </th>
            <td class="forminp">
                <div id="seaxpay-networks-list" class="seaxpay-toggle-container">
                    <p class="seaxpay-hint"><?php esc_html_e('Enable coins above to see available networks.', 'paystarsea-crypto-payment-gateway'); ?></p>
                </div>
                <?php if ($data['description']) : ?>
                    <p class="description"><?php echo wp_kses_post($data['description']); ?></p>
                <?php endif; ?>
            </td>
        </tr>
        <?php
        return ob_get_clean();
    }
    
    public function is_available() {
        if ($this->enabled !== 'yes') {
            return false;
        }
        
        if (!$this->is_valid_for_use()) {
            return false;
        }
        
        $api_key = $this->get_option('api_key');
        $api_secret = $this->get_option('api_secret');
        
        if (empty($api_key) || empty($api_secret)) {
            return false;
        }
        
        $supported_coins = seaxpay_get_supported_coins();
        if (empty($supported_coins)) {
            return false;
        }
        
        return parent::is_available();
    }
    
    public function process_admin_options() {
        $saved = parent::process_admin_options();
        
        $merchant_no = $this->get_option('merchant_no');
        if ($merchant_no) {
            $enabled_coins = isset($_POST['seaxpay_enabled_coins']) ? sanitize_text_field(wp_unslash($_POST['seaxpay_enabled_coins'])) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing
            $enabled_networks = isset($_POST['seaxpay_enabled_networks']) ? sanitize_text_field(wp_unslash($_POST['seaxpay_enabled_networks'])) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Missing
            
            if ($enabled_coins) {
                update_option('seaxpay_enabled_coins_' . $merchant_no, $enabled_coins);
            }
            if ($enabled_networks) {
                update_option('seaxpay_enabled_networks_' . $merchant_no, $enabled_networks);
            }
            
            delete_transient('seaxpay_supported_coins_' . $merchant_no);
        }
        
        $api_key = $this->get_option('api_key');
        $api_secret = $this->get_option('api_secret');
        
        if (!empty($api_key) && !empty($api_secret)) {
            try {
                $api_client = new SeaXPay_API_Client(
                    $api_key,
                    $api_secret
                );
                
                $test_result = $api_client->test_connection();
                
                if ($test_result['success']) {
                    WC_Admin_Settings::add_message(__('API connection test successful!', 'paystarsea-crypto-payment-gateway'));
                } else {
                    WC_Admin_Settings::add_error(
                        /* translators: %s: error message */
                        sprintf(__('API connection test failed: %s', 'paystarsea-crypto-payment-gateway'), $test_result['message'])
                    );
                }
            } catch (Exception $e) {
                WC_Admin_Settings::add_error(
                    /* translators: %s: error message */
                    sprintf(__('API connection test failed: %s', 'paystarsea-crypto-payment-gateway'), $e->getMessage())
                );
            }
        }
        
        return $saved;
    }
    
    public function process_payment($order_id) {
        $order = wc_get_order($order_id);
        
        $coin = null;
        $network = null;
        
    
        if (isset($_POST['seaxpay_coin'])) { // phpcs:ignore WordPress.Security.NonceVerification.Missing
            $coin = sanitize_text_field(wp_unslash($_POST['seaxpay_coin'])); // phpcs:ignore WordPress.Security.NonceVerification.Missing
        }
        if (isset($_POST['seaxpay_network'])) { // phpcs:ignore WordPress.Security.NonceVerification.Missing
            $network = sanitize_text_field(wp_unslash($_POST['seaxpay_network'])); // phpcs:ignore WordPress.Security.NonceVerification.Missing
        }
        
        if (!$coin) {
            $payment_method_data = $order->get_meta('_payment_method_data');
            if (!empty($payment_method_data) && is_array($payment_method_data)) {
                if (isset($payment_method_data['seaxpay_coin'])) {
                    $coin = sanitize_text_field($payment_method_data['seaxpay_coin']);
                }
                if (isset($payment_method_data['seaxpay_network'])) {
                    $network = sanitize_text_field($payment_method_data['seaxpay_network']);
                }
            }
        }
        
        if (!$coin) {
            $coin = $order->get_meta('_seaxpay_coin');
        }
        if (!$network) {
            $network = $order->get_meta('_seaxpay_network');
        }
        
        if (!$coin) {
            $supported_coins = seaxpay_get_supported_coins();
            if (!empty($supported_coins)) {
                $coin_keys = array_keys($supported_coins);
                $coin = $coin_keys[0];
            } else {
                $coin = 'USDT';
            }
        }
        if (!$network) {
            $supported_coins = seaxpay_get_supported_coins();
            if (isset($supported_coins[$coin]['networks'])) {
                $network_keys = array_keys($supported_coins[$coin]['networks']);
                $network = $network_keys[0];
            } else {
                $network = 'TRC20';
            }
        }
        
        seaxpay_log('order', sprintf('Creating order with coin=%s, network=%s', $coin, $network), $order_id, null, seaxpay_sanitize_for_log(array('coin' => $coin, 'network' => $network, 'order_total' => $order->get_total())), null);
        
        global $wpdb;
        $table_name = $wpdb->prefix . 'seaxpay_orders';
        if (function_exists('seaxpay_find_reusable_order')) {
            $existing_order = seaxpay_find_reusable_order($order_id, null, null);
        } else {
            // phpcs:disable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
            $existing_order = $wpdb->get_row($wpdb->prepare(
                "SELECT * FROM {$table_name} WHERE wc_order_id = %d AND status IN ('pending', 'processing', 'confirming') ORDER BY id DESC LIMIT 1",
                $order_id
            ));
            // phpcs:enable WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching, WordPress.DB.PreparedSQL.InterpolatedNotPrepared, PluginCheck.Security.DirectDB.UnescapedDBParameter
        }
        
        if ($existing_order) {
            seaxpay_log('order', 'Reusing existing payment order', $order_id, $existing_order->platform_order_no, null, null);
            
            $order->update_meta_data('_seaxpay_coin', $existing_order->coin);
            $order->update_meta_data('_seaxpay_network', $existing_order->network);
            $order->update_meta_data('_seaxpay_platform_order_no', $existing_order->platform_order_no);
            $order->update_meta_data('_seaxpay_crypto_amount', $existing_order->crypto_amount);
            $order->update_meta_data('_seaxpay_platform_address', $existing_order->customer_address);
            $order->update_meta_data('_seaxpay_address_mode', $existing_order->address_mode ?? 'fingerprint');
            if (!empty($existing_order->expire_time)) {
                $order->update_meta_data('_seaxpay_expire_time', $existing_order->expire_time);
            }
            $order->save();
            
            return array(
                'result' => 'success',
                'redirect' => add_query_arg(
                    array(
                        'order_id' => $order_id,
                        'key' => $order->get_order_key(),
                    ),
                    wc_get_endpoint_url('seaxpay-payment', '', wc_get_checkout_url())
                )
            );
        }
        
        try {
            $api_client = new SeaXPay_API_Client();

            $merchant_order_no = function_exists('seaxpay_build_merchant_order_no')
                ? seaxpay_build_merchant_order_no($order_id, $coin, $network)
                : strval($order_id);

            $response = $api_client->create_order(
                $merchant_order_no,
                $order->get_total(),
                $order->get_currency(),
                $coin,
                $network,
                WC()->api_request_url('seaxpay_webhook'),
                $order->get_checkout_order_received_url()
            );
            
            $inserted = $wpdb->insert( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery
                "{$wpdb->prefix}seaxpay_orders",
                array(
                    'wc_order_id' => $order_id,
                    'user_id' => $order->get_user_id(),
                    'platform_order_no' => $response['orderNo'],
                    'local_order_no' => $merchant_order_no,
                    'coin' => $coin,
                    'network' => $network,
                    'fiat_amount' => $order->get_total(),
                    'fiat_currency' => $order->get_currency(),
                    'crypto_amount' => strval($response['cryptoAmount'] ?? null),
                    'exchange_rate' => $response['exchangeRate'] ?? null,
                    'customer_address' => $response['paymentAddress'] ?? null,
                    'address_mode' => $response['addressMode'] ?? 'fingerprint',
                    'status' => 'pending',
                    'expire_time' => isset($response['expireTime']) ? gmdate('Y-m-d H:i:s', $response['expireTime'] / 1000) : null
                ),
                array(
                    '%d',
                    '%d',
                    '%s',
                    '%s',
                    '%s',
                    '%s',
                    '%f',
                    '%s',
                    '%s',
                    '%f',
                    '%s',
                    '%s',
                    '%s',
                    '%s'
                )
            );

            if ($inserted === false) {
                seaxpay_log('error', 'Failed to insert seaxpay_orders: ' . $wpdb->last_error,
                    $order_id, $response['orderNo'] ?? null, null, null);
                throw new Exception(__('Database insert failed', 'paystarsea-crypto-payment-gateway'));
            }

            $order->update_meta_data('_seaxpay_coin', $coin);
            $order->update_meta_data('_seaxpay_network', $network);
            $order->update_meta_data('_seaxpay_platform_order_no', $response['orderNo']);
            $order->update_meta_data('_seaxpay_crypto_amount', $response['cryptoAmount'] ?? '');
            $order->update_meta_data('_seaxpay_platform_address', $response['paymentAddress'] ?? '');
            $order->update_meta_data('_seaxpay_address_mode', $response['addressMode'] ?? 'fingerprint');
            if (isset($response['expireTime'])) {
                $order->update_meta_data('_seaxpay_expire_time', gmdate('Y-m-d H:i:s', $response['expireTime'] / 1000));
            }
            $order->save();
            
            seaxpay_log('order', 'Order created via API', $order_id, $response['orderNo'], null, null);
            
            $order->update_status('pending', __('Awaiting cryptocurrency payment', 'paystarsea-crypto-payment-gateway'));
            
            WC()->cart->empty_cart();
            
            return array(
                'result' => 'success',
                'redirect' => add_query_arg(
                    array(
                        'order_id' => $order_id,
                        'key' => $order->get_order_key()
                    ),
                    WC()->api_request_url('seaxpay_payment')
                )
            );
            
        } catch (Exception $e) {
            seaxpay_log('error', 'Failed to create order via API: ' . $e->getMessage(), $order_id, null, null, null);
            wc_add_notice(__('Payment error: ', 'paystarsea-crypto-payment-gateway') . $e->getMessage(), 'error');
            return array(
                'result' => 'failure',
                'messages' => $e->getMessage()
            );
        }
    }
    
    public function payment_page() {
        $order_id = isset($_GET['order_id']) ? absint($_GET['order_id']) : 0; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        $order_key = isset($_GET['key']) ? sanitize_text_field(wp_unslash($_GET['key'])) : ''; // phpcs:ignore WordPress.Security.NonceVerification.Recommended
        
        if (!$order_id || !$order_key) {
            wp_die(esc_html__('Invalid order', 'paystarsea-crypto-payment-gateway'));
        }
        
        $order = wc_get_order($order_id);
        
        if (!$order || $order->get_order_key() !== $order_key) {
            wp_die(esc_html__('Invalid order', 'paystarsea-crypto-payment-gateway'));
        }
        
        $seaxpay_order = seaxpay_get_order_by_wc_id($order_id);
        
        $platform_address = $seaxpay_order ? $seaxpay_order->customer_address : $order->get_meta('_seaxpay_platform_address');
        $selected_coin = $seaxpay_order ? $seaxpay_order->coin : $order->get_meta('_seaxpay_coin');
        $expire_time = $seaxpay_order ? $seaxpay_order->expire_time : $order->get_meta('_seaxpay_expire_time');
        $platform_order_no = $seaxpay_order ? $seaxpay_order->platform_order_no : $order->get_meta('_seaxpay_platform_order_no');
        $is_expired = false;
        if ($seaxpay_order && $seaxpay_order->status === 'expired') {
            $is_expired = true;
        } elseif ($expire_time) {
            $expire_timestamp = strtotime($expire_time . ' UTC');
            $is_expired = ($expire_timestamp !== false && $expire_timestamp < time());
        }

        seaxpay_enqueue_payment_page_assets($order, $is_expired, $platform_address, $expire_time, $selected_coin, $platform_order_no);

        get_header();
        include SEAXPAY_PLUGIN_DIR . 'templates/payment-page.php';
        get_footer();
        exit;
    }
    
    public function payment_scripts() {
        if (!is_wc_endpoint_url('order-pay') && !isset($_GET['seaxpay_payment'])) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            return;
        }
        
        wp_enqueue_style('seaxpay-payment', SEAXPAY_PLUGIN_URL . 'assets/css/payment.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', SEAXPAY_PLUGIN_URL . 'assets/js/payment.js', array('jquery', 'seaxpay-qrcode-js'), SEAXPAY_VERSION, true);

        wp_localize_script('seaxpay-payment', 'seaxpayL10n', array(
            'ajax_url' => admin_url('admin-ajax.php'),
            'nonce' => wp_create_nonce('seaxpay_payment'),
            'selectCoin' => __('Select Cryptocurrency', 'paystarsea-crypto-payment-gateway'),
            'payNow' => __('Pay Now', 'paystarsea-crypto-payment-gateway'),
            'copyAddress' => __('Copy Address', 'paystarsea-crypto-payment-gateway'),
            'copyAmount' => __('Copy Amount', 'paystarsea-crypto-payment-gateway'),
            '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'),
            'paymentFailed' => __('Payment failed', 'paystarsea-crypto-payment-gateway'),
            'checkingStatus' => __('Checking payment status...', 'paystarsea-crypto-payment-gateway'),
            'timeRemaining' => __('Time Remaining', 'paystarsea-crypto-payment-gateway'),
            'expired' => __('Expired', 'paystarsea-crypto-payment-gateway'),
            'qrCodeUnavailable' => __('QR code could not be loaded. Please copy the payment address manually.', 'paystarsea-crypto-payment-gateway'),
        ));
    }
}
