<?php

use Myvetshop\Module\Clinique\Handler\RecommandationHandler;

class MyvetshopcliniqueMyRecoModuleFrontController extends ModuleFrontController
{
    private RecommandationHandler $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);

        if (!\is_string($code)) {
            $code = '';
        }

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

        if ($this->context->customer->isLogged()) {
            $action = \Tools::getValue('action');
            if (!\is_string($action)) {
                $action = 'nothing';
            }

            switch ($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 n'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 = \Tools::getValue('id_recommandation');

        if (\is_string($recommandationId) || \is_int($recommandationId)) {
            $recommandationId = \intval($recommandationId);
        } else {
            $recommandationId = 0;
        }

        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 = \Tools::getValue('id_recommandation');
        if (\is_string($recommandationId) || \is_int($recommandationId)) {
            $recommandationId = \intval($recommandationId);
        } else {
            $recommandationId = 0;
        }

        $recommandationProductId = \Tools::getValue('id_recommandation_product');
        if (\is_string($recommandationProductId) || \is_int($recommandationProductId)) {
            $recommandationProductId = \intval($recommandationProductId);
        } else {
            $recommandationProductId = 0;
        }

        $animalId = \Tools::getValue('id_animal');
        if (\is_string($animalId) || \is_int($animalId)) {
            $animalId = \intval($animalId);
        } else {
            $animalId = 0;
        }

        if (
            !$recommandationId
            || !$recommandationProductId
            || !$animalId
        ) {
            $this->redirectWithNotifications($this->context->link->getModuleLink('myvetshopclinique', 'myreco'));
        }

        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);
        if (!\is_string($code)) {
            $code = '';
        }
        $animalId = \Tools::getValue('id_animal', null);
        if ('auto' == $animalId) {
            $animalId = null;
        } elseif (\is_string($animalId) || \is_int($animalId)) {
            $animalId = \intval($animalId);
        } else {
            $animalId = null;
        }
        $animalId = $animalId ? \intval($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');
        if (\is_string($recommandationId) || \is_int($recommandationId)) {
            $recommandationId = \intval($recommandationId);
        } else {
            $recommandationId = null;
        }

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

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

            echo $pdf;
            exit;
        }
    }
}
