<?php

declare(strict_types=1);

// Compatibilité PrestaShop 1.7
use Psr\Http\Message\ResponseInterface;

if (!class_exists('\GuzzleHttp\Client')) {
    require_once __DIR__ . '/../vendor/autoload.php';
}

class PhpListAPI
{
    /**
     * @var string
     */
    protected $hostname;

    /**
     * @var string
     */
    protected $username;

    /**
     * @var string
     */
    protected $password;

    /**
     * @var string|null
     */
    protected $session;

    /**
     * @var \GuzzleHttp\Client
     */
    protected $client;

    /**
     * Initialisation de la session API
     *
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    protected function initSession(): void
    {
        $response = $this->client->request(
            'POST', 'http://' . $this->hostname . '/sessions', [
                'form_params' => [
                    'login_name' => $this->username,
                    'password' => $this->password,
                ],
            ]
        );

        //get session key

        $obj = json_decode(strval($response->getBody()), true);
        $this->session = $obj['key'];
    }

    /**
     * @param string $method GET/POST/PUT/DELETE
     * @param mixed|null $data
     *
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    protected function request(string $endpoint, string $method, $data = null): ResponseInterface
    {
        if (!$this->session) {
            $this->initSession();
        }

        return $this->client->request(
            $method,
            'http://' . $this->hostname . $endpoint,
            [
                'headers' => [
                    'Authorization' => 'Basic ' . base64_encode($this->username . ':' . $this->session),
                    'Content-Type' => 'application/json',
                ],
                'json' => $data,
            ]
        );
    }

    public function __construct(string $hostname, string $username, string $password)
    {
        $this->client = new \GuzzleHttp\Client();
        $this->hostname = $hostname;
        $this->username = $username;
        $this->password = $password;
    }
}
