<?php

declare(strict_types=1);

namespace Myvetshop\Module\Clinique\Tab;

use PrestaShopBundle\Entity\Repository\TabRepository;
use PrestaShopBundle\Entity\Tab;
use PrestaShopBundle\Event\ModuleManagementEvent;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;

class ModuleTabManagementSubscriber implements EventSubscriberInterface
{
    private TabRepository $tabRepository;

    public function __construct(TabRepository $tabRepository)
    {
        $this->tabRepository = $tabRepository;
    }

    /**
     * @return array<string, string>
     */
    public static function getSubscribedEvents(): array
    {
        return [
            ModuleManagementEvent::INSTALL => 'onModuleInstall',
        ];
    }

    public function onModuleInstall(ModuleManagementEvent $event): void
    {
        $module = $event->getModule()->getInstance();

        if ($module && $module instanceof \myvetshopclinique) {
            $query = 'SELECT id_profile FROM '
                . _DB_PREFIX_ . \Profile::$definition['table'] . '_lang WHERE name="Clinique vétérinaire"';
            $profileId = (int) \Db::getInstance()->getValue($query);

            $profile = new \Profile($profileId);

            if (!\Validate::isLoadedObject($profile)) {
                /** @var int[] $languages */
                $languages = \Language::getLanguages(true, false, true);
                foreach ($languages as $language) {
                    $profile->name[$language] = 'Clinique vétérinaire';
                }

                $profile->add();
            }

            $query = 'SELECT id_authorization_role FROM '
                . _DB_PREFIX_ . 'authorization_role'
                . ' WHERE slug="' . \Access::findSlugByIdModule($module->id) . 'READ"';
            $roleId = (int) \Db::getInstance()->getValue($query);

            if ($roleId) {
                (new \Access())->addModuleAccess((int) $profile->id, $roleId);
            }

            $allowTabs = ['AdminMyVetShopClinique'];
            /**
             * @var Tab[] $tabs
             */
            $tabs = $this->tabRepository->findByModule($module->name);

            foreach ($tabs as $tab) {
                if (\in_array($tab->getClassName(), $allowTabs)) {
                    $query = 'SELECT id_authorization_role FROM '
                        . _DB_PREFIX_ . 'authorization_role WHERE'
                        . ' slug="' . \Access::findSlugByIdTab($tab->getId()) . 'READ"';
                    $roleId = (int) \Db::getInstance()->getValue($query);

                    if ($roleId) {
                        (new \Access())->addAccess((int) $profile->id, $roleId);
                    }
                }
            }
        }
    }
}
