<?php
$q = $modx->newQuery("modResource");
$q->innerJoin('modTemplateVarResource', 'tvv', array(
    'tvv.contentid = modResource.id'
));
$q->innerJoin('modTemplateVar', 'tv', array('tv.id = tvv.tmplvarid'));
$q->where(array(
    'modResource.published' => 1,
    'modResource.parent' => $parents
));

/*
    Фильтр
*/
if($allow == 'Y' || isset($pricesFrom))
{    
    $filter = array();
    $bodyType = preg_replace('/[^а-яА-Я0-9\.\s]/ui', '',$bodyType);
    $bodyType = trim($bodyType);
    $engineType = preg_replace('/[^а-яА-Я0-9\s]/ui', '',$engineType);
    $engineType = trim($engineType);
    $gearboxType = preg_replace('/[^а-яА-Я0-9\s]/ui', '',$gearboxType);
    $gearboxType = trim($gearboxType);
    
    if($brand){
        $filter = array(
            "tv.name" => "mark",
            "tvv.value:=" => $brand
        );
    }
    if($model){
        $filter = array(
            "tv.name" => "model",
            "tvv.value:=" => $model
        );
    }
    if($yearsFrom || $yearsTo){
        $filter = array(
            "tv.name" => "years",
            "tvv.value:>=" => ($yearsFrom) ? $yearsFrom : 1960,
            "tvv.value:<=" => ($yearsTo) ? $yearsTo : date('Y')
        );
    }
    // if($yearsTo){
    //     $filter = array(
    //         'modResource.published' => 1,
    //         "tv.name" => "years",
    //         "OR:tvv.value:<=" => $yearsTo
    //     );
    // }
    if($pricesFrom || $pricesTo){
        $filter = array(
            "tv.name" => "price",
            "tvv.value:>=" => (!empty($pricesFrom)) ? $pricesFrom : 10000,
            "tvv.value:<=" => (!empty($pricesTo)) ? $pricesTo : 9999999999
        );
    }
    // if($pricesTo){
    //     $filter = array(
    //         'modResource.published' => 1,
    //         "tv.name" => "price",
    //         "OR:tvv.value:<=" => $pricesTo
    //     );
    // }
    if($bodyType){
        $filter = array(
            "tv.name" => "body",
            "tvv.value:=" => "$bodyType"
        );
    }
    if($engineType){
        $filter = array(
            "tv.name" => "engine",
            "tvv.value:=" => "$engineType"
        );
    }
    if($gearboxType){
        $filter = array(
            "tv.name" => "kpp",
            "tvv.value:=" => "$gearboxType"
        );
    }
    if(!empty($distanceFrom) || !empty($distanceTo)){
        $filter = array(
            "tv.name" => "mileage",
            "tvv.value:>=" => ($distanceFrom) ? $distanceFrom : 1000,
            "tvv.value:<=" => ($distanceTo) ? $distanceTo : 999999
        );
    }
    // if($distanceTo){
    //     $filter = array(
    //         'modResource.published' => 1,
    //         "tv.name" => "mileage",
    //         "OR:tvv.value:<=" => $distanceTo
    //     );
    // }
    $q->where($filter);
}else{
    /*
        Если выбран город, фильтруем по городу
    */
    if(!empty($_SESSION['cityName']) && $_SESSION['cityName'] != "all") {
        $q->where(array(
            'tv.name' => 'cityName'
        ));
        $q->andCondition(array(
             'tvv.value:=' => $_SESSION['cityName'],
        ));
    }else {
        $q->where(array(
            'tv.name' => 'price'
        ));
        $q->andCondition(array(
            'tvv.value:!=' => 0,
        ));
    }
}

/*
    Сортировка
*/
if(!empty($sortby)) {
    $sort = $modx->getOption('sort',$scriptProperties, $sortby);
    $dir = $modx->getOption('dir',$scriptProperties, $sortdir);
    $q->sortby($sort,$dir);
}

if (!empty($sortbyTV)) {
    $q->where(array(
        "tv.name" => trim($sortbyTV)  
    ));
    $q->sortby("tvv.value", $sortdirTV);
    // $q->prepare();
    // print $q->toSql();
}

/*
    Пагинация
*/
$total = $modx->getCount("modResource", $q);
$totalVar = $modx->getOption('totalVar', $scriptProperties, 'total');
$modx->setPlaceholder($totalVar,$total);
$limit = $modx->getOption('limit', $scriptProperties, 10);
$offset = $modx->getOption('offset', $scriptProperties, 0);
$q->limit($limit, $offset);

/* Количество найденных авто */
$modx->setPlaceholders(array(
    'count' => $total
),'auto.');

$resources = $modx->getCollection('modResource',$q);
foreach ($resources as $resourceId => $resource) {
    $templateVars = $resource->getMany('TemplateVars');
    $tvs = array();
    foreach ($templateVars as $tvId => $templateVar) {
        $value = $templateVar->getValue($resourceId);
        $tvs[$tvPrefix . $templateVar->get('name')] = $value;
    }
    $properties = array_merge(
        $scriptProperties
        ,array()
        ,$resource->toArray()
        ,$tvs
    );
    $output[] = $modx->getChunk($tpl, $properties);
}
return implode("\n", $output);