<?php
/**
 * Polylang
 * @package polylang
 * @var modX $modx
 * @var Polylang $polylang
 * @var PolylangTools $tools
 * @var pdoFetch $pdoFetch
 * @var array $scriptProperties
 */

$polylang = $modx->getService('polylang', 'Polylang');
$tools = $polylang->getTools();
$isOriginalLanguage = $tools->isCurrentOriginalLanguage();

$sp = &$scriptProperties;

if (!isset($sp['lang'])) {
    $sp['lang'] = $modx->getOption('cultureKey');
}

$config = array(
    'parents' => null,  // current resource default
    'depth' => 10,
    'requestVar' => 'tag',
    'target' => null,
    'tv' => null,
    'sortby' => 'count', // count || tag
    'sortorder' => 'DESC', // DESC || ASC
    'limit' => 0,
    'countShow' => 8,
    'tpl' => '@INLINE <li><a href="{$uri}?{$requestVar}={$tag|urlencode}">{$tag} [{$count}]</a></li>', // специально оставил формирование урл здесь, вдруг кто захочет ЧПУ сделать
    'tplActive' => '',
    'tplWrapper' => '',
);

$config = array_merge($config, $sp);
$pdoFetch = $tools->getPdoTools($config);

$parents = empty($config['parents']) ? array($modx->resource->id) : explode(',', $config['parents']);
if ($config['depth'] != 1) {
    $childs = array();
    foreach ($parents as $parent) {
        $childs = array_merge($childs, $modx->getChildIds($parent, $config['depth'], array('context' => $modx->context->key)));
    }
    $parents = array_merge($parents, $childs);
}
$target = empty($config['target']) ? $modx->resource->id : $config['target'];
$uri = $modx->makeUrl($target, '', '', $modx->getOption('link_tag_scheme'));

$requestTag = !empty($_REQUEST[$config['requestVar']]) ? urldecode($_REQUEST[$config['requestVar']]) : null;

$output = array();
$classKey = 'PolylangTvssOptions';
if ($isOriginalLanguage) {
    $classKey = 'tvssOption';
    $modx->addPackage('tvsuperselect', MODX_CORE_PATH . 'components/tvsuperselect/model/');
}

$c = $modx->newQuery($classKey);
$c->innerJoin('modResource', 'mr', "mr.id = {$classKey}.resource_id");
$where = array(
    'mr.published' => 1,
    'mr.deleted' => 0,
    'mr.parent:IN' => $parents,
);
if (!empty($config['tv'])) {
    $where['tv_id'] = $config['tv'];
}

if (!$isOriginalLanguage) {
    $where['culture_key'] = $config['lang'];
}

$c->where($where);
$c->select("COUNT(*) AS `count`, `{$classKey}`.`value` AS `tag`");
$c->groupby("{$classKey}.value");
$c->sortby($config['sortby'], $config['sortorder']);
$c->limit($config['limit']);

if ($c->prepare() and $c->stmt->execute()) {
    $tags = $c->stmt->fetchAll(PDO::FETCH_ASSOC);
    if (!empty($tags)) {
        $idx = 0;
        foreach ($tags as $tag) {
            $idx++;
            $tpl = $config['tpl'];
            $isActive = $tag['tag'] == $requestTag;
            $tag['uri'] = $uri;
            $tag['countShow'] = $config['countShow'];
            $tag['requestVar'] = $config['requestVar'];
            $tag['isActive'] = $isActive;
            $tag['idx'] = $idx;
            if ($isActive && !empty($config['tplActive'])) {
                $tpl = $config['tplActive'];
            }
            $output[] = $pdoFetch->getChunk($tpl, $tag);
        }
        $output = implode('', $output);
        if (!empty($config['tplWrapper'])) {
            $output = $pdoFetch->getChunk($config['tplWrapper'], array(
                'output' => $output,
                'count' => count($tags),
                'countShow' => $config['countShow'],
            ));
        }
    }
}

return $output;