<?php
/**
 * Created by PhpStorm.
 * User: crose
 * Date: 4/8/17
 * Time: 6:53 PM
 */

namespace IMATHUZH\Qfq\Core\Store;


use IMATHUZH\OidcClient\Service\UserStorage;
use IMATHUZH\Qfq\Core\Typo3\T3Handler;


/**
 * Class T3Info
 * @package qfq
 */
class T3Info {

    /**
     * Collect some global T3 variables and return them as array.
     *
     * @return array
     */
    public static function getVars() {

        $t3vars = array();

        $t3vars[TYPO3_FE_USER] = T3Handler::getFeUserProperty('username', '');
        $t3vars[TYPO3_FE_USER_EMAIL] = T3Handler::getFeUserProperty('email', '');
        $t3vars[TYPO3_FE_USER_UID] = T3Handler::getFeUserProperty('uid', '');
        $t3vars[TYPO3_FE_USER_GROUP] = T3Handler::getFeUserProperty('usergroup', '');

        // Will be set later
        $t3vars[TYPO3_TT_CONTENT_UID] = 'not set yet';

        $pageId = T3Handler::getPageId();
        $t3vars[TYPO3_PAGE_ID] = $pageId !== 0 ? $pageId : '';

        $pageRecord = T3Handler::getPageRecord();

        // TYPO3_PAGE_ALIAS is kept for backwards compatibility with existing QFQ
        // configurations; the `alias` column was removed in TYPO3 v10, so this
        // now falls back to the page id.
        $t3vars[TYPO3_PAGE_ALIAS] = !empty($pageRecord['alias']) ? $pageRecord['alias'] : $t3vars[TYPO3_PAGE_ID];
        $t3vars[TYPO3_PAGE_SLUG] = !empty($pageRecord['slug']) ? $pageRecord['slug'] : '/';
        $t3vars[TYPO3_PAGE_TITLE] = $pageRecord['title'] ?? '';
        $t3vars[TYPO3_PAGE_TYPE] = T3Handler::getPageType();

        $t3vars[TYPO3_PAGE_LANGUAGE] = self::getLanguageId();
        $t3vars[TYPO3_PAGE_LANGUAGE_PATH] = self::getLanguagePath($t3vars[TYPO3_PAGE_LANGUAGE]);

        $t3vars[TYPO3_BE_USER_LOGGED_IN] = self::beUserLoggedIn() ? 'yes' : 'no';
        $t3vars[TYPO3_BE_USER] = T3Handler::getBeUserProperty('username', '');
        $t3vars[TYPO3_BE_USER_EMAIL] = T3Handler::getBeUserProperty('email', '');
        $t3vars[TYPO3_BE_USER_UID] = T3Handler::getBeUserProperty('uid', '');

        $t3vars[TYPO3_PAGE_DESCRIPTION] = $pageRecord[T3DATA_DESCRIPTION] ?? '';
        $t3vars[TYPO3_PAGE_ABSTRACT] = $pageRecord[T3DATA_ABSTRACT] ?? '';
        $t3vars[TYPO3_PAGE_KEYWORDS] = $pageRecord[T3DATA_KEYWORDS] ?? '';

        $t3vars[TYPO3_VERSION] = T3Handler::getTypo3Version();

        /***** oidc data ******/

        $feUserAuth = T3Handler::getFrontendUserAuthentication();
        if ($feUserAuth !== null && class_exists(UserStorage::class)) {
            $oidcStorage = (new UserStorage($feUserAuth))->get() ?? [];
        } else {
            $oidcStorage = [];
        }

        $t3vars[TYPO3_OIDC_PROVIDER] = $oidcStorage['provider'] ?? '';
        $t3vars[TYPO3_OIDC_RESOURCE_ID] = $oidcStorage['resource_id'] ?? '';
        $t3vars[TYPO3_OIDC_SUB] = $oidcStorage['sub'] ?? '';
        $t3vars[TYPO3_OIDC_EMAIL] = $oidcStorage['email'] ?? '';
        if (isset($oidcStorage['email_verified'])) {
            $t3vars[TYPO3_OIDC_EMAIL_VERIFIED] = ($oidcStorage['email_verified'] === true) ? 'true' : 'false';
        } else {
            $t3vars[TYPO3_OIDC_EMAIL_VERIFIED] = 'null';
        }
        $t3vars[TYPO3_OIDC_GIVEN_NAME] = $oidcStorage['given_name'] ?? '';
        $t3vars[TYPO3_OIDC_FAMILY_NAME] = $oidcStorage['family_name'] ?? '';

        /***** oidc data end ******/


        return $t3vars;
    }

    /**
     * Returns the page language uid. This is only possible if QFQ is called via T3, not via API.
     *
     * @return string
     */
    public static function getLanguageId() {
        if (!class_exists(\TYPO3\CMS\Core\Context\Context::class)) {
            return '';
        }
        $context = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\Context\Context::class);
        return $context->getAspect('language')->getId();
    }

    /**
     * Returns the base url with language path. This is only possible if QFQ is called via T3, not via API.
     *
     * @return string
     * @throws \UserReportException
     */
    public static function getBaseUrlLang() {
        if (!T3Handler::isTypo3Loaded()) {
            return null;
        }

        $lid = self::getLanguageId();
        if ($lid === '' || !is_numeric($lid)) {
            return null;
        }
        try {
            // In an API call Typo3 might have been loaded manually by QFQ at some earlier point. But the following line does not work in that case.
            $sf = new \TYPO3\CMS\Core\Site\SiteFinder();
        } catch (\Throwable $e) {
            return null;
        }
        $allSites = $sf->getAllSites();
        if (count($allSites) < 1) {
            return null;
        }
        $site = self::getSiteConfiguration($sf);
        $lang = $site->getLanguageById((int)$lid);
        $base = $lang->getBase();
        return (string)$base;
    }

    /**
     * Check if there is a Typo3 beUser is logged in. This is only possible if QFQ is called via T3, not via API
     *
     * @return bool  true: current Browser session is a logged in BE User.
     */
    public static function beUserLoggedIn() {
        if (!T3Handler::isTypo3Loaded()) {
            return false;
        }
        $context = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\Context\Context::class);
        return (bool)$context->getPropertyFromAspect('backend.user', 'isLoggedIn');
    }

    /**
     * Returns the language path part. Helpful for forwardPage handling of forms in T3 >=V10
     *
     * @return string
     */
    public static function getLanguagePath($languageId): string {
        if (!isset($GLOBALS['TYPO3_REQUEST'])) {
            return '';
        }
        $site = $GLOBALS['TYPO3_REQUEST']->getAttribute('site');
        if (!$site) {
            return '';
        }
        $siteIdentifier = $site->getIdentifier();
        $siteConfiguration = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance(\TYPO3\CMS\Core\Site\SiteFinder::class)
            ->getSiteByIdentifier($siteIdentifier)
            ->getConfiguration();
        $languages = $siteConfiguration['languages'] ?? [];
        $actualLanguage = $languages[$languageId]['base'] ?? '';
        return trim($actualLanguage, '/');
    }

    /**
     * Returns the site configuration from current page.
     *
     * object $sf
     * @return object
     */
    public static function getSiteConfiguration($sf): object {
        if (isset($GLOBALS['TYPO3_REQUEST'])) {
            $site = $GLOBALS['TYPO3_REQUEST']->getAttribute('site');
            if ($site) {
                return $sf->getSiteByIdentifier($site->getIdentifier());
            }
        }
        $allSites = $sf->getAllSites();
        return reset($allSites);
    }
}