<?php
/**
 * @var modX $modx
 * @var Polylang $polylang
 * @var mSearch2 $mSearch2
 * @var array $fields
 * @var array $scriptProperties
 * @var int $id
 * @var string $page
 */

$polylang = $modx->getService('polylang', 'Polylang');
if (empty($polylang)) return;
/** @var PolylangTools $tools */
$tools = $polylang->getTools();

switch ($modx->event->name) {
    case 'OnMODXInit':
        $polylang->extendTvModel();
        $polylang->extendMs2OptionModel();
        $polylang->extendPolylangContent();
        $tools->prepareModelContent();
        if ($modx->context->get('key') == 'mgr') return;
        $tools->setDefaultSettings();
        if ($language = $tools->detectLanguage(true)) {
            $tools->setLanguage($language);
        }
        $tools->setDefaultCurrencyForLanguage($language);
        break;
    case 'OnTVFormPrerender':
        $polylang->loadControllerTVJsCss($modx->controller);
        break;
    case 'msOnManagerCustomCssJs':
        if ($page != 'settings') return;
        $polylang->loadControllerMs2OptionJsCss($modx->controller);
        break;
    case 'OnDocFormPrerender':
        if (!$id || !$polylang->isWorkingTemplates($modx->controller->resourceArray['template'])) return;
        $polylang->loadControllerJsCss($id, $modx->controller);
        break;
    case 'OnPageNotFound':
        $containerSuffix = $modx->getOption('container_suffix');
        $alias = $modx->context->getOption('request_param_alias', 'q');
        if (
            empty($containerSuffix) &&
            (
                isset($_REQUEST[$alias]) ||
                (empty($_REQUEST) && !empty($_SERVER['QUERY_STRING']))
            )
        ) {
            if ($urls = $tools->getLanguageUrls()) {
                $url = $tools->getRequestUrl(true) . '/';
                if (isset($urls[$url])) {
                    $pageId = $modx->getOption('site_start');
                    $modx->sendForward($pageId);
                }
            }
        }
        break;
    case 'OnHandleRequest':
        if ($modx->context->get('key') == 'mgr' || $tools->isAjaxRequestInAssets()) {
            return;
        }
        $geoRedirectDomain = '';
        if ($tools->isDetectGeoRedirectDomain()) {
            if ($geoRedirectDomain = $tools->detectGeoRedirectDomain()) {
                $tools->setSessionVar('georedirectdomain', $geoRedirectDomain);
                $modx->setPlaceholder('polylang_geo_redirect_domain', $geoRedirectDomain);
            }
        }

        $geoRedirectLanguageCode = '';
        if ($tools->isDetectGeoRedirectLanguage()) {
            if ($geoRedirectLanguageCode = $tools->detectGeoRedirectLanguage()) {
                $tools->setSessionVar('georedirectlanguage', $geoRedirectLanguageCode);
                if ($geoRedirectLanguage = $tools->getLanguageByCode($geoRedirectLanguageCode)) {
                    $modx->setPlaceholder('polylang_redirect_language', $geoRedirectLanguage);
                } else {
                    $geoRedirectLanguageCode = '';
                }
            }
        }
        if (
            !$geoRedirectDomain &&
            !$geoRedirectLanguageCode &&
            $language = $tools->detectLanguage()
        ) {
            $visitorlanguage = $tools->detectVisitorLanguage();
            $forcelanguage = $tools->getForceLanguage();
            $tools->setLanguage($language);
            if (
                $forcelanguage &&
                !$forcelanguage->isCurrent() &&
                $tools->hasHostLanguage($forcelanguage->get('culture_key'))
            ) {
                $modx->setPlaceholder('polylang_redirect_language', $forcelanguage);
            } else if (
                $visitorlanguage &&
                !$visitorlanguage->isCurrent() &&
                $tools->hasHostLanguage($visitorlanguage->get('culture_key'))
            ) {
                $modx->setPlaceholder('polylang_redirect_language', $visitorlanguage);
            }
        }
        break;
    case 'OnLoadWebDocument':
        $geoRedirectDomain = $modx->getPlaceholder('polylang_geo_redirect_domain');
        if ($geoRedirectDomain) {
            $tools->redirectToDomain($geoRedirectDomain, $tools->getRequestQuery());
        } else {
            $placeholders = null;
            $seoPatternEnabled = $modx->getOption('polylang_seo_pattern_enabled');
            $redirectLanguage = $modx->getPlaceholder('polylang_redirect_language');
            if ($redirectLanguage) {
                $redirectLanguage->redirect($modx->resource, $tools->getRequestQuery());
            }
            if ($modx->getPlaceholder('polylang_site')) {
                $pageId = $modx->resource->get('id');
                $errorPage = $modx->getOption('error_page');
                if ($errorPage == $pageId) {
                    header($_SERVER['SERVER_PROTOCOL'] . ' 404 Not Found');
                }
                if (
                    $errorPage != $pageId &&
                    $tools->hasError404($pageId)
                ) {
                    $modx->sendForward($errorPage);
                } else {
                    $options = array(
                        'skipTVs' => true,
                        'class' => get_class($modx->resource),
                        'content_id' => $pageId,
                    );
                    $placeholders = array();
                    $modx->resource->set('polylang_override', 1);
                    $tools->overrideResourceTvs($modx->resource);
                    $tools->prepareResourceData(function ($key, $value, $context) use (&$modx, &$placeholders) {
                        $original = $modx->resource->get($key);
                        $placeholders['polylang_original_' . $key] = $original;
                        if (
                            ($key == 'createdon' || $key == 'editedon') &&
                            $original > $value
                        ) {
                            $value = $original;
                        }
                        $placeholders[$key] = $value;
                        $modx->resource->set($key, $value);
                        $modx->resource->set('polylang_original_' . $key, $original);
                    }, $options);
                    $modx->setPlaceholders($placeholders, '*');

                }
            }
            if ($seoPatternEnabled) {
                if (!$placeholders) {
                    $placeholders = $modx->resource->toArray();
                }
                $templateId = $modx->resource->get('template');
                $languageId = (int)$modx->getPlaceholder('polylang_language_id');
                $pattern = $tools->getSeoPatternByTemplateId($templateId, $languageId);
                $seoPlaceholders = $tools->prapareSeoPlaceholders($pattern, $placeholders);
                $seoPrefix = $modx->getOption('polylang_seo_placeholder_prefix', null, 'pl_');
                $modx->setPlaceholders($seoPlaceholders, $seoPrefix);
            }
        }
        break;
    case 'msOnBeforeCreateOrder':
        /** @var msOrder $msOrder */
        $properties = $msOrder->get('properties');
        if (!is_array($properties)) $properties = array();
        $cultureKey = $modx->getOption('cultureKey');
        $defaultLanguage = $tools->getDefaultLanguage();
        $properties[$polylang->getNamespace()] = array(
            'cultureKey' => $cultureKey,
            'pagetitle' => array()
        );
        foreach ($msOrder->Products as $product) {
            $pagetitle = $product->get('name');
            if ($cultureKey != $defaultLanguage) {
                $content = $modx->getObject('PolylangContent', array(
                    '`culture_key`' => $cultureKey,
                    '`content_id`' => $product->get('product_id'),
                ));
                if ($content) {
                    $pagetitle = $content->get('pagetitle');
                }
            }
            $properties[$polylang->getNamespace()]['pagetitle'][$product->get('product_id')] = $pagetitle;
        }
        $msOrder->set('properties', $properties);
        break;
    case 'msOnBeforeChangeOrderStatus':
        /** @var msOrder $order */
        $properties = $order->get('properties');
        if ($properties && isset($properties[$polylang->getNamespace()])) {
            $cultureKey = $modx->getOption('cultureKey');
            $orderCultureKey = $modx->getOption('cultureKey', $properties[$polylang->getNamespace()]);
            if ($cultureKey != $orderCultureKey) {
                $tools->reloadLexicons($orderCultureKey);
            }
        }
        break;
    case 'mse2OnGetWorkFields':
        $modx->event->returnedValues['fields'] = $tools->putSearchFields($fields);
        break;
    case 'mse2OnBeforeSearchIndex':
        $tools->putSearchIndex($mSearch2, $resource);
        break;
    case 'OnBeforeEmptyTrash':
        if (!empty($scriptProperties['ids']) && is_array($scriptProperties['ids'])) {
            $tools->removeResourceLanguages($scriptProperties['ids']);
        }
        break;
    case 'OnTVInputRenderList':
        $modx->event->output($polylang->config['corePath'] . 'elements/tv/input/');
        break;
    case 'cabinetBeforeMakeUrl':
        $url = $tools->makeUrl($id, $context, $args, $scheme, $options);
        $modx->event->returnedValues['url'] = $url;
        break;

}
return;