<?php
/* * ********************************************************************************************
 * 								Open Real Estate
 * 								----------------
 * 	version				:	V1.36.0
 * 	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
 *
 * ********************************************************************************************* */

class SeoFriendlyUrlHistory extends ParentModel
{

    public static $_availableModelSave = array(
        'UserAds' => 'Apartment',
        'Apartment' => 'Apartment',
        'InfoPages' => 'InfoPages',
        'Article' => 'Article',
        'Entries' => 'Entries',
    );

    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    public function tableName()
    {
        return '{{seo_friendly_url_history}}';
    }

    public function i18nFields()
    {
        return array(
            'url' => 'varchar(255) not null default ""',
        );
    }

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

        return $arr;
    }

    public function rules()
    {
        return array(
            array('model_name, model_id', 'required'),
            array('model_id', 'numerical', 'integerOnly' => true),
            array('model_name', 'length', 'max' => 30),
            array($this->getI18nFieldSafe(), 'safe'),
        );
    }

    public static function addSeoHistory(SeoFriendlyUrl $model)
    {
        if ($model->model_name && isset(SeoFriendlyUrlHistory::$_availableModelSave[$model->model_name])) {
            $modelHistory = new SeoFriendlyUrlHistory;

            foreach ($model->attributes as $attrName => $attrValue) {
                if ($modelHistory->hasAttribute($attrName) && $attrName != 'id') {
                    $modelHistory->setAttribute($attrName, $attrValue);
                }
            }

            $modelHistory->model_name = SeoFriendlyUrlHistory::$_availableModelSave[$model->model_name];
            $modelHistory->model_id = $model->model_id;
            $modelHistory->save(false);
        }
    }

    public static function getFromHistory($url = '', $modelName = '')
    {
        if ($url && $modelName && isset(SeoFriendlyUrlHistory::$_availableModelSave[$modelName])) {
            $modelName = SeoFriendlyUrlHistory::$_availableModelSave[$modelName];

            $urlField = 'url_' . Yii::app()->language;

            $sql = 'SELECT model_id FROM {{seo_friendly_url_history}} WHERE model_name=:model_name AND ' . $urlField . '=:url';
            $modelId = Yii::app()->db->createCommand($sql)->queryScalar(array(':model_name' => $modelName, ':url' => $url));

            if (!empty($modelId)) {
                $sql = 'SELECT * FROM {{seo_friendly_url_history}} WHERE model_id=:model_id ORDER BY id ASC';
                $result = Yii::app()->db->createCommand($sql)->queryAll(true, array(':model_id' => $modelId));

                # Последняя запись - последний url, который должен быть в таблице seo_friendly_url
                $lastElem = end($result);

                if (isset($lastElem['url_' . Yii::app()->language])) {
                    $lastUrl = $lastElem['url_' . Yii::app()->language];

                    if ($lastUrl) {
                        $model = CActiveRecord::model($modelName)->findByPk($modelId);

                        if (!empty($model)) {
                            if (method_exists($model, 'getUrl')) {
                                $modelUrl = $model->getUrl();

                                if ($modelUrl) {
                                    Yii::app()->controller->redirect($modelUrl, true, 301);
                                    Yii::app()->end(301, true);
                                }
                            }
                        }
                    }
                }
            }
        }

        return false;
    }
}
