<?php

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

// WooCommerce Gateway Class
class Cregis_WC_Gateway extends WC_Payment_Gateway {
    public function __construct() {
        $this->id = 'cregispay';
        $this->icon = CREGIS_PAYMENT_PLUGIN_URL . 'assets/images/icon.png';
        $this->has_fields = false;
        $this->method_title = __('Cregis Payment', 'cregis-payment-for-woocommerce');
        $this->method_description = __('Accept cryptocurrency payments via Cregis', 'cregis-payment-for-woocommerce');
        $this->supports = array('products', 'refunds');
        
        $this->init_form_fields();
        $this->init_settings();
        
        $this->title = $this->get_option('title');
        $this->enabled = $this->get_option('enabled', 'yes');
        
        // Force translated description - ignore database value
        $this->settings['description'] = __('Pay with cryptocurrencies using Cregis', 'cregis-payment-for-woocommerce');
        $this->description = $this->settings['description'];
        
        add_action('woocommerce_update_options_payment_gateways_' . $this->id, array($this, 'process_admin_options'));
        add_action('woocommerce_thankyou_' . $this->id, array($this, 'thankyou_page'));
    }
    
    public function init_form_fields() {
        $this->form_fields = array(
            'enabled' => array(
                'title' => __('Enable/Disable', 'cregis-payment-for-woocommerce'),
                'type' => 'checkbox',
                'label' => __('Enable Cregis Payment', 'cregis-payment-for-woocommerce'),
                'default' => 'yes'
            ),
            'title' => array(
                'title' => __('Title', 'cregis-payment-for-woocommerce'),
                'type' => 'text',
                'default' => __('Cryptocurrency Payment', 'cregis-payment-for-woocommerce')
            ),
            'description' => array(
                'title' => __('Description', 'cregis-payment-for-woocommerce'),
                'type' => 'textarea',
                'default' => __('Pay with cryptocurrencies using Cregis', 'cregis-payment-for-woocommerce')
            )
        );
    }
    
    /**
     * Check if the gateway is available
     */
    public function is_available() {
        // Always return true to ensure the payment method is displayed
        return true;
    }
    
    public function process_payment($order_id) {
        $order = wc_get_order($order_id);
        $settings = get_option('cregis_payment_settings', array());
        
        if (empty($settings['project_id']) || empty($settings['secret_key'])) {
            wc_add_notice(__('Cregis payment is not properly configured', 'cregis-payment-for-woocommerce'), 'error');
            return array(
                'result' => 'fail'
            );
        }
        
        try {
            $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'] : true // Always enable debug for API requests
            );
            
            // Get payment valid time from settings (default 60 minutes)
            $valid_time = isset($settings['payment_valid_time']) ? intval($settings['payment_valid_time']) : 60;
            
            // Log the payment valid time
            error_log(sprintf('Cregis: Payment valid time setting: %d', $valid_time));
            if (isset($api->logger)) {
                $api->logger->debug(sprintf('Payment valid time setting: %d', $valid_time));
            }
            
            // Get billing email from order
            $user_email = $order->get_billing_email();
            if (empty($user_email)) {
                wc_add_notice(__('Error: Email address is required for payment. Please fill in your email address in the billing information.', 'cregis-payment-for-woocommerce'), 'error');
                return array(
                    'result' => 'fail'
                );
            }
            
            // Log the email used
            error_log(sprintf('Cregis: Using email for payment: %s', $user_email));
            if (isset($api->logger)) {
                $api->logger->debug(sprintf('Using email for payment: %s', $user_email));
            }
            
            // Get user ID
            $user_id = $order->get_user_id();
            if (empty($user_id)) {
                $user_id = 'guest';
            }
            
            // Generate unique order ID with timestamp, random string and microtime
            $unique_id = time() . substr(str_shuffle('abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'), 0, 6) . substr(microtime(), 2, 4);
            
            $order_data = array(
                'order_id' => 'wc_' . $order_id . '_' . $unique_id,
                'order_amount' => $this->format_as_double($order->get_total()),
                'order_currency' => $order->get_currency(),
                'payer_id' => (string)$user_id,
                'payer_email' => $user_email,
                'valid_time' => $valid_time, // Convert to string
                'success_url' => Cregis_Return_Handler::get_return_url($order_id),
                'cancel_url' => Cregis_Return_Handler::get_return_url($order_id),
                'callback_url' => get_rest_url(null, '/cregis/v1/webhook'),
                'remark' => 'Order #' . $order_id
            );
            
            // Set language parameter based on WordPress locale
            $locale = get_locale();
            if (strpos($locale, 'zh_TW') === 0 || strpos($locale, 'zh_HK') === 0) {
                $order_data['language'] = 'tc'; // Traditional Chinese
            } elseif (strpos($locale, 'zh_CN') === 0) {
                $order_data['language'] = 'sc'; // Simplified Chinese
            } else {
                $order_data['language'] = 'en'; // English and others
            }
            
            if (isset($api->logger)) {
                $api->logger->debug(sprintf('Setting language parameter to: %s (locale: %s)', $order_data['language'], $locale));
            }
            
            // Log the payer ID used
            error_log(sprintf('Cregis: Using payer ID: %s', $order_data['payer_id']));
            if (isset($api->logger)) {
                $api->logger->debug(sprintf('Using payer ID: %s', $order_data['payer_id']));
            }
            
            // Check accept_all_underpaid setting
            $accept_all_underpaid = isset($settings['accept_all_underpaid']) && $settings['accept_all_underpaid'] === 'yes';
            
            // Check accept_all_overpaid setting
            $accept_all_overpaid = isset($settings['accept_all_overpaid']) && $settings['accept_all_overpaid'] === 'yes';
            
            // Handle underpaid tolerance settings
            if ($accept_all_underpaid) {
                // If accept_all_underpaid is enabled, don't include accept_partial_payment and underpaid_tolerance
                // API will use default value (true) for accept_partial_payment
                if (isset($api->logger)) {
                    $api->logger->debug('Accept all underpaid is enabled, skipping accept_partial_payment and underpaid_tolerance');
                }
            } else {
                // If accept_all_underpaid is disabled, set accept_partial_payment to false and include tolerance
                $order_data['accept_partial_payment'] = 'false';
                
                // Calculate underpaid tolerance amount
                $order_total = $order->get_total();
                $underpaid_tolerance_percent = isset($settings['underpaid_tolerance']) ? floatval($settings['underpaid_tolerance']) : 0;
                if ($underpaid_tolerance_percent > 0) {
                    $underpaid_tolerance_amount = $order_total * ($underpaid_tolerance_percent / 100);
                    $order_data['underpaid_tolerance'] = $this->format_as_double($underpaid_tolerance_amount);
                } else {
                    $order_data['underpaid_tolerance'] = '0.0';
                }
            }
            
            // Handle overpaid tolerance settings
            if ($accept_all_overpaid) {
                // If accept_all_overpaid is enabled, don't include accept_over_payment and overpaid_tolerance
                // API will use default value (true) for accept_over_payment
                if (isset($api->logger)) {
                    $api->logger->debug('Accept all overpaid is enabled, skipping accept_over_payment and overpaid_tolerance');
                }
            } else {
                // If accept_all_overpaid is disabled, set accept_over_payment to false and include tolerance
                $order_data['accept_over_payment'] = 'false';
                
                // Calculate overpaid tolerance amount
                $order_total = $order->get_total();
                $overpaid_tolerance_percent = isset($settings['overpaid_tolerance']) ? floatval($settings['overpaid_tolerance']) : 0;
                if ($overpaid_tolerance_percent > 0) {
                    $overpaid_tolerance_amount = $order_total * ($overpaid_tolerance_percent / 100);
                    $order_data['overpaid_tolerance'] = $this->format_as_double($overpaid_tolerance_amount);
                } else {
                    $order_data['overpaid_tolerance'] = '0.0';
                }
            }
            
            $response = $api->create_checkout($order_data);
            
            if (isset($response['data']['checkout_url'])) {
                // Save Cregis order ID and merchant order ID
                $order->update_meta_data('_cregis_order_id', $response['data']['cregis_id']);
                $order->update_meta_data('_cregis_merchant_order_id', 'wc_' . $order_id . '_' . $unique_id);
                $order->save();
                
                // Update order status to pending payment
                $order->update_status('pending', __('Awaiting cryptocurrency payment', 'cregis-payment-for-woocommerce'));
                
                // Reduce stock immediately when user clicks "Pay" button
                wc_reduce_stock_levels($order_id);
                
                return array(
                    'result' => 'success',
                    'redirect' => $response['data']['checkout_url']
                );
            } else {
                throw new Exception(__('Failed to create payment order', 'cregis-payment-for-woocommerce'));
            }
        } catch (Exception $e) {
            // Re-throw the exception so WooCommerce Blocks can display the actual error message
            throw $e;
        }
    }
    
    public function thankyou_page($order_id) {
        echo '<p>' . esc_html__('Thank you for your order. We are processing your cryptocurrency payment.', 'cregis-payment-for-woocommerce') . '</p>';
    }
    
    /**
     * Format a number as double (ensures at least one decimal place, max 6 decimal places)
     * Examples: 1 -> 1.0, 1.2 -> 1.2, 1.23456789 -> 1.234568
     */
    private function format_as_double($value) {
        $value = round(floatval($value), 6);
        $formatted = number_format($value, 6, '.', '');
        // Remove trailing zeros but keep at least one decimal place
        $formatted = rtrim($formatted, '0');
        // If it ends with a decimal point, add one zero
        if (substr($formatted, -1) === '.') {
            $formatted .= '0';
        }
        return $formatted;
    }
}
