<?php

/**
 * This is the model class for table "article".
 *
 * The followings are the available columns in table 'article':
 * @property integer $id
 * @property string $title
 * @property string $slug
 * @property string $content
 * @property integer $create_datetime
 * @property integer $update_datetime
 * @property string $language
 * @property integer $hits
 * @property integer $status
 * @property integer $featured
 * @property string $image
 * @property integer $create_user_id
 * @property integer $update_user_id
 * @property string $attachment_url
 * @property string $attachment_title
 * @property string $background
 * @property string $en_title
 * @property string $en_content
 * @property string $description_ar
 * @property string $description_en
 * @property string $meta
 * @property string $flash_file
 *
 * The followings are the available model relations:
 * @property User $createUser
 * @property User $updateUser
 * @property Category[] $categories
 * @property ArticleAlbum[] $albumImages
 */
class Article extends FlexActiveRecord {

    public $published_time;

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

    /**
     * @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('published_time, update_datetime, title, en_title ,en_content, content, status,featured, create_user_id, update_user_id,description_ar, description_en', 'required','on'=>'ceate'),
            // array('published_time,update_datetime','required','on'=>'ceate'),
            // array('update_datetime','numerical', 'integerOnly' => true,'on'=>'ceate'),
            array('hits,status,featured, create_user_id, update_user_id', 'numerical', 'integerOnly' => true,'on'=>'ceate'),
            array('published_time', 'date', 'format' => 'dd-MM-yyyy'),
            array('title, en_title', 'length', 'max' => 200),
            array('en_title ,en_content, meta', 'safe'),
            array('flash_file', 'length', 'max'=>500),
            array('language', 'length', 'max' => 2),
            array('flash_file', 'file', 'types' => 'swf,flv', 'maxSize' => 1024 * 1024 * 15 /* 15MB */, 'allowEmpty' => true, 'safe' => true),
            array('image', 'file', 'types' => 'jpg,jpeg,png,gif', 'maxSize' => 1024 * 1024 * 15 /* 15MB */,
                  
                  'allowEmpty' => true, 'safe' => true,  'on'=>'insert,update'),
                  
             array('description_ar', 'length', 'max'=>200 ,'message'=>'Please enter a value for {description_ar} no more than 200 charcter.'),
            array(' description_en', 'length', 'max'=>200 ,'message'=>'Please enter a value for {description_en} no more than 200 charcter.'),
            array('attachment_url', 'file', 'types' => 'pdf', 'maxSize' => 1024 * 1024 * 300 /* 15MB */, 'allowEmpty' => true, 'safe' => true),
            array('slug,categories,published_time', 'safe'),
            array('published_time','safe','on'=>'deletepdf'),
            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('id, title, slug, content, create_datetime, update_datetime, language, hits, status,featured, image, create_user_id, update_user_id, en_title, en_content, attachment_title, description_ar, description_en,flash_file', 'safe', 'on' => 'search'),
        );
    }

    public function beforeValidate() {
        if ($this->isNewRecord) {
            $this->create_datetime = strtotime($this->published_time);
            // set the create date, last updated date and the user doing the creating  
            $this->update_datetime = time();
            $this->create_user_id = Yii::app()->user->id;
            $this->update_user_id = Yii::app()->user->id;
        } else {
            $this->create_datetime = strtotime($this->published_time);
            $this->update_datetime = strtotime($this->published_time);
            //not a new record, so just set the last updated time and last updated user id     
            if (Yii::app()->user !== NULL && Yii::app()->user->id) {
                $this->update_user_id = Yii::app()->user->id;
            }
        }
        return parent::beforeValidate();
    }

    /*public function defaultScope() {
        return array('order' => 'featured DESC, create_datetime desc');
    }*/

    public function scopes() {
        return array(
            'published' => array(
                'condition' => 'status=1',
            ),
            'filterLanguage' => array(
                'condition' => "t.language='" . Yii::app()->language . "'",
            ),
        );
    }

    /**
     * @return array relational rules.
     */
    public function relations() {
        // NOTE: you may need to adjust the relation name and the related
        // class name for the relations automatically generated below.
        return array(
            'albumImages' => array(self::HAS_MANY, 'ArticleAlbum', 'article_id'),
            'createUser' => array(self::BELONGS_TO, 'User', 'create_user_id'),
            'updateUser' => array(self::BELONGS_TO, 'User', 'update_user_id'),
            'categories' => array(self::MANY_MANY, 'Category', 'article_has_category(article_id, category_id)'),
        );
    }

    public function behaviors() {
        return array(
            'FStatusBehavior' => array('class' => 'FStatusBehavior'),
            'activerecord-relation' => array(
                'class' => 'EActiveRecordRelationBehavior',
            )
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id' => Yii::t('admin', 'ID'),
            'title' => Yii::t('admin', 'Title'),
            'content' => Yii::t('admin', 'Content'),
            'create_datetime' => Yii::t('admin', 'Create Datetime'),
            'update_datetime' => Yii::t('admin', 'Update Datetime'),
            'language' => Yii::t('admin', 'Language'),
            'hits' => Yii::t('admin', 'Hits'),
            'categories' => Yii::t('admin', 'Categories'),
            'image' => Yii::t('admin', 'Image'),
            'background' => Yii::t('admin', 'Background'),
            'status' => Yii::t('admin', 'Status'),
            'featured' => Yii::t('admin', 'Featured'),
            'create_user_id' => Yii::t('admin', 'Create User'),
            'update_user_id' => Yii::t('admin', 'Update User'),
            'attachment_title' => Yii::t('admin', 'Attachment Title'),
            'attachment_url' => Yii::t('admin', 'Attachment URL'),
            'en_content'=> Yii::t('admin', 'en_content'),
            'en_titlet'=> Yii::t('admin', 'en_title'),
            'description_ar' => Yii::t('admin','Description Ar'),
            'description_en' => Yii::t('admin','Description En'),
            'meta' => Yii::t('admin', 'Meta'),
            'flash_file' => Yii::t('admin','Flash File'),
        );
    }

    /**
     * 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() {
        return new CActiveDataProvider($this, array(
            'criteria' => $this->searchCriteria(),
        ));
    }

    public function frontendSearch() {
        $criteria = $this->searchCriteria();
        $criteria->scopes = 'published';
        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
            'pagination' => array(
                'pageSize' => 10,
            )
        ));
    }

    public function searchCriteria() {
        // @todo Please modify the following code to remove attributes that should not be searched.

        $criteria = new CDbCriteria;

        if ($this->categories) {
            $criteria->together = true;
            $criteria->with = array('categories');
            $criteria->addInCondition('categories.id', array($this->categories));
        }

        $criteria->compare('t.id', $this->id);
        $criteria->addSearchCondition('t.title', $this->title, true, "OR");
        $criteria->addSearchCondition('t.content', $this->content, true, "OR");
        $criteria->compare('t.create_datetime', $this->create_datetime);
        $criteria->compare('t.update_datetime', $this->update_datetime);
        $criteria->compare('t.language', $this->language, true);
        $criteria->compare('t.hits', $this->hits);
        $criteria->compare('t.status', $this->status);
        $criteria->compare('t.featured', $this->featured);
        $criteria->compare('t.create_user_id', $this->create_user_id);
        $criteria->compare('t.update_user_id', $this->update_user_id);
        $criteria->compare('t.en_title', $this->en_title, true);
        $criteria->compare('t.en_content', $this->en_content, true);
        $criteria->compare('t.meta', $this->meta, true);
        $criteria->compare('flash_file',$this->flash_file,true);
        

        return $criteria;
    }

    /**
     * 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 Article the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    public function getImageUrl($thumb = true) {
        return Yii::app()->params['uploadUrl'] . get_class($this) . '/' . ($thumb ? 'thumb/' : '') . $this->logo;
    }

    public function getThumbnailSizes() {
        return array(
            'thumb' => array(450, 250),
        );
    }

    public function getCategories() {
        $categories = array();
        foreach ($this->categories as $category) {
            $categories[] = $category->title;
        }
        return implode(" , ", $categories);
    }

    public function getCategoriesLinks() {
        $categories = array();
        foreach ($this->categories as $category) {
            $categories[] = CHtml::link($category->title, array('article/category', 'slug' => $category->slug));
        }
        return implode(" , ", $categories);
    }

    public function getFeaturedOptions() {
        return array(
            0 => Yii::t('admin', 'No'),
            1 => Yii::t('admin', 'Yes'),
        );
    }

    public function getFeaturedLabel($status) {
        $statuses = $this->getFeaturedOptions();
        if (isset($statuses[$status])) {
            return $statuses[$status];
        }
        return false;
    }

    public function getBreadcrumb() {
        Yii::app()->setLanguage(isset(Yii::app()->session['lang']) ? Yii::app()->session['lang'] : 'ar'); 
        $lang=Yii::app()->getLanguage();
         $result="";
         foreach ($this->categories as $category) {
            $result= '<span class="page-title">'.CHtml::link(($lang=='ar'?$category->title:$category->en_title), array('article/category', 'slug' => $category->slug)).'</span> >';
            if($category->parent!=null) 
             $result= '<span class="page-title"> '.CHtml::link(($lang=='ar'?$category->parent->title:$category->parent->en_title), array('article/category', 'slug' => $category->parent->slug)).'</span> >'.$result; 
         }
       return $result;
    }

    public function setAttributes($values, $safeOnly = true) {
        if (isset($values['slug']) && isset($values['title'])) {
            $slug = trim($values['slug']);
            $title = trim($values['title']);

            if (strlen($slug) === 0) {
                $values['slug'] = Common::sanitize($title);
            }
        }
        parent::setAttributes($values, $safeOnly);
    }

       public static function get_str_by_index_space($string, $space_num) {
        $result = '';
        $array = explode(' ', $string);
        //  var_dump ($array);
        if (sizeof($array) > $space_num) {

            for ($i = 0; $i < $space_num; $i++) {
                $result = $result . ' ' . $array[$i];
            }
        } else {
            $result = $string;
        }
        return $result;
    }

}
