<?php

/**
 * This is the model class for table "menu_item".
 *
 * The followings are the available columns in table 'menu_item':
 * @property integer $id
 * @property string $title
 * @property string $en_title
 * @property string $link
 * @property integer $link_target
 * @property integer $order
 * @property integer $visible
 * @property integer $menu_id
 * @property integer $parent_id
 * @property string $language
 * @property integer $create_datetime
 * @property integer $update_datetime
 * @property string $template
 * @property string $link_options
 * @property string $item_options
 * @property string $submenu_options
 * @property string $bg_color
 * @property string $head_color
 * @property string $border_color
 * @property integer $sort
 * @property string $image
 *
 * The followings are the available model relations:
 * @property Menu $menu
 * @property MenuItem $parent
 * @property MenuItem[] $menuItems
 */
class MenuItem extends CActiveRecord {

    public function defaultScope() {
        return array('order' => '`order` DESC');
    }

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

    /**
     * @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('title, menu_id', 'required'),
            array('order, visible, menu_id, parent_id, sort', 'numerical', 'integerOnly' => true),
            array('title, bg_color, head_color, border_color', 'length', 'max' => 100),
            array('link_target', 'length', 'max' => 8),
            array('en_title', 'length', 'max'=>255),
            array('image', 'file', 'types' => 'jpg,jpeg,png,gif', 'maxSize' => 1024 * 1024 * 15 /* 15MB */,
                  
                  'allowEmpty' => true, 'safe' => true,  'on'=>'insert,update'),
//            array('link', 'url', 'allowEmpty' => true, 'defaultScheme' => 'http'),
            array('link', 'length', 'max' => 250),
            array('template', 'length', 'max' => 300),
            array('language', 'length', 'max' => 2),
            array('link_options,item_options,submenu_options', 'safe'),
            // The following rule is used by search().
            // @todo Please remove those attributes that should not be searched.
            array('id, title, link, link_target, order, visible, menu_id, parent_id,language, bg_color, head_color, border_color, en_title', 'safe', 'on' => 'search'),
        );
    }

    /**
     * @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(
            'menu' => array(self::BELONGS_TO, 'Menu', 'menu_id'),
            'parent' => array(self::BELONGS_TO, 'MenuItem', 'parent_id'),
            'menuItems' => array(self::HAS_MANY, 'MenuItem', 'parent_id','order'=>'sort ASC'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id' => Yii::t('admin', 'ID'),
            'title' => Yii::t('admin', 'Link Title'),
            'en_title' => Yii::t('admin','En Title'),
            'link' => Yii::t('admin', 'Link'),
            'link_target' => Yii::t('admin', 'Link Target'),
            'order' => Yii::t('admin', 'Order'),
            'visible' => Yii::t('admin', 'Visible'),
            'menu_id' => Yii::t('admin', 'Menu'),
            'parent_id' => Yii::t('admin', 'Parent Link'),
            'bg_color' => Yii::t('admin','Bg Color'),
            'head_color' => Yii::t('admin','Head Color'),
            'border_color' => Yii::t('admin','Border Color'),
            'sort' => Yii::t('admin','Sort'),
            'image' => Yii::t('admin', 'Image'),
        );
    }

    /**
     * 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() {
        // @todo Please modify the following code to remove attributes that should not be searched.
        $criteria = new CDbCriteria;
        $criteria->compare('id', $this->id);
        $criteria->compare('title', $this->title, true);
        $criteria->compare('en_title',$this->en_title,true);
        $criteria->compare('link', $this->link, true);
        $criteria->compare('link_target', $this->link_target);
        $criteria->compare('order', $this->order);
        $criteria->compare('visible', $this->visible);
        $criteria->compare('menu_id', $this->menu_id);
        $criteria->compare('parent_id', $this->parent_id);
        $criteria->compare('bg_color',$this->bg_color,true);
		$criteria->compare('head_color',$this->head_color,true);
		$criteria->compare('border_color',$this->border_color,true);
        $criteria->compare('sort',$this->sort);
        return new CActiveDataProvider($this, array(
            'criteria' => $criteria,
            'pagination' => array(
                'pageVar' => 'page',
                'pageSize' => 20,
            ),
            'sort' => array(
                'sortVar' => 'sort',
            ),
        ));
    }

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

    public static function stripBaseUrl($data) {
        $return = false;
        $baseUrl = Yii::app()->getBaseUrl(false);
        $absoluteBaseUrl = Yii::app()->getBaseUrl(true);
        if (is_array($data)) {
            $return = array();
            foreach ($data as $url => $label) {
                $url = str_replace($absoluteBaseUrl, '', $url);
                $url = str_replace($baseUrl, '', $url);
                $return[$url] = $label;
            }
        } else {
            $return = str_replace($absoluteBaseUrl, '', $data);
            $return = str_replace($baseUrl, '', $return);
        }
        return $return;
    }

    public function getOptions() {

        $options = array(
            'visible' => $this->visible,
            'template' => '{menu}',
            'linkOptions' => array(),
            'itemOptions' => array(),
            'submenuOptions' => array(),
        );

        if (strlen($this->template)) {
            $options['template'] = $this->template;
        }
        if (is_array($this->item_options)) {
            $options['itemOptions'] = $this->item_options;
        }
        if (is_array($this->link_options)) {
            $options['linkOptions'] = $this->getLinkOptions();
        }
        if (strlen($this->link_target)) {
            $options['linkOptions']['target'] = $this->link_target;
        }
        if (is_array($this->submenu_options)) {
            $options['submenuOptions'] = $this->submenu_options;
        }

        return $options;
    }

    public static function getLinkTargetList() {
        return array(
            '_blank' => '_blank',
            '_parent' => '_parent',
            '_self' => '_self',
            '_top' => '_top',
        );
    }

    public function __get($name) {
        if (in_array($name, array('link_options'))) {
            $value = parent::__get($name);
            if (!is_array($value)) {
                return CJSON::decode(parent::__get($name));
            }
        }
        return parent::__get($name);
    }

    public function getItemOptions() {
        return CJSON::decode($this->item_options);
    }

    public function getSubmenuOptions() {
        return CJSON::decode($this->submenu_options);
    }

    protected function beforeValidate() {

        if ($this->link_options === NULL) {
            $this->link_options = array();
        }
        if (is_array($this->link_options)) {
            $this->link_options = CJSON::encode($this->link_options);
        }

        if ($this->item_options === NULL) {
            $this->item_options = array();
        }
        if (is_array($this->item_options)) {
            $this->item_options = CJSON::encode($this->item_options);
        }
        if ($this->submenu_options === NULL) {
            $this->submenu_options = array();
        }
        if (is_array($this->submenu_options)) {
            $this->submenu_options = CJSON::encode($this->submenu_options);
        }
        return parent::beforeSave();
    }

    public function getLinkOptions() {
        $options = array();
        if (isset($this->link_options['key']) && isset($this->link_options['value'])) {
            $keysCounts = count($this->link_options['key']);
            $valuesCounts = count($this->link_options['value']);
            for ($index = 0; $index < $valuesCounts && $index < $keysCounts; $index++) {
                if (isset($this->link_options['key']) && isset($this->link_options['key'][$index]) && isset($this->link_options['value']) && isset($this->link_options['value'][$index])) {
                    $key = $this->link_options['key'][$index];
                    $value = $this->link_options['value'][$index];
                    if ($key) {
                        $options[$key] = $value;
                    }
                }
            }
        }
        return $options;
    }

}
