<?php

namespace Hyperpay\Gateways\Helpers;

if (! defined('ABSPATH')) exit;

use WP_Error;
use Hyperpay\Gateways\Helpers\Log;

final class Http
{

    public static function post($url, $data = [])
    {
        $response = wp_remote_post($url, \array_merge($data, ['timeout' => 10000])); // 10 seconds timeout
        return self::handelResponse($response);
    }

    public static function get($url, $options = [])
    {
        $response = wp_remote_get($url, \array_merge($options, ['timeout' => 10000])); // 10 seconds timeout
        return self::handelResponse($response);
    }

    public static function delete($url, $data = [])
    {
        $options = \array_merge($data, [
            'method' => 'DELETE',
            'timeout' => 10000
        ]);

        $response = wp_remote_request($url, $options);
        return self::handelResponse($response);
    }

    public static function handelResponse($response)
    {
        $result =  json_decode(wp_remote_retrieve_body($response), true);

        if (is_wp_error($response)) {
            $error = $response->get_error_message();
            Log::write(["error" => $error, "response" => $result]);

            return [
                "result" => [
                    "code" => wp_remote_retrieve_response_code($response),
                    "description" => $error
                ]
            ];
        }

        return $result;
    }
}
