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

/**
 * This is the model class for table "{{carousel}}".
 *
 * The followings are the available columns in table '{{carousel}}':
 * @property integer $id
 * @property string $name
 * @property string $date_created
 * @property string $date_updated
 */
class Carousel extends ParentModel
{

    const STATUS_NOT_ACTIVE = 0;
    const STATUS_ACTIVE = 1;
    const STATUS_DRAFT = 3;

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

    /**
     * @return array validation rules for model attributes.
     */
    public function rules()
    {
        // NOTE: you should only define rules for those attributes that
        // will receive user inputs.
        return array(
            array('name', 'required'),
            array('name', 'length', 'max' => 255),
            array('status', 'numerical'),
            array('id, name, date_created, date_updated', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations()
    {
        return array(
            'images' => array(self::HAS_MANY, 'CarouselImages', 'carousel_id', 'order' => 'images.sorter ASC')
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'id' => 'ID',
            'name' => tc('Name'),
            'date_created' => 'Date Created',
            'date_updated' => 'Date Updated',
        );
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     *
     * Typical usecase:
     * - Initialize the model fields with values from filter form.
     * - Execute this method to get CActiveDataProvider instance which will filter
     * models according to data in model fields.
     * - Pass data provider to CGridView, CListView or any similar widget.
     *
     * @return CActiveDataProvider the data provider that can return the models
     * based on the search/filter conditions.
     */
    public function search()
    {
        $criteria = new CDbCriteria;

        $criteria->compare('id', $this->id);
        $criteria->compare('name', $this->name, true);
        $criteria->compare('date_created', $this->date_created, true);
        $criteria->compare('date_updated', $this->date_updated, true);

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

    /**
     * Returns the static model of the specified AR class.
     * Please note that you should have this exact method in all your CActiveRecord descendants!
     * @param string $className active record class name.
     * @return Carousel the static model class
     */
    public static function model($className = __CLASS__)
    {
        return parent::model($className);
    }

    public static function getUploadPath()
    {
        return Yii::getPathOfAlias('webroot.uploads.carousel');
    }

    public static function getUploadDir()
    {
        return Yii::app()->baseUrl . '/uploads/carousel';
    }

    public static function getMaxPhotos()
    {
        return param('carousel.max-photos', 10);
    }

    public static function parseText($text)
    {
        $req = '/{carousel-(\d{1,5}?)}/i';

        preg_match_all($req, $text, $match);

        if (isset($match[1])) {
            foreach ($match[1] as $id) {
                $carousel = Carousel::model()->findByPk($id);

                if ($carousel) {
                    $text = str_replace("{carousel-{$id}}", Yii::app()->controller->widget('application.modules.slider.components.CarouselViewWidget', array(
                        'model' => $carousel,
                    ), true), $text);
                } else {
                    $text = str_replace("{carousel-{$id}}", '', $text);
                }
            }
        }

        return $text;
    }

    public function getCode()
    {
        return '{carousel-' . $this->id . '}';
    }

    public function beforeDelete()
    {
        if ($this->images) {
            foreach ($this->images as $image) {
                $image->delete();
            }
        }

        $dirname = Carousel::getUploadPath() . DIRECTORY_SEPARATOR . $this->id;

        @array_map('unlink', glob("$dirname/*.*"));
        @rmdir($dirname);

        return parent::beforeDelete();
    }
}
