<?php

namespace QUI\MasterLogin;

use QUI;
use QUI\System\Console\Tools\MigrationV2;

use function date;

/**
 * Class Events
 *
 * Main event handler for quiqqer/masterlogin
 */
class Events
{
    /**
     * quiqqer/core: onTemplateGetHeader
     *
     * Load MasterLogin control in template
     *
     * @param QUI\Template $Template
     * @return void
     */
    public static function onTemplateGetHeader(QUI\Template $Template): void
    {
        if (!QUI::getUsers()->isAuth(QUI::getUserBySession()) || !Manager::canUse()) {
            return;
        }

        $masterUser = '';
        $slaveUser = '';

        $masterUserData = [];
        $slaveUserData = [];

        if (Manager::isLoggedInAsSlave()) {
            // Fetch master user info
            $masterUserId = QUI::getSession()->get(Manager::SESSION_MASTER_USER_ID);

            try {
                $MasterUser = QUI::getUsers()->get($masterUserId);

                $masterUser = $MasterUser->getName() . ' (#' . $MasterUser->getId() . ')';
                $masterUserData = [
                    'id' => $MasterUser->getId(),
                    'name' => $MasterUser->getName(),
                    'email' => $MasterUser->getAttribute('email')
                ];
            } catch (\Exception $Exception) {
                QUI\System\Log::writeException($Exception);
            }

            // Fetch slave user info (session user)
            /** @var QUI\Users\User $SlaveUser */
            $SlaveUser = QUI::getUserBySession();
            $slaveName = $SlaveUser->getName();
            $slaveCompany = '';

            try {
                $SlaveUserAddress = $SlaveUser->getStandardAddress();
                $slaveCompany = $SlaveUserAddress->getAttribute('company');

                if (!empty($SlaveUserAddress->getName())) {
                    $slaveName = $SlaveUserAddress->getName();
                }
            } catch (\Exception $Exception) {
                QUI\System\Log::writeDebugException($Exception);
            }

            $slaveUser = $slaveName . ' - ' . $slaveCompany . ' (#' . $SlaveUser->getId() . ')';

            $slaveUserData = [
                'id' => $SlaveUser->getId(),
                'name' => $slaveName,
                'email' => $SlaveUser->getAttribute('email'),
                'company' => $slaveCompany
            ];
        } else {
            // no slave user, get admin user data
            $MasterUser = QUI::getUserBySession();
            $masterUser = $MasterUser->getName() . ' (#' . $MasterUser->getId() . ')';
            $masterUserData = [
                'id' => $MasterUser->getId(),
                'name' => $MasterUser->getName(),
                'email' => $MasterUser->getAttribute('email')
            ];
        }

        $masterUserData = json_encode($masterUserData);
        $slaveUserData = json_encode($slaveUserData);

        $Template->extendFooter(
            '<div data-qui="package/quiqqer/masterlogin/bin/js/frontend/controls/MasterLogin"
                  data-qui-options-slave="' . (Manager::isLoggedInAsSlave() ? 1 : 0) . '"
                  data-qui-options-masteruser="' . $masterUser . '"
                  data-qui-options-slaveuser="' . $slaveUser . '"
                  data-qui-options-masteruserdata="' . htmlspecialchars($masterUserData, ENT_QUOTES, 'UTF-8') . '"
                  data-qui-options-slaveuserdata="' . htmlspecialchars($slaveUserData, ENT_QUOTES, 'UTF-8') . '"
             ></div>'
        );
    }

    /**
     * quiqqer/core: onAdminLoad
     *
     * If the user accesses the backend -> log out of any possible slave user
     *
     * @return void
     */
    public static function onAdminLoad(): void
    {
        Manager::logBack();
    }

    /**
     * quiqqer/core: onUserLogout
     *
     * @param QUI\Users\User $User
     * @return void
     */
    public static function onUserLogout(QUI\Users\User $User): void
    {
        // Update log entry
        try {
            QUI::getDataBase()->update(
                Manager::getLogTable(),
                ['end' => date('Y-m-d H:i:s')],
                [
                    'end' => null,
                    'slave_id' => $User->getUUID(),
                    'sec_hash' => QUI::getUsers()->getSecHash()
                ]
            );
        } catch (\Exception $Exception) {
            QUI\System\Log::writeException($Exception);
        }
    }

    public static function onQuiqqerMigrationV2(MigrationV2 $Console): void
    {
        $Console->writeLn('- Migrate master login');
        $table = QUI::getDBTableName('masterlogin_log');

        QUI::getDataBaseConnection()->executeStatement(
            'ALTER TABLE `' . $table . '` CHANGE `master_id` `master_id` VARCHAR(50) NOT NULL;'
        );

        QUI::getDataBaseConnection()->executeStatement(
            'ALTER TABLE `' . $table . '` CHANGE `slave_id` `slave_id` VARCHAR(50) NOT NULL;'
        );

        QUI::getDataBaseConnection()->executeStatement(
            'ALTER TABLE `' . $table . '` CHANGE `id` `id` VARCHAR(50) NOT NULL;'
        );

        QUI\Utils\MigrationV1ToV2::migrateUsers($table, [
            'master_id',
            'slave_id',
        ]);
    }
}
