<?php

declare(strict_types=1);

use Myvetshop\Module\Clinique\Repository\CliniquePushRepository;

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 {
            $action = Tools::getValue('action');
            if (!\is_string($action)) {
                $action = 'nothing';
            }

            if ('updateVetoApp' === $action) { // Gestion de la maintenance
                $minVersion = Tools::getValue('minVersion');
                if (!\is_string($minVersion)) {
                    $minVersion = '';
                }

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

                $maintenanceMessageTitle = Tools::getValue('maintenanceMessageTitle');
                if (!\is_string($maintenanceMessageTitle)) {
                    $maintenanceMessageTitle = '';
                }

                $maintenanceMessage = Tools::getValue('maintenanceMessage');
                if (!\is_string($maintenanceMessage)) {
                    $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
                );
                $maintenanceMessageLink = Tools::getValue('maintenanceMessageLink');
                if (!\is_string($maintenanceMessageLink)) {
                    $maintenanceMessageLink = '';
                }
                Configuration::updateValue(
                    self::PREFIX_NAME_COMFIG . 'MESSAGE_LINK',
                    $maintenanceMessageLink
                );
                $maintenanceMessageLinkTitle = Tools::getValue('maintenanceMessageLinkTitle');
                if (!\is_string($maintenanceMessageLinkTitle)) {
                    $maintenanceMessageLinkTitle = '';
                }
                Configuration::updateValue(
                    self::PREFIX_NAME_COMFIG . 'MESSAGE_LINK_TITLE',
                    $maintenanceMessageLinkTitle
                );
                Configuration::updateValue(
                    self::PREFIX_NAME_COMFIG . 'MIN_VERSION',
                    $minVersion
                );
                $maintenanceMode = Tools::getValue('maintenanceMode');
                if (\is_string($maintenanceMode)) {
                    $maintenanceMode = '';
                }
                Configuration::updateValue(
                    self::PREFIX_NAME_COMFIG . 'MAINTENANCE_MODE',
                    $maintenanceMode
                );

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

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

                if (!\is_array($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();
                $container = $this->getContainer();
                if (null === $container) {
                    throw new Exception('Container not started');
                }

                /** @var CliniquePushRepository $cliniquePushRepository */
                $cliniquePushRepository = $container->get(CliniquePushRepository::class);

                // Envoi des notifications
                \array_walk(
                    $notificationTokens,
                    function (OAuthAccessToken $token) use ($cliniquePushRepository): void {
                        $cliniquePush = $cliniquePushRepository->findOneBy(['idOauthAccessToken' => $token->id]);

                        if ($cliniquePush) {
                            // TODO : Fix
                            // Récupération des cliniques push associés aux tokens et envoi de la notification
                            // $notificationManager->sendNotification($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, c.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,
            ]
        );
    }
}
