<?php

use GuzzleHttp\Client;

class PpsApiController
{
    const BASE_URL_API = 'https://pps-dev.myvetshop.fr';
    const LOGIN_TOKEN_API = 'HDdH{#bc{jID41;ugdvJOFIekdZOdbhc+f*t//M,xqJI^zhJ+:}f';

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

    /**
     * PpsApiController constructor.
     */
    public function __construct()
    {
        $this->client = $client = new GuzzleHttp\Client();
    }

    /**
     * @param $email
     *
     * @return array|mixed
     *
     * @throws PpsBadRequestException
     * @throws PpsNotFoundException
     * @throws PpsUnauthorizedException
     */
    public function getContractsByCustomersEmail($email)
    {
        $url = self::BASE_URL_API . '/api/customers/' . $email . '/contracts';

        return $this->get($url);
    }

    /**
     * @param $email
     * @param $idContract
     *
     * @return array|mixed
     *
     * @throws PpsBadRequestException
     * @throws PpsNotFoundException
     * @throws PpsUnauthorizedException
     */
    public function getActsByContractId($email, $idContract)
    {
        $url = self::BASE_URL_API . '/api/customers/' . $email . '/contracts/' . $idContract . '/acts';

        return $this->get($url);
    }

    /**
     * @param $url
     *
     * @return array|mixed
     *
     * @throws PpsBadRequestException
     * @throws PpsNotFoundException
     * @throws PpsUnauthorizedException
     */
    protected function get($url)
    {
        try {
            $res = $this->client->get(
                $url, [
                    'headers' => ['X-AUTH-TOKEN' => self::LOGIN_TOKEN_API],
                ]
            );

            return json_decode($res->getBody()->getContents(), true);
        } catch (Exception $exception) {
            if ($exception->hasResponse()) {
                $response = $exception->getResponse();
                $statusCode = $response->getStatusCode();

                if ($statusCode) {
                    switch ($statusCode) {
                        case 400:
                            throw new PpsBadRequestException();
                            break;
                        case 401:
                            throw new PpsUnauthorizedException();
                            break;
                        case 404:
                            throw new PpsNotFoundException();
                            break;
                    }
                }
            }

            throw $exception;
        }
    }
}
