<?php

use Myvetshop\Module\Clinique\Handler\RecommandationHandler;

class MyvetshopcliniqueMyRecoModuleFrontController extends ModuleFrontController
{
    private $handler;

    public function __construct()
    {
        parent::__construct();

        $this->handler = new RecommandationHandler($this->context->customer, $this->translator);
    }

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

        $code = Tools::getValue('code');
        $animalId = Tools::getValue('id_animal', null);

        $this->context->smarty->assign([
            'code' => $code,
        ]);

        if ($this->context->customer->isLogged()) {
            switch (Tools::getValue('action')) {
                case 'pdf':
                    $this->processPdf();
                    break;
                case 'update':
                    $this->processUpdate();
                    break;
                case 'delete':
                    $this->processDelete();
                    break;
                default:
                    if ($code && $animalId) {
                        $this->processImport();
                    }
            }

            $animals = Animal::getByCustomerId($this->context->customer->id);

            if ($code) {
                $data = $this->handler->getByCode($code);
                $animals = array_filter(
                    $animals,
                    function (Animal $animal) use ($data) {
                        return $animal->isSpecies($data['esp']);
                    }
                );
            }

            $this->context->smarty->assign([
                'recommandations' => Recommandation::getByCustomerId($this->context->customer->id),
                'animals' => $animals,
            ]);
        }

        $this->setTemplate('module:myvetshopclinique/views/templates/front/myreco/recommandations.tpl');

        // Si on est pas connecté et qu'on a un code, il faut récupérer les données de l'api et afficher la page public
        if (!$this->context->customer->isLogged() && $code) {
            try {
                $data = $this->handler->getByCode($code);
                $recommandation = new Recommandation();
                $recommandation->code_reco = $code;
                $recommandation->date_reco = $data['date'];
                $recommandation->code_clinique = $data['code'];
                $recommandation->petname = $data['petname'];
                $recommandation->espece = $data['esp'];
                $recommandation->race = $data['race'];
                $recommandation->id_gender = $data['sex'];
                $recommandation->activite = $data['act'];
                $recommandation->age = $data['age'];
                $recommandation->date_birth = $data['dob'];
                $recommandation->stade_physio = $data['stadePhysio'];
                $recommandation->pathologie = $data['patho'];
                $recommandation->poids_actuel = $data['actualw'];
                $recommandation->poids_ideal = $data['idealw'];
                $recommandation->be = $data['be'];
                $recommandation->nbr_aliment = $data['nbrAliment'];
                $recommandation->products = $data['products'];

                $this->context->smarty->assign([
                    'recommandation' => $recommandation,
                ]);

                $this->setTemplate('module:myvetshopclinique/views/templates/front/myreco/recommandation_public.tpl');
            } catch (Exception $exception) {
                $this->errors[] = $exception->getMessage();
            }
        }
    }

    public function processDelete(): void
    {
        $recommandationId = (int) Tools::getValue('id_recommandation');

        try {
            $this->handler->delete($recommandationId);
            $this->success[] = $this->trans('La recommandation a bien été supprimé !', [], 'Modules.Myvetshopclinique.Shop');
        } catch (Exception $exception) {
            $this->errors[] = $exception->getMessage();
        }

        $this->redirectWithNotifications($this->context->link->getModuleLink('myvetshopclinique', 'myreco'));
    }

    public function processUpdate(): void
    {
        $recommandationId = (int) Tools::getValue('id_recommandation');
        $recommandationProductId = (int) Tools::getValue('id_recommandation_product');
        $animalId = (int) Tools::getValue('id_animal');

        try {
            $this->handler->update($recommandationId, $animalId, $recommandationProductId);
            $this->success[] = $this->trans('La recommandation a bien été mise à jour !', [], 'Modules.Myvetshopclinique.Shop');
        } catch (Exception $exception) {
            $this->errors[] = $exception->getMessage();
        }

        $this->redirectWithNotifications($this->context->link->getModuleLink('myvetshopclinique', 'myreco'));
    }

    public function processImport(): void
    {
        $code = Tools::getValue('code', null);
        $animalId = Tools::getValue('id_animal', null);
        if ('auto' == $animalId) {
            $animalId = null;
        }
        $animalId = $animalId ? (int) $animalId : null;

        try {
            $this->handler->import($code, $animalId);

            $this->success[] = $this->trans('Le code a bien été importée !', [], 'Modules.Myvetshopclinique.Shop');
        } catch (Exception $exception) {
            $this->errors[] = $exception->getMessage();
        }

        $this->redirectWithNotifications($this->context->link->getModuleLink('myvetshopclinique', 'myreco'));
    }

    /**
     * @throws PrestaShopDatabaseException
     * @throws PrestaShopException
     */
    public function processPdf(): void
    {
        $recommandationId = Tools::getValue('id_recommandation');

        $pdf = $this->handler->getPdf((int) $recommandationId);

        if ($pdf) {
            header('Content-Type: application/pdf');
            header('Content-Disposition: inline; filename=Recommandation-' . $recommandationId . '.pdf;');

            echo $pdf;
            exit;
        }
    }
}
