<?php
defined('_JEXEC') or die;
class CatalogModelFrontpage extends JModelItem
{
    private function item()
    {
        $db = $this->getDbo();
        $query = $db->getQuery(true);
        $published = $this->getState('filter.published', 1);
        $archived = $this->getState('filter.archived', 2);
        $app = JFactory::getApplication();
        $filter_post = $app->input->get('filter', '', 'post');
        $search_title = JFactory::getApplication()->input->post->get('search_title', '');
        var_dump($search_title);
        $sort = $app->input->get('sort', '', 'post');
        if (!empty($filter_post)) {
            $filter = array();
            for ($i = 0; $i < count($filter_post); $i++) {
                if (!in_array('0', $filter_post[$i])) {
                    if (is_numeric($filter_post[$i]['value'])) {
                        $filter[$filter_post[$i]['name']] = $filter_post[$i]['value'];
                    }
                }
            }
        }
        $query->select(
            'a.id AS id, ' .
            'a.title AS title, ' .
            'a.catid AS catid, ' .
            'a.unique_code AS unique_code, ' .
            'a.price AS price, ' .
            'a.floor AS floor, ' .
            'a.area AS area, ' .
            'a.params AS params, ' .
            'a.images AS images, ' .
            'a.options AS options, ' .
            'a.description AS description, ' .
            'm.id AS mid '
        );
        $query->from('#__catalog AS a')
            ->join('LEFT', '#__menu AS m ON a.title = m.title');
        $query->where('a.language in (' . $db->quote(JFactory::getLanguage()->getTag()). ',' . $db->quote('*'). ')')
            ->where('(a.state = ' . (int)$published . ' OR a.state = ' . (int)$archived . ')');
        if (!empty($filter_post)) {
            $query->where('(a.price >= ' . (int)$filter['price-min'] . ' AND a.price <= ' . (int)$filter['price-max'] . ')')
                ->where('(a.floor >= ' . (int)$filter['floor-min'] . ' AND a.floor <= ' . (int)$filter['floor-max'] . ')')
                ->where('(a.area >= ' . (int)$filter['area-min'] . ' AND a.area <= ' . (int)$filter['area-max'] . ')');
        }
        if(!empty($search_title)) {
            $query->where('a.title LIKE '.$db->Quote('%'.$db->escape($search_title, true).'%').'');
        }
        if (!empty($sort)) {
            $query->order('a.' . $sort);
        }
        $db->setQuery($query);
        return $db->loadObjectList();
    }
    
    private function newArray(){
         $array = array();
         $field = array();
         $rows = $this->item();
         for($i = 0; $i < count($rows); $i++){
                $params[$i]     = json_decode($rows[$i]->params, true);
                $images[$i]     = json_decode($rows[$i]->images, true);
                $options[$i]    = json_decode($rows[$i]->options, true);
                unset($params[$i]['stock-ico']);
                $field[$i] = array(
                    'id'            => $rows[$i]->id,
                    'title'         => $rows[$i]->title,
                    'catid'         => $rows[$i]->catid,
                    'unique_code'   => $rows[$i]->unique_code,
                    'price'         => $rows[$i]->price,
                    'floor'         => $rows[$i]->floor,
                    'area'          => $rows[$i]->area
                    );
                $array[$i] = array_merge($field[$i],$params[$i],$images[$i],$options[$i]);
            }
            return $array;
    }
    
    private function sortString($array){
        
        $app           = JFactory::getApplication();
        $filter_post   = $app->input->get('filter', '', 'post');
        
        $filter = array();
        $list   = array();
        $result = array();
        
        for($i = 0; $i < count($filter_post); $i++){
             
            if(!in_array('0', $filter_post[$i])){
                
                if(!is_numeric($filter_post[$i]['value'])){
                    
                    $filter[$filter_post[$i]['name']] = $filter_post[$i]['value'];    
                }  
            }
        }
        
        if(isset($filter)){ 
            
            $filter_count = count($filter);
            
            for($i = 0; $i < count($array); $i++){
                
                //Находим схождение массивов $filter и $array[$i]
                $comparison = array_intersect($filter,$array[$i]);
                    
                if(isset($comparison)){
                
                    foreach($comparison as $compare){
                        //Проверяем искомое значение в массиве $filter
                        if(in_array($compare,$filter)){
                            //Ищем ключи в массиве $filter
                            $key = array_search($compare,$filter);
                            //Создаем массив из id, совпадающих со значениями из $filter
                            if($filter[$key] == $array[$i][$key]){
           
                                $list[] = $array[$i]['id'];
                            }
                        }
                    }
                }
            }
        }
                
        //Подсчитать количество id в массиве $list 
        //Возвращаем массив ключами которого являются значения массива $list
        if(isset($list)){
            
            $values_count = array_count_values($list);
        }else{
            
            exit();
        }
        
        //Создаем массив схожими поля из $filter и $array  
        foreach($values_count as $key => $values){
            
            if($filter_count == $values){
                
              $result[] = $key;  
            }
        }
        
        if(!empty($result)){
            
            for($i = 0; $i <= count($array); $i++){
                
                if(isset($array[$i])){  
                  
                    foreach($result as $r){
                   
                        if(array_search($r,$array[$i])){
                    
                           if($array[$i]['id'] == $r){
                               
                               $output[] = $array[$i]; 
                          }
                        }
                    }    
                }  
            } 
      
            return $output;
            
        }elseif(empty($filter)){
            return $array;  
        }
    }
              
    function getView()
    {
        $app = JFactory::getApplication();
        $filter_post = $app->input->get('filter', '', 'post');
        $search_title = $app->input->get('search_title', '', 'post');
        $search = $app->input->get('search', '', 'post');
        if (!empty($filter_post)) {
            return $this->sortString($this->newArray());
        } else {
            return $this->newArray();
        }
    }
       
    function getCategory(){
            
            $db             = $this->getDbo();
            $query          = $db->getQuery(true);
            $app            = JFactory::getApplication();
            $itemid         = $app->input->getInt('Itemid', '');
            $published      = $this->getState('filter.published',1);
            $archived       = $this->getState('filter.archived',2);
                        
            $query->select(
			'a.id AS id, '.
			'a.title AS title, '.
                        'a.link  AS link, '.
			'a.params AS params '
		);
            
            $query->from('#__menu AS a');
            
            $query->where('a.language in (' . $db->quote(JFactory::getLanguage()->getTag()). ',' . $db->quote('*'). ')')
                ->where('(a.published = ' . (int) $published . ' OR a.published = ' . (int) $archived . ')')
                ->where('parent_id = "'.$itemid.'"');
            $query->order('a.lft');
            
            $db->setQuery($query);
            return $db->loadObjectList();
        }
        
        
    function getFilter()
    {
        $db = $this->getDbo();
        $query = $db->getQuery(true);
        $doc = JFactory::getDocument();
        $published = $this->getState('filter.published', 1);
        $archived = $this->getState('filter.archived', 2);
        $query->select(
            'a.id AS id, ' .
            'a.title AS title, ' .
            'a.catid  AS catid, ' .
            'a.type AS type, ' .
            'a.params AS params,' .
            'a.hidden AS hidden, ' .
            'a.filter AS filter'
        );
        $query->from('#__catalog_customoptions AS a');
        $query->where('(a.published = ' . (int)$published . ' OR a.published = ' . (int)$archived . ')');
        $query->order('a.ordering ASC');
        $db->setQuery($query);
        return $db->loadObjectList();
    }
         
}
?>