<?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;
$pdoFetch = $tools->getPdoTools($sp);

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

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

$id = $sp['id'] ?: 0;
$tv = $sp['tv'] ?: 0;
$pageId = $sp['pageId'] ?: 0;
$tpl = $sp['tpl'] ?: '@INLINE <a href="[[+link]]">[[+tag]]</a>';
$tplWrapper = $sp['tplWrapper'] ?: '';
$outputSeparator = $sp['outputSeparator'] ?? ', ';
$toPlaceholder = $sp['toPlaceholder'] ?: false;
$scheme = $sp['scheme'] ?: '-1';
if (!$id || !$tv || !$tpl) {
    return false;
}

$q = $modx->newQuery($classKey);
$q->where(array(
    'resource_id' => $id,
    'tv_id' => $tv,
));

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

$q->select('value as tag');

$output = '';
$items = array();
if ($q->prepare()->execute()) {
    if ($rows = $q->stmt->fetchAll(PDO::FETCH_ASSOC)) {
        foreach ($rows as $row) {
            $row['tagLink'] = urlencode($row['tag']);
            $row['link'] = $pageId ? $modx->makeUrl($pageId, '', array('tag' => $row['tagLink']), $scheme) : '';

            $items[] = $pdoFetch->getChunk($tpl, $row);
        }
    }
}


if (!empty($items)) {
    $output = implode($outputSeparator, $items);
    if ($tplWrapper) {
        $output = $pdoFetch->getChunk($tplWrapper, array(
            'output' => $output,
        ));
    }
}

if (!empty($toPlaceholder)) {
    $modx->setPlaceholder($toPlaceholder, $output);
} else {
    return $output;
}