<?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 fsPluginVersion(): string
{
    return "2.10.0";
}

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('fsLog')) {
    function fsLog($log): void
    {
        if (is_array($log) || is_object($log)) {
            error_log(print_r($log, true));
        } else {
            error_log($log);
        }
    }
}

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);
    }
}

function fss_is_wp_json(): bool
{
    return strpos($_SERVER['REQUEST_URI'], '/wp-json') !== false;
}

function fss_is_wc_store_api(): bool
{
    return strpos($_SERVER['REQUEST_URI'], '/wc/store') !== false;
}

/**
 * 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-app: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 fss_get_woocommerce_major_version(): int
{
    $version = wc()->version;
    $split = explode(".", $version);
    return intval($split[0]);
}