<?php
/* * ********************************************************************************************
 * 								Open Real Estate
 * 								----------------
 * 	version				:	V1.29.2
 * 	copyright			:	(c) 2016 Monoray
 * 							http://monoray.net
 * 							http://monoray.ru
 *
 * 	website				:	http://open-real-estate.info/en
 *
 * 	contact us			:	http://open-real-estate.info/en/contact-us
 *
 * 	license:			:	http://open-real-estate.info/en/license
 * 							http://open-real-estate.info/ru/license
 *
 * This file is part of Open Real Estate
 *
 * ********************************************************************************************* */

namespace application\modules\seo\repositories;


use SeoFriendlyUrlSearch;
use MetroStations;
use Lang;
use Yii;

class SeoSearchRepository
{
    private $seoSearchModel;

    private $replace;

    private $country_id;
    private $region_id;
    private $city_id;
    private $metro_id;
    private $ap_type;
    private $obj_type_id;

    private $variantSearch = [];

    public function __construct()
    {
        $this->initSearchParam();

        if(param('useSeoSearchConfigByLink')){
            if(strpos(Yii::app()->request->url, 'search?') !== false){
                $lang = Yii::app()->language;
                $replace = Yii::app()->baseUrl . ($lang == Lang::getDefaultLang() ? '/' : '/' . $lang . '/');
                $url = str_replace($replace, '', Yii::app()->request->url);

                $dependency = new \CDbCacheDependency('SELECT MAX(date_updated) FROM '.SeoFriendlyUrlSearch::model()->tableName().' WHERE type='.SeoFriendlyUrlSearch::TYPE_BY_URL);

                $this->seoSearchModel = SeoFriendlyUrlSearch::model()->cache(param('cachingTime', 86400), $dependency)->find('url = :url AND type = 1', array(':url' => $url));
            }
        }

        if(param('useSeoSearchConfigBySearch') && !$this->seoSearchModel){
            $this->genVariantSearch();
        }

        if($this->seoSearchModel){
            $this->initReplacer();
        }
    }

    public function getSearchModel()
    {
        return $this->seoSearchModel;
    }

    private function genVariantSearch(){

        $data = [
            'type' => SeoFriendlyUrlSearch::TYPE_BY_SEARCH,
            'ap_type' => $this->ap_type,
            'obj_type_id' => $this->obj_type_id,
            'geo_coverage' => 0,
        ];

        if($this->metro_id){
            $data['geo_coverage'] = SeoFriendlyUrlSearch::GEO_METRO;
        } elseif ($this->city_id){
            $data['geo_coverage'] = SeoFriendlyUrlSearch::GEO_CITY;
        } elseif ($this->region_id){
            $data['geo_coverage'] = SeoFriendlyUrlSearch::GEO_REGION;
        } elseif ($this->country_id){
            $data['geo_coverage'] = SeoFriendlyUrlSearch::GEO_COUNTRY;
        }

        $this->variantSearch[] = $data;

        $this->getAllVariantSearch($data);

        // убираем дубли
        $this->variantSearch = array_map("unserialize", array_unique(array_map("serialize", $this->variantSearch)));

        $this->variantSearch = array_reverse($this->variantSearch);

        // находим модель по вариантам
        if($this->variantSearch){
            $cacheKey = md5(serialize($this->variantSearch));

            $cacheId = (int) Yii::app()->cache->get($cacheKey);
            if($cacheId){
                $this->seoSearchModel = SeoFriendlyUrlSearch::model()->findByPk($cacheId);
            } else {
                $data = array_pop($this->variantSearch);
                $this->seoSearchModel = $this->getSearchModelByData($data);

                if($this->seoSearchModel){
                    $dependency = new \CDbCacheDependency('SELECT MAX(date_updated) FROM '.$this->seoSearchModel->tableName().' WHERE type='.SeoFriendlyUrlSearch::TYPE_BY_SEARCH);

                    Yii::app()->cache->set($cacheKey, $this->seoSearchModel->id, param('cachingTime', 86400), $dependency);
                }
            }
        }
    }

    private function getAllVariantSearch($search){

        // ap_type, obj_type_id, geo_coverage (Тип сделки, Тип недвижимости, Рсположение)
        $mask = [
            [1,1,0],
            [1,0,1],
            [1,0,0],
            [0,1,1],
            [0,1,0],
            [0,0,1],
            [0,0,0],
        ];

        foreach ($mask as $row)
        {
            $searchTemp = $search;
            if(!$row[2]){
                $searchTemp['geo_coverage'] = 0;
            }
            if(!$row[1]){
                $searchTemp['obj_type_id'] = 0;
            }
            if(!$row[0]){
                $searchTemp['ap_type'] = 0;
            }

            $this->variantSearch[] = $searchTemp;
        }
    }

    private function getSearchModelByData($data){
        $model = null;

        $model = SeoFriendlyUrlSearch::model()->findByAttributes($data);

        if(count($this->variantSearch) >= 1){
            if(!$model){
                $data = array_pop($this->variantSearch);

                return $this->getSearchModelByData($data);
            }
        }

        return $model;
    }


    private function initSearchParam()
    {
        if(issetModule('location')){
            $this->country_id = (int) Yii::app()->request->getParam('country');
            $this->region_id = (int) Yii::app()->request->getParam('region');
            $this->city_id = (int) Yii::app()->request->getParam('city');
        }

        if(issetModule('metroStations')){
            $metroArr = Yii::app()->request->getParam('metro');
            $this->metro_id = (isset($metroArr[0]) && $metroArr[0] > 0) ? (int) $metroArr[0] : 0;
        }

        $this->ap_type = Yii::app()->request->getParam('apType', 0);
        $this->obj_type_id = (int) Yii::app()->request->getParam('objType', 0);
    }

    private function initReplacer()
    {
        $this->replace = array(
            '{country}' => '',
            '{region}' => '',
            '{city}' => '',
            '{metro}' => '',
            '{type_deal}' => '',
            '{type_estate}' => '',
        );

        if($this->country_id){
            $country = \Country::model()->findByPk($this->country_id);

            if($country){
                $this->replace['{country}'] = $country->getName();
            }
        }

        if($this->region_id){
            $region = \Region::model()->findByPk($this->region_id);

            if($region){
                $this->replace['{region}'] = $region->getName();
            }
        }

        if($this->city_id){
            $city = \City::model()->findByPk($this->city_id);

            if($city){
                $this->replace['{city}'] = $city->getName();
            }
        }

        if($this->metro_id){
            $metro = MetroStations::model()->findByPk($this->metro_id);

            if($metro){
                $this->replace['{metro}'] = $metro->getName();
            }
        }

        $objTypes = \CArray::merge(array(0 => tc('All')), \ApartmentObjType::getList());
        $typeList = \CArray::merge(array(0 => tc('All')), \HApartment::getTypesForSearch(false, false));

        if($this->obj_type_id && isset($objTypes[$this->obj_type_id])){
            $this->replace['{type_estate}'] = $objTypes[$this->obj_type_id];
        }

        if($this->ap_type && isset($typeList[$this->ap_type])){
            $this->replace['{type_deal}'] = $typeList[$this->ap_type];
        }
    }

    public function parse($str, $encode = true)
    {
        if($this->replace){
            $str = str_replace(array_keys($this->replace), array_values($this->replace), $str);
        }

        if($encode){
            return \CHtml::encode($str);
        } else {
            return $str;
        }
    }

}