<?php
/**
 * IMPORTANT NOTE
 * The code of this system is closed and a private proprietary of Flex Solutions.
 * A written authorization/license from Flex Solutions is required before using or modifying this code.
 * Email: sales@flexsolution.biz, Phone: +962795342585, Website: http://www.flexsolutions.biz
 */
 

/**
 * This is the model class for table "item_request_header".
 *
 * The followings are the available columns in table 'item_request_header':
 * @property string $id
 * @property integer $location_id
 * @property integer $pos_id
 * @property integer $user_id
 * @property integer $department_id
 * @property string $date_time
 * @property integer $cancelled
 * @property integer $created_by
 * @property string $created_date
 * @property integer $last_edited_by
 * @property string $last_edited_date
 *
 * The followings are the available model relations:
 * @property ItemRequestDetail[] $itemRequestDetails
 * @property Location $location
 * @property Pos $pos
 * @property User $user
 * @property Department $department
 */
class ItemRequestHeader extends LsmsActiveRecord {

    public $items_detail_array;

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

    /**
     * @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('id, location_id, user_id, department_id, date_time', 'required'),
	    array('location_id, user_id, department_id, cancelled', 'numerical', 'integerOnly' => true),
	    array('id', 'length', 'max' => 25),
	    array('items_detail_array', 'validateOneItemAtLeast', 'on' => 'add'),
	    // The following rule is used by search().
	    // @todo Please remove those attributes that should not be searched.
	    array('id, location_id, user_id, department_id, date_time, cancelled, created_by, created_date, last_edited_by, last_edited_date', '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(
	    'itemRequestDetails' => array(self::HAS_MANY, 'ItemRequestDetail', 'item_request_header_id'),
	    'location' => array(self::BELONGS_TO, 'Location', 'location_id'),
	    'user' => array(self::BELONGS_TO, 'User', 'user_id'),
	    'department' => array(self::BELONGS_TO, 'Department', 'department_id'),
	);
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
	return array(
	    'id' => 'ID',
	    'location_id' => Yii::t('default', 'Location'),
	    'user_id' => Yii::t('default', 'User'),
	    'department_id' => Yii::t('default', 'Department'),
	    'date_time' => Yii::t('default', 'Date Time'),
	    'cancelled' => Yii::t('default', 'Cancelled'),
	);
    }

    /**
     * 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 = $this->ModelCriteria();

	$pageSize = $this->yiiparam('pageSize');
	$sort = new CSort;
	$sort->defaultOrder = 'date_time Desc';
	return new CActiveDataProvider($this, array(
	    'pagination' => array('pageSize' => $pageSize,),
	    'criteria' => $criteria,
	    'sort'=>$sort
	));
    }
    
    public function ModelCriteria(){
	$criteria = new CDbCriteria;
	//$criteria->with = array('location', 'department', 'user');
	$criteria->compare('t.id', $this->id, true);
	$criteria->compare('t.location_id', $this->location_id);
	$criteria->compare('t.user_id', $this->user_id);
	$criteria->compare('t.department_id', $this->department_id);
	$criteria->compare('t.date_time', $this->date_time, true);
	$criteria->compare('cancelled', $this->cancelled);
	
	$criteria->join = 'inner join location on location.id = t.location_id'
		. ' inner join department on department.id = t.department_id'
		. ' inner join user on user.id = t.user_id';
	
	if(!Yii::app()->user->checkAccess('Super Admin')){
	    $ids = User::getIdsOfDepartments();
	    if((is_string($ids)))
		$criteria->addCondition('t.department_id in ('.$ids.')');
	    else 
		$criteria->addCondition('t.department_id ='.$ids);
	}
	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 ItemRequestHeader the static model class
     */
    public static function model($className=__CLASS__) {
	return parent::model($className);
    }

    protected function beforeValidate() {
	if ($this->isNewRecord) {
	    $this->id = "I_" . date("YmdHis");
	    $this->cancelled = 0;
	    $this->user_id = Yii::app()->user->id;
	}
	return parent::beforeValidate();
    }

    /*
     * The following validation is responsible for check max Served Meals is in range that limited at badge type
     *
     */

    public function validateOneItemAtLeast($attribute, $params) {
	if (!isset($this->items_detail_array) || empty($this->items_detail_array)) {

	    $this->addError($attribute, Yii::t('default', 'You have to select the items first'));
	    return;
	}
	$array = json_decode($this->items_detail_array);
	if (count($array) > 20) {
	    $this->addError($attribute, Yii::t('default', 'The maximum allowed number of items in one request is 20'));
	    return;
	} else {
	    $is_all_null = true;
	    
	    //if the user add items and then delete all of them, then the array will not be empty but its elements are all null
	    foreach ($array as $item) {
		if ($item != null) {
		    $is_all_null = false;
		    break;
		}
	    }
	    if ($is_all_null)
		$this->addError($attribute, Yii::t('default', 'You have to select the items first'));
	}
    }
    
    public function exportToExcel($name, $model, $header, $column, $criteria_real = null) {
	$criteria = ($criteria_real != null) ? $criteria_real : new CDbCriteria;
	if ($column == '') {
	    $criteria->addCondition('id = -1');
	}
	else
	    $criteria->select = $column;
	$data = $model->commandBuilder->createFindCommand(
			$model->tableName(), $criteria)->queryAll();
	array_unshift($data, $header);
	ob_clean();
	Yii::import('application.extensions.phpexcel_test.JPhpExcel');
	$xls = new JPhpExcel('UTF-8', false, $name);
	$xls->addArray($data);
	$xls->generateXML($name);
    }

}
