<?php
/**
 * Polylang
 * @package polylang
 * @var modX $modx
 * @var Polylang $polylang
 * @var PolylangTools $tools
 * @var array $scriptProperties
 * @var string $scheme
 * @var string $activeClass
 * @var bool $showActive
 * @var bool $onlyWithLocalization
 */

$polylang = $modx->getService('polylang', 'Polylang');
$tools = $polylang->getTools();
$current = array();
$languages = array();
$classKey = 'PolylangLanguage';
$defaultLanguage = $tools->getDefaultLanguage();
$defaultLanguageGroup = $modx->getOption('polylang_default_language_group');
$languageGroup = $modx->getOption('languageGroup', $scriptProperties, $defaultLanguageGroup, true);

if (empty($scheme)) {
    $scheme = $modx->getOption('link_tag_scheme', null, -1, true);
}

$q = $modx->newQuery($classKey);
$q->where(array("`{$classKey}`.`active`" => 1));
if ($languageGroup) {
    $languageGroup = $tools->explodeAndClean($languageGroup);
    $q->leftJoin('PolylangLanguageGroupMember', 'LanguageGroupMember', "`LanguageGroupMember`.`language_id` = `{$classKey}`.`id`");
    $q->where(array('`LanguageGroupMember`.`group_id`:IN' => $languageGroup));
}
$q->sortby('`rank`', 'ASC');

/* @var PolylangLanguage[] $list */
if ($list = $modx->getCollection($classKey, $q)) {
    foreach ($list as $item) {
        $cultureKey = $item->get('culture_key');
        if ($onlyWithLocalization && $defaultLanguage !== $cultureKey) {
            if (!$tools->hasLocalization($modx->resource->get('id'), $cultureKey)) {
                continue;
            }
        }
        $active = $item->isCurrent();
        $language = $item->toArray();
        $language['active'] = $active;
        $language['classes'] = $active ? $activeClass : '';
        $language['link'] = $item->makeUrl($modx->resource, $scheme, $tools->getRequestQuery());
        if ($active) {
            $current = $language;
            if (!$showActive) continue;
        }
        $languages[] = $language;
    }
}

$config = array(
    'actionUrl' => $polylang->config['actionUrl'],
    'trigger' => $modx->getOption('trigger', $scriptProperties, 'polylang-toggle', true),
);

$modx->regClientStartupHTMLBlock('<script> var polylangConfig = ' . $modx->toJSON($config) . ';</script>');

if (!empty($css)) {
    $modx->regClientCSS($tools->preparePath($css));
}

if (!empty($js)) {
    $modx->regClientScript($tools->preparePath($js));
}

return $tools->getPdoTools()->getChunk($tpl, array(
    'mode' => $mode,
    'current' => $current,
    'languages' => $languages,
    'showActive' => $showActive,
));