<?php

namespace App\Utility\HttpRequest;

use Illuminate\Support\Facades\Http;

class HttpAsForm
{

    private array $prepareData;
    private static string $url;
    private static array $header;
    const CONTENT_TYPE_JSON = 'application/json';

    const CONTENT_TYPE_X_WWW_FORM_URLENCODE = 'application/x-www-form-urlencoded';

    public function __construct($url){
        static::$url = $url;
    }

    private function prepareRequest($inputData){
        return $inputData;
    }

    public function post($request, $header = 'application/x-www-form-urlencoded'){

        $this->prepareData = $this->prepareRequest($request);

        if($header == self::CONTENT_TYPE_X_WWW_FORM_URLENCODE) {
            $response = Http::asForm();
        }else if($header == self::CONTENT_TYPE_JSON){
            $response = Http::asJson();
        }

        $response = $response->post(
            static::$url,
            $this->prepareData
        );

        return json_decode((string) $response->getBody(), true);
    }

    public function get($request, $header = 'application/x-www-form-urlencoded'){

        $this->prepareData = $this->prepareRequest($request);

        if($header == self::CONTENT_TYPE_X_WWW_FORM_URLENCODE) {
            $response = Http::asForm();
        }else if($header == self::CONTENT_TYPE_JSON){
            $response = Http::asJson();
        }

        $response = $response->get(
                static::$url,
                $this->prepareData
            );

        return json_decode((string) $response->getBody(), true);
    }

    public function put($request, $header = 'application/x-www-form-urlencoded'){

        $this->prepareData = $this->prepareRequest($request);

        if($header == self::CONTENT_TYPE_X_WWW_FORM_URLENCODE) {
            $response = Http::asForm();
        }else if($header == self::CONTENT_TYPE_JSON){
            $response = Http::asJson();
        }

        $response = $response->put(
            static::$url,
            $this->prepareData
        );

        return json_decode((string) $response->getBody(), true);
    }
}
