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

$polylang = $modx->getService('polylang', 'Polylang');
$tools = $polylang->getTools();
$classKey = 'PolylangLanguage';
$id = $modx->resource->get('id');
$defaultLanguage = $tools->getDefaultLanguage();
$currentLanguage = $modx->getOption('cultureKey');
$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);
}

$keys = $tools->getResourceLanguageKeys($id);
$keys[] = $tools->getDefaultLanguage();

$q = $modx->newQuery($classKey);
$q->where(array("`{$classKey}`.`culture_key`:IN" => $keys));
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');


$languages = $modx->getCollection('PolylangLanguage', $q);

if ($languages) {
    $links = array();
    $items = array();
    foreach ($languages as $language) {
        $cultureKey = $language->get('culture_key');
        if ($onlyWithLocalization && $defaultLanguage !== $cultureKey) {
            if (!$tools->hasLocalization($id, $cultureKey)) {
                continue;
            }
        }
        $items[] = array(
            'url' => $language->makeUrl($id, $scheme),
            'lang' => $cultureKey,
            'default' => $language->get('culture_key') == $defaultLanguage ? 1 : 0,
            'current' => $language->get('culture_key') == $currentLanguage ? 1 : 0,
        );
    }
    if (!empty($items)) {
        $total = count($items);
        foreach ($items as $item) {
            $item['total'] = $total;
            $links[] = $tools->getPdoTools()->getChunk($tpl, $item);
        }
    }
    return implode("\n", $links);
}