<?php

declare(strict_types=1);

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

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

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

        parent::init();

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

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

        $animal = new Animal();

        try {
            $action = Tools::getValue('action');
            $idAnimal = Tools::getValue('id');
            $context = Context::getContext();
            $customer = $context->customer;

            if ('POST' == $_SERVER['REQUEST_METHOD'] && 'create' === $action) { // Création d'un animal
                $postData = Tools::getAllValues();

                $formData = $this->extractFormData($postData);
                $formData['id_customer'] = $customer->id;
                $animal->hydrate($formData);
                $this->validateValue($animal);
                $animal->save();

                Tools::redirect($this->context->link->getModuleLink('myvetshopclinique', 'myanimals', ['create' => true]));
            } elseif ('POST' == $_SERVER['REQUEST_METHOD'] && 'update' === $action && $idAnimal) { // Maj d'un animal
                $animal = new Animal($idAnimal);
                if ($animal->id_customer != $customer->id) {
                    Tools::redirect($this->context->link->getPageLink('my-account', true));
                }
                $postData = Tools::getAllValues();

                $animal->hydrate($this->extractFormData($postData));
                $this->validateValue($animal);

                $animal->update();

                Tools::redirect($this->context->link->getModuleLink('myvetshopclinique', 'myanimals', ['update' => true]));
            } elseif ('GET' == $_SERVER['REQUEST_METHOD'] && 'delete' === $action && $idAnimal) { // Suppression d'un animal
                $animal = new Animal($idAnimal);
                if ($animal->id_customer != $customer->id) {
                    Tools::redirect($this->context->link->getPageLink('my-account', true));
                }
                $animal->deleted = true;
                $reco = $animal->getReco();
                if ($reco) {
                    $reco = new Recommandation($reco['id_recommandation']);
                    $reco->deleted = true;
                    $reco->update();
                }

                $animal->update();

                Tools::redirect($this->context->link->getModuleLink('myvetshopclinique', 'myanimals', ['delete' => true]));
            } elseif ('GET' == $_SERVER['REQUEST_METHOD'] && $idAnimal) { // defaut
                $animal = new Animal($idAnimal);
                if ($animal->id_customer != $customer->id) {
                    Tools::redirect($this->context->link->getPageLink('my-account', true));
                }
            }

            $recos = [];
            $idReco = $animal->getIdRecoCricCroc();
            if ($idReco) {
                $recos[] = new Recommandation($idReco);
            }

            $this->context->smarty->assign('recos', $recos);
        } catch (Exception $exception) {
            $this->context->smarty->assign('error', $exception->getMessage());
        }

        $this->context->smarty->assign('animal', $animal);
        $this->context->smarty->assign(['meta_title' => 'MyVetShop - Mes animaux']);
        $this->setTemplate('my_animals_edit.tpl');
    }

    /**
     * @param array<string, string> $post
     *
     * @return array<string, string>
     */
    private function extractFormData(array $post): array
    {
        $validData = [];

        foreach ($post as $key => $value) {
            if ('nom' === $key || 'id_gender' === $key || 'date_naissance' === $key || 'espece' === $key || 'race' === $key || 'robe' === $key || 'ration' === $key) {
                $validData[$key] = $value;
            }
        }

        return $validData;
    }

    /**
     * TODO : Utiliser le système de validation de PrestaShop
     *
     * @throws Exception
     */
    private function validateValue(Animal $animal): void
    {
        $animalGenderValuesValid = [1, 2];
        if (!in_array($animal->id_gender, $animalGenderValuesValid)) {
            throw new Exception('Le genre de l\'animal est invalide.');
        }

        $animalSpeciesValuesValid = ['chien', 'chat'];
        if (!in_array($animal->espece, $animalSpeciesValuesValid)) {
            throw new Exception('L\'espèce de l\'animal est invalide.');
        }

        if ('' == $animal->nom || '' == $animal->espece) {
            throw new Exception('Les champs "Nom" et "Espèce" sont obligatoires.');
        }

        if ($animal->ration < 0) {
            throw new Exception('La valeur de la ration n\'est pas valide.');
        }

        if ($animal->date_naissance) {
            $date = DateTime::createFromFormat('Y-m-d', $animal->date_naissance);

            if (false === $date) {
                throw new Exception('Date de naissance invalide.');
            }

            $tomorrow = new DateTime('+1day');
            if ($date >= $tomorrow) {
                throw new Exception('La date de naissance ne peut être supérieure à la date d\'aujourd\'hui.');
            }

            $animal->date_naissance = $date->format('Y-m-d');
        }
    }
}
