<?php

require_once __DIR__ . '/../../classes/Animal.php';
require_once __DIR__ . '/../../classes/Recommandation.php';
require_once __DIR__ . '/../../class/CricCrocApi.php';

class MyvetshopcliniqueSubmitCodeRecoModuleFrontController extends ModuleFrontController
{
    /**
     * @var bool
     */
    public $display_column_left = false;

    /**
     * @throws PrestaShopException
     */
    public function init(): void
    {
        global $smarty;

        parent::init();

        $this->context->smarty = $smarty;
    }

    /**
     * @throws PrestaShopDatabaseException
     * @throws PrestaShopException
     */
    public function initContent(): void
    {
        parent::initContent();

        $userLogged = (bool) $this->context->customer->id;

        // Vérifie la présence d'un code
        $codeReco = Tools::getValue('code', null);
        $reco = null;

        if (!$codeReco) {
            Tools::redirect((new Link())->getModuleLink('myvetshopclinique', 'myreco') . '#header');
        }

        // Récupération de la recommandation
        $api = new CricCrocApi();
        try {
            $recoJson = $api->getRecoJson($codeReco);
            $reco = $api->parseRecoJson($recoJson);
            $reco->code_reco = trim(strtoupper($codeReco));
        } catch (Exception $e) {
            $linkMyReco = ((new Link())->getModuleLink('myvetshopclinique', 'myreco', ['code' => $codeReco]) . '#header');
            Tools::redirect($linkMyReco);
        }

        if (!$reco || $userLogged) {
            $linkMyReco = ((new Link())->getModuleLink('myvetshopclinique', 'myreco', ['code' => $codeReco]) . '#header');
            Tools::redirect($linkMyReco);
        }

        $this->context->smarty->assign(['meta_title' => 'MyVetShop - Recommandation nutritionnelle vétérinaire']);
        $this->context->smarty->assign(['reco' => $reco]);
        $this->setTemplate('my_reco_public.tpl');
    }
}
