<?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();

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

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

$sp['context'] = !empty($sp['context']) ? $sp['context'] : $modx->context->key;
if (!$tags = (((($sp['tag'] ?: $sp['tags']) ?: $_REQUEST['tag']) ?: $_REQUEST['tags']) ?: '')) {
    return false;
}
if (!$tvs = (($sp['tv'] ?: $sp['tvs']) ?: '')) {
    return false;
}
unset($sp['tag'], $sp['tags'], $sp['tv'], $sp['tvs']);

if (is_string($tags)) {
    $tags = explode('||', $tags);
}
if (is_array($tags)) {
    $tags = array_map('trim', $tags);
    $tags = array_map('urldecode', $tags);
    $tags = array_diff($tags, array(''));
} else {
    return false;
}
if (empty($tags)) {
    return false;
}

$tvs = explode(',', $tvs);

$like = isset($sp['like']) ? $sp['like'] : false;

$class = !empty($sp['class']) ? $sp['class'] : 'modResource';

$select = array($class => '*');
$leftJoin = array();
$where = array(array());

foreach ($tvs as $tv) {
    $alias = 'tvss' . $tv;
    $orConditions = array();

    foreach ($tags as $i => $tag) {
        $tag = addslashes($tag);
        if ($like) {
            $condition = "`{$alias}`.`value` LIKE %'{$tag}'%";
        } else {
            $condition = "`{$alias}`.`value` = '{$tag}'";
        }
        if (!$isOriginalLanguage) {
            $condition .= " AND `{$alias}`.`culture_key` = '{$sp['lang']}'";
        }
        $orConditions[] = $condition;
    }

    if (!empty($orConditions)) {
        $orConditions = implode(' OR ', $orConditions);
        $leftJoin += array(
            $alias => array(
                'class' => $classKey,
                'alias' => $alias,
                'on' => "`{$alias}`.`resource_id` = `{$class}`.`id` AND ({$orConditions})",
            ),
        );
        if ($isOriginalLanguage) {
            $where[0][] = array(
                "OR:`{$alias}`.`tv_id`:=" => $tv,
            );
        } else {
            $where[0][] = array(
                "OR:`{$alias}`.`tv_id`:=" => $tv,
                "`{$alias}`.`culture_key`:=" => $sp['lang'],
            );
        }
    }
}

foreach (array('where', 'select', 'leftJoin') as $v) {
    if (!empty($sp[$v])) {
        $tmp = !is_array($sp[$v]) ? $modx->fromJSON($sp[$v]) : $sp[$v];
        if (is_array($tmp)) {
            $$v = array_merge($$v, $tmp);
        }
        unset($tmp);
    }
    unset($sp[$v]);
}
$pdoFetch->addTime('Conditions prepared');

$pdoFetch->addTime('Query parameters ready');

//$sp['return'] = 'sql';

$config = array_merge(array(
    'class' => $class,
    'select' => $modx->toJSON($select),
    'leftJoin' => $modx->toJSON($leftJoin),
    'where' => $modx->toJSON($where),
    'groupby' => "{$class}.id",
), $sp);

$pdoFetch->setConfig($config, false);
$rows = $pdoFetch->run();

return $rows;
