<?php
if (!defined('ABSPATH')) exit;

class ASSI_Request {

    public static function get($url = '', $timeout = 30) {
        if (!defined('ASSI_PLUGIN_CONNECTION_TO_SERVER') || !ASSI_PLUGIN_CONNECTION_TO_SERVER) {
            return 'connection_disabled_by_admin';
        }
        $maxExecTime = 30;
        if (function_exists('ini_get')) {
            $maxTime = ini_get('max_execution_time');
            if ((int) $maxTime != 0) {
                $maxExecTime = $maxTime;
            }
        }
        if ($maxExecTime < ($timeout + 3)) {
            $timeout = ($maxExecTime - 3);
        }
    
        $wpVersion = get_bloginfo('version');
        $pluginVersion = implode('.', str_split((string) ASSI_PLUGIN_VERSION));
        $ua = sprintf(
                'AssistiniBot/1.0 (WP/%s; Plugin/%s; +https://assistini.com/en/bot-info; bot@assistini.com)',
                $wpVersion,
                $pluginVersion
        );
        $args = array(
            'method' => 'GET',
            'timeout' => (int) $timeout,
            'redirection' => '5',
            'user-agent' => $ua,
        );
        $response = wp_remote_get($url, $args);
        if (is_wp_error($response)) {
            $errorCode = $response->get_error_code();
            $errorMessage = $response->get_error_message();
            if ($errorCode == 'http_request_failed' && strpos($errorMessage, 'timed out')) {
                return 'client_timeout';
            }
            if ($errorCode == 'http_request_not_executed') {
                return 'client_blocked';
            }
            if (!function_exists('curl_init')) {
                return 'client_blocked';
            }
            return false;
        } else {
            $statusCode = wp_remote_retrieve_response_code($response);
            if ($statusCode === 401) { // empty or wrong blog access token
                return 'server_auth_failed';
            }
            if ($statusCode === 403) { // access denied (ip block)
                return 'server_blocked'; 
            }
        }
        $result = wp_remote_retrieve_body($response);
        return json_decode($result);
    }
    
    public static function post($url, $data = array(), $timeout = 30, $addUserData = true) {
        if (!defined('ASSI_PLUGIN_CONNECTION_TO_SERVER') || !ASSI_PLUGIN_CONNECTION_TO_SERVER) {
            return 'connection_disabled_by_admin';
        }
        $maxExecTime = 30;
        if (function_exists('ini_get')) {
            $maxTime = ini_get('max_execution_time');
            if ((int) $maxTime != 0) {
                $maxExecTime = $maxTime;
            }
        }
        if ($maxExecTime < ($timeout + 3)) {
            $timeout = ($maxExecTime - 3);
        }
        $wpVersion = get_bloginfo('version');
        $pluginVersion = implode('.', str_split((string) ASSI_PLUGIN_VERSION));
        $ua = sprintf(
                'AssistiniBot/1.0 (WP/%s; Plugin/%s; +https://assistini.com/en/bot-info; bot@assistini.com)',
                $wpVersion,
                $pluginVersion
        );
        if ($addUserData) {
            $data['plugin_version'] = (defined('ASSI_PLUGIN_VERSION') ? sanitize_text_field(wp_unslash(ASSI_PLUGIN_VERSION)) : '');
            $data['access_token'] = (defined('ASSI_PLUGIN_BLOG_ACCESS_TOKEN') ? sanitize_text_field(wp_unslash(ASSI_PLUGIN_BLOG_ACCESS_TOKEN)) : '');
        }
        $args = array(
            'method' => 'POST',
            'body' => $data,
            'timeout' => (int) $timeout,
            'redirection' => '5',
            'user-agent' => $ua,
        );
        $response = wp_remote_post($url, $args);
        if (is_wp_error($response)) {
            $errorCode = $response->get_error_code();
            $errorMessage = $response->get_error_message();
            if ($errorCode == 'http_request_failed' && strpos($errorMessage, 'timed out')) {
                return 'client_timeout';
            }
            if ($errorCode == 'http_request_not_executed') { // if defined WP_HTTP_BLOCK_EXTERNAL
                return 'client_blocked';
            }
            if (!function_exists('curl_init')) {
                return 'client_blocked';
            }
            return false;
        } else {
            $statusCode = wp_remote_retrieve_response_code($response);
            if ($statusCode === 401) { // empty or wrong blog access token
                return 'server_auth_failed';
            }
            if ($statusCode === 403) { // access denied (ip block)
                return 'server_blocked'; 
            }
        }
        $result = wp_remote_retrieve_body($response);
        return json_decode($result);
    }

    public static function postImage($url, $data = array(), $filePath = '', $filename = '', $mimeType = '', $timeout = 30, $addUserData = true) {
        if (!defined('ASSI_PLUGIN_CONNECTION_TO_SERVER') || !ASSI_PLUGIN_CONNECTION_TO_SERVER) {
            return 'connection_disabled_by_admin';
        }
        $maxExecTime = 30;
        if (function_exists('ini_get')) {
            $maxTime = ini_get('max_execution_time');
            if ((int) $maxTime != 0) {
                $maxExecTime = $maxTime;
            }
        }
        if ($maxExecTime < ($timeout + 3)) {
            $timeout = ($maxExecTime - 3);
        }
        $wpVersion = get_bloginfo('version');
        $pluginVersion = implode('.', str_split((string) ASSI_PLUGIN_VERSION));
        $ua = sprintf(
                'AssistiniBot/1.0 (WP/%s; Plugin/%s; +https://assistini.com/en/bot-info; bot@assistini.com)',
                $wpVersion,
                $pluginVersion
        );
        if ($addUserData) {
            $data['plugin_version'] = (defined('ASSI_PLUGIN_VERSION') ? sanitize_text_field(wp_unslash(ASSI_PLUGIN_VERSION)) : '');
            $data['access_token'] = (defined('ASSI_PLUGIN_BLOG_ACCESS_TOKEN') ? sanitize_text_field(wp_unslash(ASSI_PLUGIN_BLOG_ACCESS_TOKEN)) : '');
        }
        $boundary = wp_generate_password(24);
        $headers = [
            'Content-Type' => 'multipart/form-data; boundary=' . $boundary,
        ];
        $body = '';
        foreach ($data as $name => $value) {
            $body .= "--{$boundary}\r\n";
            $body .= "Content-Disposition: form-data; name=\"{$name}\"\r\n\r\n";
            $body .= "{$value}\r\n";
        }
        $body .= "--{$boundary}\r\n";
        $body .= "Content-Disposition: form-data; name=\"image\"; filename=\"{$filename}\"\r\n";
        $body .= "Content-Type: {$mimeType}\r\n\r\n";
        $body .= file_get_contents($filePath) . "\r\n";
        $body .= "--{$boundary}--";
        $args = array(
            'method' => 'POST',
            'body' => $body,
            'timeout' => (int) $timeout,
            'redirection' => '5',
            'user-agent' => $ua,
            'headers' => $headers
        );
        $response = wp_remote_post($url, $args);
        if (is_wp_error($response)) {
            $errorCode = $response->get_error_code();
            $errorMessage = $response->get_error_message();
            if ($errorCode == 'http_request_failed' && strpos($errorMessage, 'timed out')) {
                return 'client_timeout';
            }
            if ($errorCode == 'http_request_not_executed') { // if defined WP_HTTP_BLOCK_EXTERNAL
                return 'client_blocked';
            }
            if (!function_exists('curl_init')) {
                return 'client_blocked';
            }
            return false;
        } else {
            $statusCode = wp_remote_retrieve_response_code($response);
            if ($statusCode === 401) { // empty or wrong blog access token
                return 'server_auth_failed';
            }
            if ($statusCode === 403) { // access denied (ip block)
                return 'server_blocked'; 
            }
        }
        $result = wp_remote_retrieve_body($response);
        return json_decode($result);
    }
}