<?php

declare(strict_types=1);

/**
 * Created by Aurélien RICHAUD (21/06/2016 10:31)
 */
class IdentityController extends IdentityControllerCore
{
    /**
     * @throws PrestaShopDatabaseException
     * @throws PrestaShopException
     */
    public function postProcess(): 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` g
			        WHERE g.id_group > 3
			        AND g.name LIKE "' . Db::getInstance()->escape($codePrivilege) . '"'
            );

            if (is_array($resultat) && 0 == count($resultat)) {
                $this->errors[] = Tools::displayError(
                    'Code privilège invalide'
                );
            }
        }

        if (0 == count($this->errors)) {
            parent::postProcess();

            $codePrivilege = Tools::getValue('code_privilege');

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

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

            if (0 == count($this->errors)) {
                if (isset($this->context->cookie->id_clinique)) {
                    unset($this->context->cookie->id_clinique);
                }
            }
        }

        return $this->customer;
    }

    /**
     * @throws PrestaShopDatabaseException
     * @throws PrestaShopException
     */
    public function initContent(): void
    {
        parent::initContent();
        if ($this->customer->id_default_group > 3) {
            $group = new Group($this->customer->id_default_group);
            $this->context->smarty->assign('code_privilege', $group->name[Context::getContext()->language->id]);
        }
    }
}
