<?php

namespace App\Classes\Modules\Orders\Services;

use Psr\Http\Message\ResponseInterface;

class FetchesDataFromVTPortal
{

    /** @var string|null */
    private $cookies;

    /**
     * @param string $cookies
     */
    public function setCookies(string $cookies): void
    {
        $this->cookies = $cookies;
    }

    /**
     * @return string|null
     */
    public function getCookies(): ?string
    {
        return $this->cookies;
    }


    /**
     * @param string $url
     * @param string $method
     * @param $body
     * @param string $cookie
     * @param bool $requiresAuthentication
     * @return \Psr\Http\Message\ResponseInterface
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public function clientRequest(string $url, string $method, $body, string $cookie, $requiresAuthentication = true){

        if($requiresAuthentication) {
            if(!$this->getCookies()){
                $this->remoteLogin();
            }
        }

        $client = new \GuzzleHttp\Client(
            [
                'cookies' => true,
                'headers' => [
                    'Content-Type' => 'application/json',
                    'Cookie' => $this->getCookies() ? $this->getCookies() : $cookie
                ]
            ]
        );

        $request = $client->requestAsync($method, $url, [\GuzzleHttp\RequestOptions::JSON => $body, 'timeout' => 1200]);

        return $request->wait();

    }

    /**
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    private function remoteLogin(){

        $latest_cookie = [];
        $cookieRequest = new \GuzzleHttp\Client(['cookies' => true]);

        $cookieRequest->get('http://portal.vtnation.com.my');
        foreach ($cookieRequest->getConfig('cookies')->toArray() as $key => $row) {
            $latest_cookie[] = $row['Name'] . '=' . $row['Value'];
        }

        $latest_cookie = implode(';', $latest_cookie);


        /** @var  $loginRequest */
        $loginRequest = $this->clientRequest('http://portal.vtnation.com.my/Services/DataControllerService.asmx/Login', 'POST', [
            "username" => "CIEF",
            "password" => "0122120880",
            "createPersistentCookie" => true,
        ], $latest_cookie, false);

        $this->setCookies($latest_cookie.';AppVTCC='.$this->getResponseBody($loginRequest)->AccessToken);

    }

    public function getResponseBody(ResponseInterface $request){
        return json_decode($request->getBody()->getContents())->d;
    }

}