<?php
/*####################################################################
 # Copyright ©2020 UseePay Ltd. All Rights Reserved.                 #
 # This file may not be redistributed in whole or significant part.  #
 # This file is part of the UseePay package and should not be used   #
 # and distributed for any other purpose that is not approved by     #
 # UseePay Ltd.                                                      #
 # https://www.useepay.com                                           #
 ####################################################################*/

class WC_UseePay_Inner_API
{
    const SANDBOX_ENDPOINT = 'https://pay-gateway1.uat.useepay.com/api';
    const LIVE_ENDPOINT    = 'https://pay-gateway.useepay.com/api';


    /**
     * @param $parameters
     * @throws WC_UseePay_Inner_Exception
     */
    public static function request($parameters)
    {
        $options            = get_option('woocommerce_' . WC_Gateway_UseePay_CreditCard::ID . '_settings');
        $sandbox_mode       = isset($options["testMode"]) && 'yes' === $options["testMode"];
        $endpoint           = $sandbox_mode ? self::SANDBOX_ENDPOINT : self::LIVE_ENDPOINT;
        $parameters['sign'] = Wc_UseePay_Inner_Util::generate_signature($parameters, $options["useepay_key"]);
        // SSL验证设置：沙箱模式可以关闭SSL验证，生产环境必须启用
        $ssl_verify = !$sandbox_mode;

        WC_UseePay_Inner_Logger::log('[API] ' . $endpoint . ' | SSL=' . ($ssl_verify ? 'on' : 'off'));
        WC_UseePay_Inner_Logger::log('[API] Request parameters: ' . var_export($parameters, true));
        
        $request_args = array(
            'timeout'   => 45,
            'blocking'  => true,
            'sslverify' => $ssl_verify,
            'body'      => $parameters,
            'headers'   => array(
                'User-Agent' => 'WooCommerce-UseePay/1.0.4',
                'Content-Type' => 'application/x-www-form-urlencoded'
            ),
            'httpversion' => '1.1'
        );
        
        $response = wp_remote_post($endpoint, $request_args);
        if (is_wp_error($response)) {
            $error_message = $response->get_error_message();
            WC_UseePay_Inner_Logger::log("WP Error: " . $error_message);
            throw new WC_UseePay_Inner_Exception($error_message, 'Network error: ' . $error_message);
        }
        
        if (empty($response['body'])) {
            WC_UseePay_Inner_Logger::log("Empty response body: " . var_export($response, true));
            throw new WC_UseePay_Inner_Exception('Empty response from server', 'Server returned empty response');
        }
        
        if (wp_remote_retrieve_response_code($response) !== 200) {
            $response_code = wp_remote_retrieve_response_code($response);
            $response_message = wp_remote_retrieve_response_message($response);
            WC_UseePay_Inner_Logger::log("HTTP Error: " . $response_code . ' ' . $response_message);
            throw new WC_UseePay_Inner_Exception("HTTP {$response_code}: {$response_message}", 'HTTP request failed');
        }
        $final_response = stripslashes_deep(json_decode($response['body'], true));
        WC_UseePay_Inner_Logger::log("response body: " . var_export($final_response, true));
        if (Wc_UseePay_Inner_Util::verify_signature($final_response, $options["useepay_key"])) {
            WC_UseePay_Inner_Logger::log("response signature matched");
            return $final_response;
        } else {
            WC_UseePay_Inner_Logger::log("response signature not matched!!!");
            throw new WC_UseePay_Inner_Exception('Signature not match!', 'Signature verification failed');
        }
    }
}
