<?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
 *
 * ********************************************************************************************* */

/**
 * This is the model class for table "{{seo_friendly_url}}".
 *
 * The followings are the available columns in table '{{seo_friendly_url}}':
 * @property integer $id
 * @property integer $type
 * @property integer $rooms
 * @property string $ap_type
 * @property integer $obj_type_id
 * @property integer $geo_coverage
 * @property string $url
 * @property string $canonical_url
 * @property integer $is_noindex
 * @property string $json_data
 * @property string $title_ru
 * @property string $title_en
 * @property string $description_ru
 * @property string $description_en
 * @property string $keywords_ru
 * @property string $keywords_en
 * @property string $date_created
 * @property string $date_updated
 */
class SeoFriendlyUrlSearch extends ParentModel
{

    const TYPE_BY_URL = 1;
    const TYPE_BY_SEARCH = 2;

    const GEO_COUNTRY = 1;
    const GEO_REGION = 2;
    const GEO_CITY = 3;
    const GEO_METRO = 4;

    public function behaviors()
    {
        $arr = array();
        $arr['AutoTimestampBehavior'] = array(
            'class' => 'zii.behaviors.CTimestampBehavior',
            'createAttribute' => 'date_created',
            'updateAttribute' => 'date_updated',
        );

        return $arr;
    }

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return SeoFriendlyUrlSearch the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    /**
     * @return string the associated database table name
     */
    public function tableName()
    {
        return '{{seo_friendly_url_search}}';
    }

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        return array(
            array('url', 'filter', 'filter'=>'trim'),
            array('url', 'validUrl'),
            array('is_noindex, obj_type_id, geo_coverage', 'numerical', 'integerOnly' => true),
            array($this->i18nRules('title'), 'length', 'max' => 255),
            array($this->i18nRules('description'), 'length', 'max' => 255),
            array($this->i18nRules('keywords'), 'length', 'max' => 255),
            array($this->i18nRules('h1'), 'length', 'max' => 255),
            array($this->getI18nFieldSafe() . ', canonical_url, ap_type', 'safe'),
            array('type', 'numerical', 'integerOnly' => true),
            array('id', 'safe', 'on' => 'search'),
        );
    }

    public function validUrl()
    {
        if($this->type == self::TYPE_BY_URL){
            if(!$this->url){
                $this->addError('url', tt('URL required', 'seo'));
                return false;
            }

            if($this->isNewRecord){
                $count = self::model()->count('url = :url', [':url' => $this->url]);
            } else {
                $count = self::model()->count('url = :url AND id != :id', [':url' => $this->url, ':id' => $this->id]);
            }

            if($count){
                $this->addError('url', tt('Matching has already been added for this search', 'seo'));
            }

            if(substr($this->url, 0, 6) !== "search"){
                $this->addError('url', tt('URL should start with "search", example - search?apType=1&objType=1', 'seo'));
            }

        } elseif($this->type == self::TYPE_BY_SEARCH) {
            $data = [
                'type' => self::TYPE_BY_SEARCH,
                'ap_type' => $this->ap_type,
                'obj_type_id' => $this->obj_type_id,
                'geo_coverage' => $this->geo_coverage,
            ];

            if($this->isNewRecord){
                $count = self::model()->findByAttributes($data);
            } else {
                $criteria = new CDbCriteria();

                $criteria->addColumnCondition($data);
                $criteria->addCondition('id != :id');
                $criteria->params[':id'] = $this->id;

                $count = self::model()->count($criteria);
            }

            if($count){
                $this->addError('url', tt('Matching has already been added for this search', 'seo'));
            }
        }
    }

    public function i18nFields()
    {
        return array(
            'title' => 'varchar(255) not null default ""',
            'description' => 'varchar(255) not null default ""',
            'keywords' => 'varchar(255) not null default ""',
            'h1' => 'varchar(255) not null default ""',
            'body' => 'text null',
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => 'ID',
            'url' => tt('URL', 'seo'),
            'title' => tt('meta Title', 'seo'),
            'description' => tt('meta Description', 'seo'),
            'keywords' => tt('meta Keywords', 'seo'),
            'is_noindex' => tt('meta robots noindex', 'seo'),
            'h1' => tt('H1', 'seo'),
            'body' => tt('Text', 'seo'),
            'type' => tt('Type', 'seo'),
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search()
    {
        $criteria = new CDbCriteria;
        $lang = Yii::app()->language;

        $criteria->compare($this->getTableAlias() . '.id', $this->id);
        $criteria->compare($this->getTableAlias() . '.type', $this->type);

        $criteria->compare($this->getTableAlias() . ".url", $this->url, true);
        $criteria->compare($this->getTableAlias() . ".title_{$lang}", $this->{'title_' . $lang}, true);

        $criteria->compare($this->getTableAlias() . '.type', array_keys($this->getTypeList()));

        return new CustomActiveDataProvider($this, array(
            'criteria' => $criteria,
            'sort' => array(
                'defaultOrder' => $this->getTableAlias() . '.id DESC',
            ),
            'pagination' => array(
                'pageSize' => param('adminPaginationPageSize', 20),
            ),
        ));
    }

    public function getUrlForTable()
    {
        $url = $alias = '';

        if ($this->type == self::TYPE_BY_URL) {
            $alias = $this->url;
            $url = Yii::app()->createAbsoluteUrl('/').'/'.$this->url;

            return CHtml::link($alias, $url);

        } elseif($this->type == self::TYPE_BY_SEARCH){
//            $data = [
//                'country' => 222,
//                'apType' => $this->ap_type,
//                'objType' => $this->obj_type_id,
//            ];
//
//            foreach ($data as $key => $val){
//                if(!$val){
//                    unset($data[$key]);
//                }
//            }
//
//            $alias =  $data ? '/search?'.http_build_query($data) : '';
//
//            $url = Yii::app()->createAbsoluteUrl('/').$alias;
            
            $objTypes = CArray::merge(array(0 => tc('All')), ApartmentObjType::getList());
            $typeList = CArray::merge(array(0 => tc('All')), HApartment::getTypesForSearch(false, false));
            $geoList = self::getGeographCoverageList();

            $data = [
                tc('Type') => isset($typeList[$this->ap_type]) ? $typeList[$this->ap_type] : tc('All'),
                tc('Property type') => isset($objTypes[$this->obj_type_id]) ? $objTypes[$this->obj_type_id] : tc('All'),
                tt('Location', 'apartments') => isset($geoList[$this->geo_coverage]) ? $geoList[$this->geo_coverage] : tc('All'),
            ];

            return implode('/', $data);
        }

        if($alias && $url){
            return CHtml::link($alias, $url);
        }

        return null;
    }

    private static $_models = array();

    public static function getCachedModel(CActiveRecord $model, $id)
    {
        if(!isset($_models[$model->tableName()][$id])){
            $_models[$model->tableName()][$id] = $model->findByPk($id);
        }

        return $_models[$model->tableName()][$id];
    }

    public function beforeValidate()
    {
        $absUrl = Yii::app()->createAbsoluteUrl('/').'/';

        $this->url = str_replace($absUrl, '', urldecode($this->url));
        $this->canonical_url = str_replace($absUrl, '', urldecode($this->canonical_url));

        if($this->type == self::TYPE_BY_SEARCH) {
            $this->is_noindex = 0;
            $this->canonical_url = '';
            $this->{'body_'.Yii::app()->language} = '';
        }

        return parent::beforeValidate();
    }

    public static function getTypeList()
    {
        $list = [];

        if(param('useSeoSearchConfigByLink')){
            $list[self::TYPE_BY_URL] = tt('By URL', 'seo');
        }
        if(param('useSeoSearchConfigBySearch')){
            $list[self::TYPE_BY_SEARCH] = tt('By search', 'seo');
        }

        return $list;
    }

    public function getTypeName()
    {
        return isset(self::getTypeList()[$this->type]) ? self::getTypeList()[$this->type] : null;
    }

    public static function getGeographCoverageList()
    {
        return [
            0 => tc('All'),
            self::GEO_COUNTRY => tc('Country'),
            self::GEO_REGION => tc('Region'),
            self::GEO_CITY => tc('City'),
            self::GEO_METRO => tt('Metro', 'apartments'),
        ];
    }
}
