<?php

namespace Myvetshop\Module\Clinique\Api;

use Exception;

class CricCrocApi
{
    private $host = 'https://www.crokit.fr';

    public function getRecommandationByCode(string $code): array
    {
        $code = strtoupper($code);

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

        $path = '/MVSreturn.php?secure=SMV4521bou&codeReco=' . urlencode($code);
        $data = $this->request($path);

        $data = json_decode($data, true);

        if (is_array($data) && isset($data[0])) {
            $recommandation = $data[0];

            //Si il n'y a pas de code, c'est que la recommandation n'existe pas / plus.
            if (is_null($recommandation['code'])) {
                throw new Exception("Cette recommandation n'est plus disponible.");
            }

            $recommandation['date'] = \DateTime::createFromFormat('d-m-Y', $recommandation['date'])->format('Y-m-d');
            $recommandation['esp'] = strtolower($recommandation['esp']);
            $recommandation['sex'] = false !== strpos(strtolower($recommandation['sex']), 'mâle') ? 1 : 2;
            $recommandation['dob'] = !empty($recommandation['dob']) ? \DateTime::createFromFormat('d-m-Y', $recommandation['dob'])->format('Y-m-d') : null;
            $recommandation['productIDmvs1'] = !empty($recommandation['productIDmvs1']) ? (int) $recommandation['productIDmvs1'] : null;
            $recommandation['productIDmvs2'] = !empty($recommandation['productIDmvs2']) ? (int) $recommandation['productIDmvs2'] : null;
            $recommandation['productIDmvs3'] = !empty($recommandation['productIDmvs3']) ? (int) $recommandation['productIDmvs3'] : null;
            $recommandation['qteAliment1'] = !empty($recommandation['qteAliment1']) ? (int) $recommandation['qteAliment1'] : null;
            $recommandation['qteAliment2'] = !empty($recommandation['qteAliment2']) ? (int) $recommandation['qteAliment2'] : null;
            $recommandation['qteAliment3'] = !empty($recommandation['qteAliment3']) ? (int) $recommandation['qteAliment3'] : null;
            $recommandation['transition12'] = !empty($recommandation['transition12']) ? (int) $recommandation['transition12'] : null;
            $recommandation['transition23'] = !empty($recommandation['transition23']) ? (int) $recommandation['transition23'] : null;

            return $recommandation;
        }

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

    public function parseRecoJson(array $recoJson): Recommandation
    {
        if (!$recoJson['petname']) {
            throw new Exception('La recommandation n\'est pas valide.');
        }

        $ret = new Recommandation();

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

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

        return $ret;
    }

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

    protected function request(string $endpoint): string
    {
        $curl = curl_init();
        if (!$curl) {
            throw new Exception('Erreur initialisation cURL');
        }
        curl_setopt($curl, CURLOPT_URL, $this->host . $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;
    }
}
