<?php

/**
 * This is the model class for table "menu".
 *
 * The followings are the available columns in table 'menu':
 * @property integer $id
 * @property string $title
 * @property string $slug
 * @property integer $status
 * @property string $language
 * @property integer $create_datetime
 * @property integer $update_datetime
 * @property string $active_css_class
 * @property integer $encode_label
 * @property string $first_item_css_class
 * @property string $last_item_css_class
 * @property integer $hide_empty_items
 * @property string $item_css_class
 * @property string $item_template
 * @property string $link_label_wrapper
 * @property string $en_title
 *
 * The followings are the available model relations:
 * @property MenuItem[] $menuItems
 */
class Menu extends CActiveRecord {

    public $optionColumns = array(
        'active_css_class',
        'encode_label',
        'first_item_css_class',
        'last_item_css_class',
        'hide_empty_items',
        'item_css_class',
        'item_template',
        'link_label_wrapper',
    );

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

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

    protected function beforeSave() {
        if (is_string($this->link_label_wrapper) && strlen($this->link_label_wrapper) === 0) {
            $this->link_label_wrapper = NULL;
        }
        if (strlen($this->slug) == 0) {
            $this->slug = Common::sanitize($this->title);
        }
        return parent::beforeSave();
    }

    public function scopes() {
        return array(
            'published' => array(
                'condition' => 'status=1',
            ),
        );
    }

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

    /**
     * @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,slug, create_datetime, update_datetime,status', 'required'),
            array('status, create_datetime, update_datetime, encode_label, hide_empty_items', 'numerical', 'integerOnly' => true),
            array('title, slug, en_title', 'length', 'max' => 100),
            array('language', 'length', 'max' => 2),
            array('active_css_class, first_item_css_class, last_item_css_class, item_css_class, link_label_wrapper', 'length', 'max' => 45),
            array('item_template', 'length', 'max' => 200),
            // The following rule is used by search().
// @todo Please remove those attributes that should not be searched.
            array('id, title,slug, status, language, create_datetime, update_datetime, active_css_class, encode_label, first_item_css_class, last_item_css_class, hide_empty_items, item_css_class, item_template, link_label_wrapper', '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(
            'menuItems' => array(self::HAS_MANY, 'MenuItem', 'menu_id','order'=>'menuItems.sort'),
			'menuItemsFirstLevel' => array(self::HAS_MANY, 'MenuItem', 'menu_id','condition'=>'parent_id is null'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
        return array(
            'id' => Yii::t('admin', 'ID'),
            'title' => Yii::t('admin', 'Title'),
            'slug' => Yii::t('admin', 'Slug'),
            'status' => Yii::t('admin', 'Status'),
            'language' => Yii::t('admin', 'Language'),
            'create_datetime' => Yii::t('admin', 'Create Datetime'),
            'update_datetime' => Yii::t('admin', 'Update Datetime'),
            'active_css_class' => Yii::t('admin', 'Active Css Class'),
            'encode_label' => Yii::t('admin', 'Encode Label'),
            'first_item_css_class' => Yii::t('admin', 'First Item Css Class'),
            'last_item_css_class' => Yii::t('admin', 'Last Item Css Class'),
            'hide_empty_items' => Yii::t('admin', 'Hide Empty Items'),
            'item_css_class' => Yii::t('admin', 'Item Css Class'),
            'item_template' => Yii::t('admin', 'Item Template'),
            'link_label_wrapper' => Yii::t('admin', 'Link Label Wrapper'),
            'en_title' => Yii::t('admin','En Title'),
        );
    }

    /**
     * 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('slug', $this->slug, true);
        $criteria->compare('status', $this->status);
        $criteria->compare('language', $this->language, true);
        $criteria->compare('create_datetime', $this->create_datetime);
        $criteria->compare('update_datetime', $this->update_datetime);
        $criteria->compare('active_css_class', $this->active_css_class, true);
        $criteria->compare('encode_label', $this->encode_label);
        $criteria->compare('first_item_css_class', $this->first_item_css_class, true);
        $criteria->compare('last_item_css_class', $this->last_item_css_class, true);
        $criteria->compare('hide_empty_items', $this->hide_empty_items);
        $criteria->compare('item_css_class', $this->item_css_class, true);
        $criteria->compare('item_template', $this->item_template, true);
        $criteria->compare('link_label_wrapper', $this->link_label_wrapper, true);
        $criteria->compare('en_title',$this->en_title,true);

        return new CActiveDataProvider($this, array(
            'criteria' => $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 Menu the static model class
     */
    public static function model($className = __CLASS__) {
        return parent::model($className);
    }

    public function getItems() {
        $destMenuItems = array();
        if ($this->menuItems) {
            foreach ($this->menuItems as $srcItem) {

                $item = $srcItem->getOptions();


                if (isset($item['template']) && $item['template'] == '{menu}') { // remove the template if its the default value so the item can inhirt from base item menu
                    unset($item['template']);
                }

                $item['label'] = $srcItem->title;
                $item['url'] = $this->normalizeUrl($srcItem->link);
                if ($srcItem->parent_id !== NULL) {


                    if (!isset($destMenuItems[$srcItem->parent_id]['items'])) {
                        $destMenuItems[$srcItem->parent_id]['items'] = array();
                    }

                    array_push($destMenuItems[$srcItem->parent_id]['items'], $item);
                } else {

                    $destMenuItems[$srcItem->id] = $item;
                }
            }
        }
        return $destMenuItems;
    }

    public function normalizeUrl($url) {
        if (substr($url, 0, 1) !== '#') {
            $parsedUrl = parse_url($url);
            if ($parsedUrl && !isset($parsedUrl['host'])) {
                $url = Yii::app()->baseUrl . '/' . ltrim($url, '/');
            }
        }
        return $url;
    }

    public function getOptions() {

        $options = array();
        foreach ($this->optionColumns as $column) {
            $className = '';
            foreach (explode('_', $column) as $name) {
                if ($name !== '')
                    $className.=ucfirst($name);
            }
            $options[lcfirst($className)] = $this->$column;
        }

        return $options;
    }

}
