<?php

declare(strict_types=1);

require_once __DIR__ . '/../classes/Recommandation.php';

class CricCrocApi
{
    protected function request(string $endpoint): string
    {
        $curl = \curl_init();
        if (!$curl) {
            throw new Exception('Erreur initialisation cURL');
        }
        \curl_setopt($curl, \CURLOPT_URL, 'https://www.crokit.fr' . $endpoint);
        \curl_setopt($curl, \CURLOPT_TIMEOUT, 30);
        \curl_setopt($curl, \CURLOPT_RETURNTRANSFER, 1);

        $ret = \curl_exec($curl);

        if (\is_bool($ret)) {
            throw new Exception('Erreur requête cURL');
        }

        return $ret;
    }

    /**
     * @return array<string, bool|float|int|string|null>
     */
    public function getRecoJson(string $codeReco): array
    {
        $codeReco = \strtoupper((string) $codeReco);

        if (1 !== \preg_match('#^[A-Z0-9]{5}$#', $codeReco)) {
            throw new Exception('Code reco invalide. Il doit être composé de 5 lettres et chiffres.');
        }

        $ret = \json_decode(
            $this->request('/MVSreturn.php?secure=SMV4521bou&codeReco=' . \urlencode($codeReco)),
            true
        );

        if (\is_array($ret) && isset($ret[0])) {
            return $ret[0];
        }

        throw new Exception('Retour cric-croc invalide.');
    }

    /**
     * @param array<string, bool|float|int|string|null> $recoJson
     *
     * @throws Exception
     */
    public function parseRecoJson(array $recoJson): Recommandation
    {
        if (!$recoJson['petname']) {
            throw new Exception('La recommandation n\'est pas valide.');
        }

        $ret = new Recommandation();

        \assert(\is_string($recoJson['date']));

        $date_reco_parts = \explode('-', $recoJson['date']);

        $ret->date_reco = $date_reco_parts[2] . '-' . $date_reco_parts[1] . '-' . $date_reco_parts[0];
        $ret->code_clinique = \strval($recoJson['code']);
        $ret->petname = \strval($recoJson['petname'] ?? '');
        $ret->espece = \strtolower(\strval($recoJson['esp'] ?? '')); // chien/chat
        $ret->race = \strval($recoJson['race']); // chien croisé type robuste
        $ret->id_gender = \str_contains(\strtolower(\strval($recoJson['sex'])), 'mâle') ? 1 : 2;
        $ret->activite = \strval($recoJson['act']);
        $ret->age = \strval($recoJson['age']);
        $ret->date_birth = empty($recoJson['dob']) ? null : \strval($recoJson['dob']);
        $ret->stade_physio = \strval($recoJson['stadePhysio']);
        $ret->pathologie = \strval($recoJson['patho']);
        $ret->poids_actuel = \floatval($recoJson['actualw']);
        $ret->poids_ideal = \floatval($recoJson['idealw']);
        $ret->be = \intval($recoJson['be']);
        $ret->nbr_aliment = \intval($recoJson['nbrAliment']);
        $ret->product_id_mvs1 = \intval($recoJson['productIDmvs1'] ?? 0);
        $ret->product_id_mvs2 = empty($recoJson['productIDmvs2']) ? null : (int) ($recoJson['productIDmvs2']);
        $ret->product_id_mvs3 = empty($recoJson['productIDmvs3']) ? null : (int) ($recoJson['productIDmvs3']);
        $ret->qte_aliment1 = \intval($recoJson['qteAliment1']);
        $ret->qte_aliment2 = empty($recoJson['qteAliment2']) ? null : \intval($recoJson['qteAliment2']);
        $ret->qte_aliment3 = empty($recoJson['qteAliment3']) ? null : \intval($recoJson['qteAliment3']);
        $ret->transition12 = empty($recoJson['transition12']) ? null : \intval($recoJson['transition12']);
        $ret->transition23 = empty($recoJson['transition23']) ? null : \intval($recoJson['transition23']);

        return $ret;
    }

    public function getPdf(string $codeReco): string
    {
        return $this->request('/pdf/' . \urlencode($codeReco) . '.pdf');
    }
}
