<?php 
/**
 * Class OAuth
 */
class ST_Oauth{
	public $version                     = '1.0.0';
    protected static $_instance         = null;
    
	public static function instance() {
		if ( is_null( self::$_instance ) ) {
			self::$_instance = new self();
		}
		return self::$_instance;
	}

    public function __construct() {}
    /**
     * method: POST
     * status: stabled
     */
    /**
     * method: POST
     * status: stabled
     */
    public static function rest_post_request( $endpoint = "", $body = [], $token = '' ) {

        $site_url = wp_parse_url(site_url(), PHP_URL_HOST);
        $site_url = preg_replace('#^www\.(.+\.)#i', '$1', $site_url); // Remove 'www.' prefix
        $site_url = rtrim($site_url, '/'); // Remove trailing slash if present

        $rest_endpoint = ST_MAIN_ENDPOINT."/oauth".$endpoint;
        $rest_headers  = [
            'Authorization' => 'Bearer '.$token, // Example of adding an Authorization header
            'Content-Type' => 'application/json',
            'x-host'       => $site_url,
            'x-reffer'     => site_url() 
        ];
        
        // Define your custom headers
        $headers = (array) $rest_headers;

        $body = (array) $body;
        // Encode the body as JSON
        $body_json = wp_json_encode($body);
        
        // Arguments for the wp_remote_post function
        $args = array(
            'headers'     => $headers,
            'body'        => $body_json,
            'timeout'     => 15, // Adjust the timeout as needed
            'redirection' => 1,  // Number of redirects to follow
            'method'      => 'POST',
            'data_format' => 'body',
        );
        
        // Disable SSL certificate verification
        add_filter('https_ssl_verify', '__return_false');
        add_filter('https_local_ssl_verify', '__return_false');

        // Make the request
        $response = wp_remote_post($rest_endpoint, $args);

        // Check for errors
        if (is_wp_error($response)) {
            // Error occurred, handle the error
            $error_message = $response->get_error_message();
    
            // Check if it's a timeout error
            if (strpos($error_message, 'Operation timed out after') !== false) {
                
                return (object) array('error' => (object) [
                    "message"   => 'Request timed out. The server may be unreachable.',
                    "code"      => "ERR::timeout",
                    "res_type"  => 'warning',
                    "status"    => 400        
                ]);
                
            } else {

                return (object) array('error' => (object) [
                    "message"   => $error_message,
                    "code"      => "ERR::Invalid",
                    "res_type"  => 'error',
                    "status"    => 200        
                ]);
            }
        }

        // Check if the response code indicates success (2xx)
        $response_code = wp_remote_retrieve_response_code($response);
        if ($response_code >= 200 && $response_code < 300) {
            // Parse the response body
            $body = wp_remote_retrieve_body($response);
    
            // Check if the response body is empty
            if (empty($body)) {
                return (object) array('error' => (object) [
                    "message"   => 'Empty response.',
                    "code"      => "ERR::empty_response",
                    "res_type"  => 'warning',
                    "status"    => 200        
                ]);
            }
    
            // Parse the response as needed
            $parsed_response = json_decode($body, true);
    
            // Check if the parsed response is empty
            if (empty($parsed_response)) {
                return (object) array('error' => (object) [
                    "message"   => 'Invalid or empty JSON response.',
                    "code"      => "ERR::empty_response",
                    "res_type"  => 'warning',
                    "status"    => 200        
                ]);
            }
    
            // Process the response as needed
            return $parsed_response;
        } else {
            // Non-successful response code, handle accordingly
            return (object) array('error' => (object) [
                "message"   => 'Non-successful response. HTTP code :'.$response_code,
                "code"      => "ERR::invalid-response",
                "res_type"  => 'warning',
                "status"    => $response_code        
            ]);
            
        }

    }

}