<?php

/**
 * Created by Aurélien RICHAUD (03/01/2017 17:26)
 */
if (!defined('_PS_VERSION_')) {
    exit;
}

require_once __DIR__ . DIRECTORY_SEPARATOR . 'class' . DIRECTORY_SEPARATOR . 'NotificationManager.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'classes' . DIRECTORY_SEPARATOR . 'Clinique.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'classes' . DIRECTORY_SEPARATOR . 'CliniquePush.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . 'class' . DIRECTORY_SEPARATOR . 'LimitedNumberOfProductByOrder.php';

class MyVetshopClinique extends Module
{
    /**
     * @var string
     */
    public $confirmUninstall;

    protected function getOrCreateMyVetshopTab(): int
    {
        $idTabMyVetshop = Tab::getIdFromClassName('AdminMyVetshop');

        if (!$idTabMyVetshop) {
            $tab = new Tab();
            $tab->active = true;
            $languages = Language::getLanguages(false);
            if (is_array($languages)) {
                foreach ($languages as $language) {
                    $tab->name[$language['id_lang']] = 'MyVetshop';
                }
            }
            $tab->class_name = 'AdminMyVetshop';
            $tab->id_parent = 0;

            // Création de l'onglet dans la base de données
            $tab->add();

            $idTabMyVetshop = $tab->id;
        }

        return $idTabMyVetshop;
    }

    protected function createController(): void
    {
        $db = Db::getInstance();

        /////////////////////////////////////////
        /// Tab : Cliniques
        $tab = new Tab();
        $tab->active = true;
        $languages = Language::getLanguages(false);
        if (is_array($languages)) {
            foreach ($languages as $language) {
                $tab->name[$language['id_lang']] = 'Cliniques';
            }
        }
        $tab->class_name = 'AdminMyVetShopClinique';
        $tab->module = $this->name;
        $tab->id_parent = $this->getOrCreateMyVetshopTab();
        $tab->add();
        $db->execute('DELETE FROM `' . _DB_PREFIX_ . 'access` WHERE `id_tab` = ' . (int) $tab->id . ' AND `id_profile` = 5');
        $db->execute('INSERT INTO `' . _DB_PREFIX_ . 'access` (`id_profile`, `id_tab`, `view`, `add`, `edit`, `delete`) VALUES (5, ' . (int) $tab->id . ', 1, 0, 0, 0)');

        /////////////////////////////////////////
        /// Tab : Vacances
        $tab = new Tab();
        $tab->active = true;
        $languages = Language::getLanguages(false);
        if (is_array($languages)) {
            foreach ($languages as $language) {
                $tab->name[$language['id_lang']] = 'Vacances';
            }
        }
        $tab->class_name = 'AdminMyVetShopCliniqueHolidays';
        $tab->module = $this->name;
        $tab->id_parent = $this->getOrCreateMyVetshopTab();
        $tab->add();

        /////////////////////////////////////////
        /// Tab : Statistiques
        $tab = new Tab();
        $tab->active = true;
        $languages = Language::getLanguages(false);
        if (is_array($languages)) {
            foreach ($languages as $language) {
                $tab->name[$language['id_lang']] = 'Statistiques';
            }
        }
        $tab->class_name = 'AdminMyVetShopCliniqueStatistiques';
        $tab->module = $this->name;
        $tab->id_parent = $this->getOrCreateMyVetshopTab();
        $tab->add();

        /////////////////////////////////////////
        /// Tab : Exports comptables
        $tab = new Tab();
        $tab->active = true;
        $languages = Language::getLanguages(false);
        if (is_array($languages)) {
            foreach ($languages as $language) {
                $tab->name[$language['id_lang']] = 'Exports Comptables';
            }
        }
        $tab->class_name = 'AdminMyVetShopExportComptable';
        $tab->module = $this->name;
        $tab->id_parent = $this->getOrCreateMyVetshopTab();
        $tab->add();

        /////////////////////////////////////////
        /// Tab : SSO (Authorization)
        $tab = new Tab();
        $tab->active = true;
        $languages = Language::getLanguages(false);
        if (is_array($languages)) {
            foreach ($languages as $language) {
                $tab->name[$language['id_lang']] = 'SSO';
            }
        }
        $tab->class_name = 'AdminMyVetShopCliniqueSSOAuthorization';
        $tab->module = $this->name;
        $tab->id_parent = -1;
        $tab->add();

        /////////////////////////////////////////
        /// Tab : SSO (Token)
        $tab = new Tab();
        $tab->active = true;
        $languages = Language::getLanguages(false);
        if (is_array($languages)) {
            foreach ($languages as $language) {
                $tab->name[$language['id_lang']] = 'SSO';
            }
        }
        $tab->class_name = 'AdminMyVetShopCliniqueSSOToken';
        $tab->module = $this->name;
        $tab->id_parent = -1;
        $tab->add();

        /////////////////////////////////////////
        /// Tab : SSO (Self)
        $tab = new Tab();
        $tab->active = true;
        $languages = Language::getLanguages(false);
        if (is_array($languages)) {
            foreach ($languages as $language) {
                $tab->name[$language['id_lang']] = 'SSO';
            }
        }
        $tab->class_name = 'AdminMyVetShopCliniqueSSOSelf';
        $tab->module = $this->name;
        $tab->id_parent = -1;
        $tab->add();

        /////////////////////////////////////////
        /// Tab : SSO (DisplayToken (pour les app mobiles))
        $tab = new Tab();
        $tab->active = true;
        $languages = Language::getLanguages(false);
        if (is_array($languages)) {
            foreach ($languages as $language) {
                $tab->name[$language['id_lang']] = 'SSO App Token';
            }
        }
        $tab->class_name = 'AdminMyVetShopCliniqueSSOAppToken';
        $tab->module = $this->name;
        $tab->id_parent = -1;
        $tab->add();

        /////////////////////////////////////////
        /// Tab : Maintenance des applications
        $tab = new Tab();
        $tab->active = 1;
        $languages = Language::getLanguages(false);
        if (is_array($languages)) {
            foreach ($languages as $language) {
                $tab->name[$language['id_lang']] = 'Maintenance de l\'application vetzen';
            }
        }
        $tab->class_name = 'AdminMyVetShopAppVetzenMaintenance';
        $tab->module = $this->name;
        $tab->id_parent = $this->getOrCreateMyVetshopTab();
        $tab->add();
    }

    /**
     * @throws PrestaShopDatabaseException
     * @throws PrestaShopException
     */
    protected function removeController(): bool
    {
        while ($tab_id = (int) Tab::getIdFromClassName('AdminMyVetShopClinique')) {
            $tab = new Tab($tab_id);
            $tab->delete();
        }

        while ($tab_id = (int) Tab::getIdFromClassName('AdminMyVetShopCliniqueHolidays')) {
            $tab = new Tab($tab_id);
            $tab->delete();
        }

        while ($tab_id = (int) Tab::getIdFromClassName('AdminMyVetShopExportComptable')) {
            $tab = new Tab($tab_id);
            $tab->delete();
        }

        while ($tab_id = (int) Tab::getIdFromClassName('AdminMyVetShopCliniqueSSOAuthorization')) {
            $tab = new Tab($tab_id);
            $tab->delete();
        }

        while ($tab_id = (int) Tab::getIdFromClassName('AdminMyVetShopCliniqueSSOToken')) {
            $tab = new Tab($tab_id);
            $tab->delete();
        }

        while ($tab_id = (int) Tab::getIdFromClassName('AdminMyVetShopCliniqueSSOSelf')) {
            $tab = new Tab($tab_id);
            $tab->delete();
        }

        while ($tab_id = (int) Tab::getIdFromClassName('AdminMyVetShopCliniqueSSOAppToken')) {
            $tab = new Tab($tab_id);
            $tab->delete();
        }

        while ($tab_id = (int) Tab::getIdFromClassName('AdminMyVetShopCliniqueStatistiques')) {
            $tab = new Tab($tab_id);
            $tab->delete();
        }

        while ($tab_id = (int) Tab::getIdFromClassName('AdminMyVetShopAppVetzenMaintenance')) {
            $tab = new Tab($tab_id);
            $tab->delete();
        }

        return true;
    }

    public function __construct()
    {
        $this->name = 'myvetshopclinique';
        $this->tab = 'administration';
        $this->version = '3.11.3';
        $this->author = 'BtoWeb.fr';
        $this->need_instance = 0;
        $this->ps_versions_compliancy = ['min' => '1.6', 'max' => '1.7'];
        $this->dependencies = [];

        parent::__construct();

        $this->displayName = $this->l('MyVetshop cliniques');
        $this->description = $this->l('Gestion des cliniques / groupes de clients / Livreurs');

        $this->confirmUninstall = $this->l('Confirmer la désinstallation du plugin ?');
    }

    /**
     * @throws PrestaShopException
     */
    public function install(): bool
    {
        if (false == parent::install()) {
            return false;
        }

        // Ajout des colonnes pour la classe employee
        $db = Db::getInstance();

        /////////////////////////////////////////
        // Création d'une table spécifique
        $db->execute(
            'CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'myvetshop_clinique` (
			  `id_myvetshop_clinique` INT(11) NOT NULL AUTO_INCREMENT,
			  `id_employee` INT(11) DEFAULT NULL,
			  `id_carrier` INT(11) DEFAULT NULL,
			  `id_carrier_home` INT(11) DEFAULT NULL,
			  `id_group` INT(11) DEFAULT NULL,
			  `id_store` INT(11) DEFAULT NULL,
			  `code_privilege` VARCHAR(10) NOT NULL,
			  `centrale` VARCHAR(10) NOT NULL,
			  `id_warehouse` INT(11) NOT NULL,
			  `code_client` VARCHAR(10) DEFAULT NULL,
			  `mdp` VARCHAR(10) DEFAULT NULL,
			  `code_filiere` VARCHAR(10) DEFAULT NULL,
			  `theme` VARCHAR(10) DEFAULT NULL,
			  `masquer_logo` INT(1) DEFAULT 0,
			  `email_original` VARCHAR(150) DEFAULT NULL,
			  `jours_livraison` VARCHAR(55) DEFAULT NULL,
			  `don` bool DEFAULT TRUE,
			  
			   PRIMARY KEY (`id_myvetshop_clinique`),
			   UNIQUE (id_employee),
			   UNIQUE (id_carrier),
			   UNIQUE (id_group),
			   UNIQUE (id_store),
			   UNIQUE (code_privilege)
			);'
        );

        // Création de la colonne don si elle n'existe pas dans la table
        $columnDonCreate = $db->execute('ALTER TABLE `' . _DB_PREFIX_ . 'myvetshop_clinique` ADD COLUMN IF NOT EXISTS `don` bool DEFAULT TRUE');
        if (!$columnDonCreate) {
            return false;
        }

        // Table des vacances
        $db->execute(
            'CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'myvetshop_clinique_holidays` (
              `id_myvetshop_clinique_holidays`  INT(11) NOT NULL AUTO_INCREMENT,
			  `id_myvetshop_clinique` INT(11) NOT NULL,
			  `date_alerte` DATE NULL,
			  `date_debut` DATE NOT NULL,
			  `date_fin` DATE NOT NULL,
			  `message_alerte` TEXT NULL,
			  `message` TEXT NOT NULL,
			  
			   PRIMARY KEY (id_myvetshop_clinique_holidays)
			);'
        );

        /////////////////////////////////////////
        /// Augmente l'espace disponible pour les horaires
        $db->execute('ALTER TABLE `' . _DB_PREFIX_ . 'store` CHANGE `hours` `hours` VARCHAR(1024) CHARACTER SET utf8 COLLATE utf8_unicode_ci NULL DEFAULT NULL');

        /////////////////////////////////////////
        // Tables OAuth
        $db->execute(
            'CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'oauth_client` (
			  `id_oauth_client` INT(11) NOT NULL AUTO_INCREMENT,
			  `name` VARCHAR(50) NOT NULL,
			  `random_id` VARCHAR(50) NOT NULL,
			  `secret` VARCHAR(50) NOT NULL,
			  `redirect_uris` VARCHAR(512) NOT NULL,
			  `allowed_grant_types` VARCHAR(512) NOT NULL,
			  
			   PRIMARY KEY (`id_oauth_client`),
			   KEY (random_id)
			);'
        );
        $db->execute(
            'CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'oauth_auth_code` (
			  `id_oauth_auth_code` INT(11) NOT NULL AUTO_INCREMENT,
			  `client_id` INT(11) NOT NULL,
			  `id_employee` INT(11) NOT NULL,
			  `redirect_uri` VARCHAR(50) NOT NULL,
			  `token` VARCHAR(50)  NOT NULL,
			  `created` INT(11) NOT NULL,
			  `expires` INT(11) NOT NULL,
			  
			   PRIMARY KEY (`id_oauth_auth_code`),
			   KEY (token)
			);'
        );
        $db->execute(
            'CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'oauth_access_token` (
			  `id_oauth_access_token` INT(11) NOT NULL AUTO_INCREMENT,
			  `client_id` INT(11) NOT NULL,
			  `id_employee` INT(11) NOT NULL,
			  `token` VARCHAR(50)  NOT NULL,
			  `created` INT(11) NOT NULL,
			  `expires` INT(11) NOT NULL,
			  
			   PRIMARY KEY (`id_oauth_access_token`),
			   KEY (token)
			);'
        );

        /////////////////////////////////////////
        // Création de la table pour les exports générés depuis l'app veto
        $db->execute(
            'CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'myvetshop_export_product` (
			  `id_export_product` INT(11) NOT NULL AUTO_INCREMENT,
			  `id_myvetshop_clinique` INT(11) NOT NULL,
			  `name` VARCHAR(50) NOT NULL,
			  `date_start` DATE NOT NULL,
			  `date_end` DATE NOT NULL,
			  `products` TEXT  NOT NULL,
			  `date_add` DATE NOT NULL,
			  `date_upd` DATE NOT NULL,
			  `deleted` BOOL NOT NULL DEFAULT FALSE,
		
			   PRIMARY KEY (`id_export_product`)
			);'
        );

        /////////////////////////////////////////
        // Table des recommandations
        $db->execute(
            'CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . 'recommandation` (
			  `id_recommandation` INT(11) NOT NULL AUTO_INCREMENT,
			  `id_customer` INT(11) NOT NULL,
              `id_animal` INT(11) NULL,
              `code_reco` VARCHAR(6) NULL,
              `date_reco` DATETIME NOT NULL,
              `code_clinique` INT(6) NULL,
              `petname` VARCHAR(50) NOT NULL,
              `espece` VARCHAR(50) NOT NULL,
              `race` VARCHAR(50) NOT NULL,
              `id_gender` INT(11) NOT NULL,
              `activite` VARCHAR(60) NOT NULL,
              `age` VARCHAR(60) NOT NULL,
              `date_birth` VARCHAR(50) NULL,
              `pathologie` VARCHAR(60) NULL,
              `stade_physio` VARCHAR(60) NOT NULL,
              `poids_actuel` DECIMAL(20,2) NOT NULL,
              `poids_ideal` DECIMAL(20,2) NOT NULL,
              `be` INT(11) NULL,
              `nbr_aliment` INT(11) NOT NULL,
              `product_id_mvs1` INT(11) NOT NULL,
              `product_id_mvs2` INT(11) NULL,
              `product_id_mvs3` INT(11) NULL,
              `qte_aliment1` INT(11) NOT NULL,
              `qte_aliment2` INT(11) NULL,
              `qte_aliment3` INT(11) NULL,
              `transition12` INT(11) NULL,
              `transition23` INT(11) NULL,
              `date_add` DATETIME NOT NULL,
              `date_upd` DATETIME NOT NULL,
              `deleted` TINYINT(1) NOT NULL,
			   PRIMARY KEY (`id_recommandation`),
			   KEY (`id_customer`)
			);'
        );

        /////////////////////////////////////////
        // Table des recommandations
        $db->execute(
            'CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . BuyLimitedNumberOfProducts::TABLE . '` (
			  `id_product` INT(11) NOT NULL,
              `max_quantity` INT(11) NOT NULL,
    
			   PRIMARY KEY (`id_product`)
			);'
        );

        /////////////////////////////////////////
        // Création de la table pour notifications app véto
        $db->execute(
            'CREATE TABLE IF NOT EXISTS `' . _DB_PREFIX_ . CliniquePush::TABLE . '` (
			  `id_clinique_push` INT(11) NOT NULL AUTO_INCREMENT,
			  `push_id` VARCHAR(255) NOT NULL,
			  `push_type` VARCHAR(10) NOT NULL,
			  `id_oauth_access_token` INT(11),
			  `date_add` DATE NOT NULL,
			  `date_upd` DATE NOT NULL,

			   PRIMARY KEY (`id_clinique_push`)
			);'
        );

        $this->registerHook('actionObjectCustomerAddAfter');
        $this->registerHook('actionObjectCustomerUpdateAfter');
        $this->registerHook('actionCustomerUpdate');
        $this->registerHook('actionCustomerAccountAdd');
        $this->registerHook('actionCustomerAccountUpdate');
        $this->registerHook('actionOrderStatusUpdate');
        $this->registerHook('customerAccount');
        $this->registerHook('hideOrShowStatMenu');
        $this->registerHook('myvetshopHoliday');
        $this->registerHook('myvetshopMessageClinique');
        $this->registerHook('actionAdminControllerSetMedia');
        $this->registerHook('actionGetExtraMailTemplateVars');
        $this->registerHook('displayHeader');
        $this->registerHook('actionBeforeCartUpdateQty');
        $this->registerHook('displayAddRecoLink');

        // URL personnalisée
        $metaRaw = Meta::getMetaByPage('module-myvetshopclinique-submitcodereco', 1);
        if (!$metaRaw) {
            $meta = new Meta();
            $meta->page = 'module-myvetshopclinique-submitcodereco';
            $meta->configurable = 1;
            $meta->save();
        } else {
            $meta = new Meta($metaRaw['id_meta']);
        }

        Db::getInstance()
            ->execute('INSERT INTO `' . _DB_PREFIX_ . 'meta_lang`'
                . ' (`id_meta`, `id_shop`, `id_lang`, `title`, `description`, `url_rewrite`)'
                . ' VALUES (' . (int) $meta->id . ', 1, 1, "Mes recommandations", "Mes recommandations", "reco")'
                . ' ON DUPLICATE KEY UPDATE `url_rewrite` = "reco"');

        /////////////////////////////////////////
        /// Création du Controller
        $this->createController();

        return true;
    }

    /**
     * @throws PrestaShopDatabaseException
     * @throws PrestaShopException
     */
    public function uninstall(): bool
    {
        /////////////////////////////////////////
        /// Suppression du Controller
        $this->removeController();

        return parent::uninstall();
    }

    /**
     * @param array<string, mixed> $params
     */
    public function hookActionObjectCustomerAddAfter(array $params): void
    {
        /** @var Customer $object */
        $object = $params['object'];

        $this->syncCustomerWithPhpList($object);
    }

    /**
     * @param array<string, mixed> $params
     */
    public function hookActionObjectCustomerUpdateAfter(array $params): void
    {
        /** @var Customer $object */
        $object = $params['object'];

        $this->syncCustomerWithPhpList($object);
    }

    /**
     * @param array<string, mixed> $params
     *
     * @throws PrestaShopDatabaseException
     * @throws PrestaShopException
     */
    public function hookActionCustomerAccountAdd(array $params): void
    {
        /** @var Customer $customer */
        $customer = $params['newCustomer'];
        $codePrivilege = Tools::getValue('code_privilege');

        if ($codePrivilege && !in_array(strtoupper($codePrivilege), ['AAA111', 'VET123'])) {
            $resultat = Db::getInstance()->executeS(
                'SELECT g.id_group
                FROM `' . _DB_PREFIX_ . 'group_lang` gl
                LEFT JOIN `' . _DB_PREFIX_ . 'group` g ON gl.id_group = g.id_group
                WHERE g.id_group > 3
			        AND gl.name LIKE "' . Db::getInstance()->escape($codePrivilege) . '"
                    AND gl.name NOT IN ("AAA111", "VET123")'
            );

            if (is_array($resultat) && count($resultat) && isset($resultat[0]['id_group'])) {
                // On ajoute l'utilisateur au groupe
                $customer->updateGroup([3, $resultat[0]['id_group']]);

                // Change le groupe par défaut
                $customer->id_default_group = $resultat[0]['id_group'];
                $customer->save();
            }
        }
    }

    /**
     * @param array<string, mixed> $params
     *
     * @throws PrestaShopDatabaseException
     * @throws PrestaShopException
     */
    public function hookActionCustomerAccountUpdate(array $params): void
    {
        /** @var Customer $customer */
        $customer = $params['customer'];
        $codePrivilege = Tools::getValue('code_privilege');

        if ($codePrivilege && !in_array(strtoupper($codePrivilege), ['AAA111', 'VET123'])) {
            $resultat = Db::getInstance()->executeS(
                'SELECT g.id_group
                FROM `' . _DB_PREFIX_ . 'group_lang` gl
                LEFT JOIN `' . _DB_PREFIX_ . 'group` g ON gl.id_group = g.id_group
                WHERE g.id_group > 3
			        AND gl.name LIKE "' . Db::getInstance()->escape($codePrivilege) . '"
			        AND gl.name NOT IN ("AAA111", "VET123")'
            );

            if (is_array($resultat) && count($resultat) && isset($resultat[0]['id_group'])) {
                // On ajoute l'utilisateur au groupe
                $customer->updateGroup([3, $resultat[0]['id_group']]);

                // Change le groupe par défaut
                $customer->id_default_group = $resultat[0]['id_group'];
                $customer->save();
            }
        }
    }

    /**
     * @param array<string, mixed> $params
     *
     * @throws PrestaShopDatabaseException
     * @throws PrestaShopException
     */
    public function hookActionOrderStatusUpdate(array $params): void
    {
        /** @var OrderState $newOrderStatus */
        $newOrderStatus = $params['newOrderStatus'];
        $order = new Order($params['id_order']);

        try {
            $notificationManager = new NotificationManager();

            $result = Db::getInstance()
                ->executeS('SELECT * FROM `ps_customer_push` WHERE `id_customer` = ' . (int) $order->id_customer);

            if (!is_array($result)) {
                $result = [];
            }

            /** @var CustomerPush[] $customerPushes */
            $customerPushes = ObjectModel::hydrateCollection(
                CustomerPush::class, $result
            );

            $message = null;
            switch ($newOrderStatus->template) {
                case 'preparation':
                    $message = 'Votre commande ' . $order->reference . ' est en cours de préparation';
                    break;

                case 'shipped':
                    $message = 'Votre commande ' . $order->reference . ' est expédiée';
                    break;

                case 'order_clinique':
                    $message = 'Votre commande ' . $order->reference . " est disponible à la clinique. Merci de suivre les mesures de distanciation sociale qui s'imposent.";
                    break;

                default:
                    // Rien
            }

            if ($message) {
                $nb_telephones_destination = 0;

                foreach ($customerPushes as $customerPush) {
                    try {
                        $notificationManager->sendNotification($customerPush, $message);
                        ++$nb_telephones_destination;
                    } catch (\GuzzleHttp\Exception\GuzzleException $e) {
                        // Inhibiteur d'erreur
                        //var_dump($e);
                    } catch (Exception $exception) {
                        // Inhibiteur d'erreur
                        //var_dump($exception);
                    }
                }

                // Ajout d'une note dans la commande pour indiquer qu'elle vient de l'application mobile
                $msg = new Message();
                $message_prive = strip_tags("Notification envoyée sur l'application mobile (" . $nb_telephones_destination . ' terminaux) : ' . $message, '<br>');
                if (Validate::isCleanHtml($message_prive)) {
                    $msg->message = $message_prive;
                    $msg->id_cart = (int) $order->id_cart;
                    $msg->id_customer = (int) ($order->id_customer);
                    $msg->id_order = (int) $order->id;
                    $msg->private = true;
                    try {
                        $msg->add();
                    } catch (PrestaShopDatabaseException $e) {
                        // Inhibiteur d'erreur
                    } catch (PrestaShopException $e) {
                        // Inhibiteur d'erreur
                    }
                }
            }
        } catch (Exception $exception) {
            // Inhibiteur d'erreur
            //var_dump($exception);
        }
    }

    /**
     * @param array<string, mixed> $params
     */
    public function hookCustomerAccount(array $params): string
    {
        global $smarty;

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

        return $this->display(__FILE__, 'customer_myanimals.tpl');
    }

    /**
     * @param array<string, mixed> $params
     *
     * @throws PrestaShopDatabaseException
     */
    public function hookHideOrShowStatMenu(array $params): void
    {
        $smarty = $params['smarty'];

        if (isset($params['module'])) {
            $params['module']['class'] = '';

            $cookieContent = Context::getContext()->cookie->getAll();
            if (isset($cookieContent['profile'])) {
                $resultat = Db::getInstance()->executeS(
                    '
                    SELECT m.name, ma.view
                    FROM `' . _DB_PREFIX_ . 'module` m
                    LEFT JOIN `' . _DB_PREFIX_ . 'module_access` ma ON ma.id_module = m.id_module AND ma.id_profile = ' . (int) $cookieContent['profile'] . '
                    WHERE m.name = "' . Db::getInstance()->escape($params['module']['name']) . '"
                '
                );

                if (is_array($resultat) && count($resultat) && isset($resultat[0]['view']) && 0 == $resultat[0]['view']) {
                    $params['module']['class'] = ' hidden';
                }
            }

            $smarty->assign('module_class', $params['module']['class']);
        }
    }

    /**
     * @param array<string, mixed> $params
     *
     * @throws PrestaShopDatabaseException
     */
    public function hookMyvetshopHoliday(array $params): void
    {
        $smarty = $params['smarty'];

        $context = Context::getContext();
        $group = (int) $context->customer->id_default_group;

        $holidays = Db::getInstance()->executeS(
            'SELECT mch.*, (CURDATE() BETWEEN mch.date_debut AND mch.date_fin) AS block_paiement FROM `' . _DB_PREFIX_ . 'myvetshop_clinique` mc
                        INNER JOIN `' . _DB_PREFIX_ . 'myvetshop_clinique_holidays` mch ON mch.id_myvetshop_clinique = mc.id_myvetshop_clinique 
                        WHERE mc.id_group = ' . $group . ' AND (
                            CURDATE() BETWEEN mch.date_debut AND mch.date_fin
                            OR
                            CURDATE() BETWEEN mch.date_alerte AND mch.date_debut
                        )'
        );

        if (
            is_array($holidays)
            && count($holidays)
            && isset($holidays[0], $holidays['block_paiement'], $holidays['message'], $holidays['message_alerte'])
        ) {
            $holiday = $holidays[0];

            // Laisse le paiement de la commande
            $smarty->assign('allow_paiement', '1');
            //$smarty->assign('allow_paiement', $holiday['block_paiement'] ? '0' : '1');
            $smarty->assign('myvetshop_holiday_message', $holiday['block_paiement'] ? $holiday['message'] : $holiday['message_alerte']);
        }
    }

    /**
     * @param array<string, mixed> $params
     */
    public function hookMyvetshopMessageClinique(array $params): void
    {
        try {
            $smarty = $params['smarty'];

            $context = Context::getContext();
            $group_id = (int) $context->customer->id_default_group;

            $clinique_id = Clinique::getCliniqueByGroup((int) $group_id);

            if ($clinique_id) {
                $clinique = new Clinique($clinique_id);
                $smarty->assign('myvetshop_message_clinique', $clinique->message);
            }
        } catch (PrestaShopDatabaseException $e) {
        } catch (PrestaShopException $e) {
        }
    }

    /**
     * @param array<string, mixed> $params
     */
    public function hookActionAdminControllerSetMedia(array $params): void
    {
        //if ($this->context->controller->controller_name == 'YourAdminController'
        $this->context->controller->addCSS($this->_path . 'css/admin.css');
    }

    /**
     * Personnalisation plus avancée des e-mails
     *
     * @param array<string, mixed> $params
     *
     * @throws PrestaShopDatabaseException
     * @throws PrestaShopException
     */
    public function hookActionGetExtraMailTemplateVars(array $params): void
    {
        // Uniquement pour le e-mails "shipped" (lors de l'envoi du colis)
        if (!isset($params['template'])
            || !isset($params['template_vars'])
            || !in_array($params['template'], ['shipped', 'order_clinique'])
            || !isset($params['extra_template_vars'])
            || !isset($params['template_vars']['{id_order}'])) {
            return;
        }

        // Récupération de la commande
        $order = new Order($params['template_vars']['{id_order}']);
        if (!$order->id_carrier) {
            return;
        }

        require_once __DIR__ . DIRECTORY_SEPARATOR . 'classes' . DIRECTORY_SEPARATOR . 'Clinique.php';

        $id_clinique = Clinique::getCliniqueByCarrier((int) $order->id_carrier);
        if (!$id_clinique) {
            return;
        }

        // Chargement des informations
        $clinique = new Clinique($id_clinique);
        $store = new Store($clinique->id_store);

        /////////////////////////////////////////
        /// Génération du texte l'e-mail
        $order_html = '';
        switch (Clinique::getCarrierType((int) $order->id_carrier)) {
            case Clinique::CARRIER_CLINIQUE:
                switch ($params['template']) {
                    case 'order_clinique':
                        $order_html
                            = '<strong>ATTENTION : </strong> Compte tenu de la situation face au coronavirus, nous vous invitons à prendre contact directement avec votre propre clinique vétérinaire. Vous serez assurés de connaître ses nouveaux horaires d’ouvertures et protocoles pour récupérer vos commandes au mieux. Attention les horaires ci-dessous sont susceptibles de changer :';
                        //$order_html = "Votre clinique <strong>" . $store->name . "</strong> est ouverte aux horaires suivants :";
                        break;

                    default:
                        $order_html
                            = '<strong>ATTENTION : </strong> Compte tenu de la situation face au coronavirus, nous vous invitons à prendre contact directement avec votre propre clinique vétérinaire. Vous serez assurés de connaître ses nouveaux horaires d’ouvertures et protocoles pour récupérer vos commandes au mieux. Attention les horaires ci-dessous sont susceptibles de changer :';
                    //$order_html = "Elle sera disponible dans votre clinique vétérinaire entre 2j et 4j ouvrés après réception de ce message aux horaires suivants :";
                }
                $order_html .= "<br /><br/>\n";
                // Récupèrse les heures d'ouverture en fonction des jours
                $hours = explode(';', $store->getWsHours());

                if (!is_array($hours) || count($hours) > 7) {
                    $horaires_html = 'Horaires non disponibles';
                } else {
                    $jours = ['lundi', 'mardi', 'mercredi', 'jeudi', 'vendredi', 'samedi', 'dimanche'];
                    $horaires_html = '';

                    // Génération
                    foreach ($hours as $i => $horaires) {
                        if (6 == $i) {
                            // Ignore le dimanche
                            continue;
                        }
                        $horaires_html .= $jours[$i] . ' : ' . ($horaires ? $horaires : 'Non renseigné') . "<br>\n";
                    }
                }

                $order_html .= $horaires_html;

                switch ($params['template']) {
                    case 'order_clinique':
                        $order_html .= '<br />'
                            . "A l'adresse suivante :<br />" . $store->address1 . '<br />' . ($store->address2 ? $store->address2 . '<br />' : '') . $store->postcode . ' ' . $store->city . '<br />';
                        break;

                    default:
                }
                break;

            case Clinique::CARRIER_DOMICILE:
                $order_html = "Elle sera livrée directement à l'adresse de livraison que vous avez indiqué :<br/>\n";
                $address_delivery = new Address($order->id_address_delivery);

                $order_html .= $address_delivery->firstname . ' ' . $address_delivery->lastname . ($address_delivery->company ? ' (' . $address_delivery->company . ')' : '') . "<br>\n";
                $order_html .= $address_delivery->address1 . "<br>\n";
                if ($address_delivery->address2) {
                    $order_html .= $address_delivery->address2 . "<br>\n";
                }
                $order_html .= $address_delivery->postcode . ' ' . $address_delivery->city . ' ' . $address_delivery->country . "<br>\n";
                break;

            case Clinique::CARRIER_INCONNU:
                $order_html = "Elle sera livrée suivant les modalités que vous avez choisi lors du passage de commande :<br/>\n";
                $order_html .= (new Carrier($order->id_carrier))->name;
                break;
        }

        $params['extra_template_vars']['{order_html}'] = $order_html;
        $params['extra_template_vars']['{order_text}'] = strip_tags($order_html);
    }

    public function hookDisplayHeader(): void
    {
        // Gestion automatique du mode "application mobile"
        if (Tools::getValue('mobile_app')) {
            $this->context->cookie->mobile_app = 1;
            $this->context->cookie->update();
        }

        if ($this->context->cookie->mobile_app) {
            $this->context->controller->addCSS($this->_path . 'css/mobileapp.css', 'all');
        }
    }

    /**
     * @param array<string, mixed> $params
     */
    public function hookActionBeforeCartUpdateQty(array $params): void
    {
        $operator = $params['operator'];

        if ('up' === $operator) {
            /** @var Cart $cart */
            $cart = $params['cart'];

            /** @var Product $product */
            $product = $params['product'];

            if (!LimitedNumberOfProductByOrder::canBuyProduct($cart, $product, (int) $params['quantity'])) {
                $product->available_for_order = false;
            }
        }
    }

    /**
     * @param array<string, mixed> $params
     */
    public function hookDisplayAddRecoLink(array $params): string
    {
        return $this->display(__FILE__, 'add_reco.tpl');
    }

    /**
     * @param Customer $customer
     */
    public function syncCustomerWithPhpList(Customer $customer): void
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, 'https://newsletter.myvetshop.fr/lists/?pi=myvetshop&p=syncfromprestashop');
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($curl, CURLOPT_DNS_USE_GLOBAL_CACHE, true);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt(
            $curl, CURLOPT_POSTFIELDS, [
                'email' => $customer->email,
                'newsletter' => $customer->newsletter,
                'optin' => $customer->optin,
                'firstname' => $customer->firstname,
                'lastname' => $customer->lastname,
            ]
        );
        curl_exec($curl);
    }
}
