<?php

require_once __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'classes' . DIRECTORY_SEPARATOR . 'OrderExporter.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'classes' . DIRECTORY_SEPARATOR . 'OrderSlipExporter.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'classes' . DIRECTORY_SEPARATOR . 'OAuthAccessToken.php';
require_once __DIR__ . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . '..' . DIRECTORY_SEPARATOR . 'class' . DIRECTORY_SEPARATOR . 'NotificationManager.php';

class AdminMyVetShopAppVetzenMaintenanceController extends ModuleAdminController
{
    /**
     * @var string
     */
    public const PREFIX_NAME_COMFIG = 'MYVETSHOP_CLINIQUE_APP_VETO_MAINTENANCE_CONFIG_';

    /**
     * @var int
     *          Délais en mois apres lequel le token n'est plus considéré comme actif pour les notifications
     */
    public const DELAY_ENABLE_NOTIF_AFTER_LAST_USED = 1;

    /**
     * AdminMyVetShopAppMaintenanceController constructor.
     *
     * @throws PrestaShopException
     */
    public function __construct()
    {
        parent::__construct();

        $this->bootstrap = true;
    }

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

        try {
            if ('updateVetoApp' === Tools::getValue('action')) { // Gestion de la maintenance
                $minVersion = (string) Tools::getValue('minVersion');

                if ($minVersion && 1 !== preg_match('/^([0-9]+)(.[0-9]+)?(.[0-9]+)?$/', $minVersion)) {
                    throw new Exception('Le format de la version est invalide');
                }

                $maintenanceMessageTitle = (string) Tools::getValue('maintenanceMessageTitle');
                $maintenanceMessage = (string) Tools::getValue('maintenanceMessage');

                if (($maintenanceMessageTitle && !$maintenanceMessage) || (!$maintenanceMessageTitle && $maintenanceMessage)) {
                    throw new Exception('Le message doit avoir un titre et du contenu valide');
                }

                Configuration::updateValue(self::PREFIX_NAME_COMFIG . 'MESSAGE_TITLE', $maintenanceMessageTitle);
                Configuration::updateValue(self::PREFIX_NAME_COMFIG . 'MESSAGE', $maintenanceMessage);
                Configuration::updateValue(self::PREFIX_NAME_COMFIG . 'MESSAGE_LINK', (string) Tools::getValue('maintenanceMessageLink'));
                Configuration::updateValue(self::PREFIX_NAME_COMFIG . 'MESSAGE_LINK_TITLE', (string) Tools::getValue('maintenanceMessageLinkTitle'));
                Configuration::updateValue(self::PREFIX_NAME_COMFIG . 'MIN_VERSION', $minVersion);
                Configuration::updateValue(self::PREFIX_NAME_COMFIG . 'MAINTENANCE_MODE', (string) Tools::getValue('maintenanceMode'));

                $this->context->smarty->assign(
                    [
                        'success' => 'Mise à jour de la configuration effectuée avec succès',
                    ]
                );
            } elseif ('sendNotificationVetoApp' === Tools::getValue('action')) { // Envoi de notification
                $employeesId = Tools::getValue('notification_clinique_ids_employee');
                $notificationMessage = Tools::getValue('notificationMessage');
                $notificationMessageTitle = Tools::getValue('notificationMessageTitle') ? Tools::getValue('notificationMessageTitle') : null;

                if (!$notificationMessage) {
                    throw new Exception('Le message de la notification est invalide');
                }

                if (!$employeesId) {
                    throw new Exception('La liste des cliniques est invalide');
                }

                $notificationTokens = [];

                foreach ($employeesId as $employeeId) {
                    // Récupération des tokens de moins de self::DELAY_ENABLE_NOTIF_AFTER_LAST_USED mois
                    $tokensForEmployee = OAuthAccessToken::getValidTokenNotificationForEmployee((int) $employeeId);

                    if ($tokensForEmployee) {
                        $notificationTokens = array_merge($notificationTokens, $tokensForEmployee);
                    }
                }

                $notificationManager = new NotificationManager();

                // Envoi des notifications
                array_walk(
                    $notificationTokens,
                    function (OAuthAccessToken $token) use ($notificationManager, $notificationMessage, $notificationMessageTitle) {
                        $cliniquePush = OAuthAccessToken::getPushCliniqueByToken($token);

                        if ($cliniquePush) {
                            // Récupération des clinique push associés aux tokens et envoi de la notification
                            $notificationManager->sendCliniqueNotification($cliniquePush, $notificationMessage, $notificationMessageTitle);
                        }
                    }
                );

                $this->context->smarty->assign(
                    [
                        'success' => 'Notifications envoyées avec succès',
                    ]
                );
            }
        } catch (Exception $exception) {
            $this->context->smarty->assign(
                [
                    'error' => 'Une erreur s\'est produite : ' . $exception->getMessage(),
                ]
            );
        }

        $db = db::getInstance();
        $cliniques = $db->executeS(
            'SELECT c.code_privilege, c.id_myvetshop_clinique, c.id_employee, s.name FROM ' . _DB_PREFIX_ . 'myvetshop_clinique c 
            INNER JOIN ' . _DB_PREFIX_ . 'store s ON c.id_store = s.id_store WHERE c.deleted = 0 ORDER BY c.code_privilege ASC'
        );
        $this->context->smarty->assign('cliniques', $cliniques);

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

        $this->context->smarty->assign(
            [
                'messageTitle' => Configuration::get(self::PREFIX_NAME_COMFIG . 'MESSAGE_TITLE'),
                'message' => Configuration::get(self::PREFIX_NAME_COMFIG . 'MESSAGE'),
                'messageLink' => Configuration::get(self::PREFIX_NAME_COMFIG . 'MESSAGE_LINK'),
                'messageLinkTitle' => Configuration::get(self::PREFIX_NAME_COMFIG . 'MESSAGE_LINK_TITLE'),
                'minVersion' => Configuration::get(self::PREFIX_NAME_COMFIG . 'MIN_VERSION'),
                'maintenanceMode' => Configuration::get(self::PREFIX_NAME_COMFIG . 'MAINTENANCE_MODE'),
            ]
        );

        $template_file = _PS_MODULE_DIR_ . 'myvetshopclinique/views/templates/admin/my_vet_shop_clinique_app_maintenance/view.tpl';
        $content = $this->context->smarty->fetch($template_file);
        $this->context->smarty->assign(
            [
                'content' => $content,
            ]
        );
    }
}
