<?php

namespace Myvetshop\Module\Clinique\Tab;

use Access;
use Db;
use Language;
use PrestaShopBundle\Entity\Repository\TabRepository;
use PrestaShopBundle\Entity\Tab;
use PrestaShopBundle\Event\ModuleManagementEvent;
use Profile;
use Symfony\Component\EventDispatcher\EventSubscriberInterface;
use Validate;

class ModuleTabManagementSubscriber implements EventSubscriberInterface
{
    /**
     * @var TabRepository
     */
    private $tabRepository;

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

    public static function getSubscribedEvents()
    {
        return [
            ModuleManagementEvent::INSTALL => 'onModuleInstall',
        ];
    }

    public function onModuleInstall(ModuleManagementEvent $event)
    {
        $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 = Db::getInstance()->getValue($query);

            $profile = new Profile($profileId);

            if (!Validate::isLoadedObject($profile)) {
                foreach (Language::getLanguages() as $language) {
                    $profile->name[$language['id_lang']] = '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($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($profile->id, $roleId);
                    }
                }
            }
        }
    }
}
