<?php

use Soft_Tehnica\Freya_Sync_Service\Data\FSSResponse;

if (!function_exists('dd')) {
    function dd()
    {
        echo '<pre>';
        array_map(function ($x) {
            var_dump($x);
        }, func_get_args());
        die;
    }
}

function isRestRequest()
{
    return (bool)constant('REST_REQUEST');
}


function request_is_frontend_ajax()
{
    if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower(
            $_SERVER['HTTP_X_REQUESTED_WITH']
        ) == 'xmlhttprequest') {
        return true;
    } else {
        return false;
    }
}

if (!function_exists('fss_random_string')) {
    // Furat de pe StackOverflow
    // https://stackoverflow.com/questions/4356289/php-random-string-generator

    /**
     * Generates a random string, withing the given keyspace
     *
     * @param int $length
     * @param string $keyspace
     * @return string
     * @throws Exception
     */
    function fss_random_string(
        int $length = 64,
        string $keyspace = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
    ): string {
        if ($length < 1) {
            throw new \RangeException("Length must be a positive integer");
        }
        $pieces = [];
        $max = mb_strlen($keyspace, '8bit') - 1;
        for ($i = 0; $i < $length; ++$i) {
            $pieces [] = $keyspace[random_int(0, $max)];
        }
        return implode('', $pieces);
    }
}

if (!function_exists('makeHttpGet')) {
    function makeHttpGet(string $path, array $params = []): FSSResponse
    {
        $url = fsServiceUrl() . $path;

        $response = wp_remote_get($url, [
            'method' => 'GET',
            'timeout' => 45,
            'redirection' => 5,
            'httpversion' => '1.0',
            'blocking' => true,
            'sslverify' => false,
            'headers' => ['Content-Type' => 'application/json'],
        ]);

        // Request error, not 4xx or 5xx
        if (is_wp_error($response)) {
            $error_message = "Eroare la conectare la API-ul Freya Sync: " . $response->get_error_message();
            wc_add_notice(__($error_message, 'textdomain'), 'error');

            return new FSSResponse(null, $error_message, false, 500);
        }

        $code = wp_remote_retrieve_response_code($response);
        $result = wp_remote_retrieve_body($response);
        $response = json_decode($result);
        return new FSSResponse($response->payload ?? null, $response->message ?? '', $response->status, $code);
    }
}

if (!function_exists('makeHttpPost')) {
    function makeHttpPost(string $path, $data): FSSResponse
    {
        $url = fsServiceUrl() . $path;

        $body = wp_json_encode($data);

        $response = wp_remote_post($url, [
            'method' => 'POST',
            'timeout' => 45,
            'redirection' => 5,
            'httpversion' => '1.0',
            'blocking' => true,
            'sslverify' => false,
            'headers' => ['Content-Type' => 'application/json'],
            'body' => $body,
            'data_format' => 'body'
        ]);


        if (is_wp_error($response)) {
            $error_message = "Eroare la conectare la API-ul Freya Sync: " . $response->get_error_message();
            wc_add_notice(__($error_message, 'textdomain'), 'error');

            return new FSSResponse(null, $error_message, false, 500);
        }

        $code = wp_remote_retrieve_response_code($response);
        $result = wp_remote_retrieve_body($response);
        $data = json_decode($result);
        return new FSSResponse($data->payload ?? null, $data->message ?? '', $data->status ?? false, $code);
    }
}

/**
 * Returns the url for FreyaSync API
 *
 * @param bool $forAjax if the request is made using jQuery, set this to true
 * @return string
 */
function fsServiceUrl(bool $forAjax = false): string
{
    if (defined("FSS_DOCKER") && !$forAjax) {
        return 'http://fss-nginx:8000/';
    }
    $options = get_option('fs_option_settings', array());
    $url = (isset($options['fsServiceUrl'])) ? $options['fsServiceUrl'] : '';
    if ($url !== "" && !str_ends_with($url, "/")) {
        $url = $url . "/";
    }
    return $url;
}

function get_the_user_ip()
{
    if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
        //check ip from share internet
        $ip = $_SERVER['HTTP_CLIENT_IP'];
    } elseif (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        //to check ip is pass from proxy
        $ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
    } else {
        $ip = $_SERVER['REMOTE_ADDR'];
    }
    return apply_filters('wpb_get_ip', $ip);
}
