<?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 "ticket".
 *
 * The followings are the available columns in table 'ticket':
 * @property string $id
 * @property integer $badge_id
 * @property integer $person_id
 * @property string $date_time
 * @property integer $schedule_id
 * @property integer $pos_id
 * @property integer $quantity
 * @property integer $user_id
 * @property integer $department_id
 * @property integer $issuing_reason_id
 * @property integer $cancelled
 * @property integer $issued_at_server
 *
 * The followings are the available model relations:
 * @property Badge $badge
 * @property Department $department
 * @property IssuingReason $issuingReason
 * @property Person $person
 * @property Pos $pos
 * @property Schedule $schedule
 * @property User $user
 */
class Ticket extends CActiveRecord {

    public $ticket_type;
    public $location;

    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Ticket the static model class
     */
    public static function model($className=__CLASS__) {
	return parent::model($className);
    }

    protected function afterFind() {
	if ($this->badge == '') {
	    $this->ticket_type = yii::t('default', 'Department');
	} else {
	    $this->ticket_type = yii::t('default', 'Person');
	}
	$this->location = $this->department->location_id;
	parent::afterFind();
    }

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

    /**
     * @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('date_time, schedule_id, pos_id, quantity, user_id, department_id', 'required'),
	    array('issuing_reason_id', 'required', 'on' => 'CreateDepartmentTicketAtServer'),
	    //Schedule validation day
	    array('date_time', 'scheduleDayValidate', 'on' => 'CreateDepartmentTicketAtServer'),
	    array('badge_id, person_id, schedule_id, pos_id, quantity, user_id, department_id, issuing_reason_id', 'numerical', 'integerOnly' => true),
	    array('id', 'length', 'max' => 25),
	    array('id, badge_id, person_id, date_time, schedule_id, pos_id, quantity, user_id, department_id, issuing_reason_id,cancelled,issued_at_server,ticket_type', 'safe'),
	    // The following rule is used by search().
	    // Please remove those attributes that should not be searched.
	    array('id, badge_id, person_id, date_time, schedule_id, pos_id, quantity, user_id, department_id, issuing_reason_id,cancelled,issued_at_server,ticket_type', '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(
	    'badge' => array(self::BELONGS_TO, 'Badge', 'badge_id'),
	    'department' => array(self::BELONGS_TO, 'Department', 'department_id'),
	    'issuingReason' => array(self::BELONGS_TO, 'IssuingReason', 'issuing_reason_id'),
	    'person' => array(self::BELONGS_TO, 'Person', 'person_id'),
	    'pos' => array(self::BELONGS_TO, 'Pos', 'pos_id'),
	    'schedule' => array(self::BELONGS_TO, 'Schedule', 'schedule_id'),
	    'user' => array(self::BELONGS_TO, 'User', 'user_id'),
	);
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels() {
	return array(
	    'id' => 'ID',
	    'badge_id' => 'Badge',
	    'person_id' => 'Person',
	    'date_time' => 'Date Time',
	    'schedule_id' => 'Schedule',
	    'pos_id' => 'POS',
	    'quantity' => 'Quantity',
	    'user_id' => 'User',
	    'department_id' => 'Department',
	    'issuing_reason_id' => 'Reason',
	    'cancelled' => 'Cancelled',
	    'issued_at_server' => 'Issued At Server',
	);
    }

    /**
     * Retrieves a list of models based on the current search/filter conditions.
     * @return CActiveDataProvider the data provider that can return the models based on the search/filter conditions.
     */
    public function search() {
	// Warning: Please modify the following code to remove attributes that
	// should not be searched.

	$criteria = new CDbCriteria;

	$criteria->compare('t.id', $this->id, true);
	$criteria->compare('date_time', $this->date_time, true);
	$criteria->compare('schedule.name', $this->schedule_id, true);
	$criteria->compare('pos.name', $this->pos_id, true);
	$criteria->compare('quantity', $this->quantity);
	$criteria->compare('t.user_id', $this->user_id);
	$criteria->compare('department.name', $this->department_id, true);
	$criteria->compare('issuingReason.reason', $this->issuing_reason_id, true);
	$criteria->compare('cancelled', $this->cancelled);
	$criteria->compare('issued_at_server', $this->issued_at_server);

	if ($this->ticket_type == yii::t('default', 'Department')) {
	    $criteria->addCondition('badge_id IS  NULL');
	} else if ($this->ticket_type == yii::t('default', 'Person')) {
	    $criteria->addCondition('badge_id IS NOT NULL');
	}

	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);
	}

	$pageSize = Yii::app()->params['pageSize'];
	return new CActiveDataProvider($this, array(
	    'pagination' => array('pageSize' => $pageSize,),
	    'criteria' => $criteria,
	    'sort' => array(
		'defaultOrder'=>'date_time Desc',
		'attributes' => array(
		    '*',
		    'ticket_type' => array(
			'asc' => 'badge_id',
			'desc' => 'badge_id DESC',
		    ),
	    )),
	));
    }

    public function scheduleDayValidate($attribute, $params) {
	if ($this->date_time != "") {
	    $schedule_id = $this->schedule_id;
	    if ($schedule_id == null) { // we can't validate the date until the schedule is selected
		return;
	    }
	     $date_format = DateTime::createFromFormat('Y-m-d', $this->date_time);
	    if ($date_format && $date_format->format('Y-m-d') != $this->date_time || !$date_format)
	    {
		$this->addError($attribute, Yii::t('default', 'The Date is not a valid date {n}', $this->date_time));
		return;
	    }
	    $schedule_model = Schedule::model()->findByPk($schedule_id);
	    //complete date field with time
	    $this->date_time = $this->concat_date_and_Time($this->date_time, $schedule_model->start_time);
	    $ticket_day = date('D', strtotime($this->date_time));
	    if ($ticket_day == 'Sat') {
		if ($schedule_model->sat == 0)
		    $this->addError($attribute, Yii::t('default', 'The schedule ({n}) is not avalable on (Saturday)', $schedule_model->name));
	    }
	    else if ($ticket_day == 'Sun') {
		if ($schedule_model->sun == 0)
		    $this->addError($attribute, Yii::t('default', 'The schedule ({n}) is not avalable on (Sunday)', $schedule_model->name));
	    }
	    else if ($ticket_day == 'Mon') {
		if ($schedule_model->mon == 0)
		    $this->addError($attribute, Yii::t('default', 'The schedule ({n}) is not avalable on (Monday)', $schedule_model->name));
	    }
	    else if ($ticket_day == 'Tue') {
		if ($schedule_model->tue == 0)
		    $this->addError($attribute, Yii::t('default', 'The schedule ({n}) is not avalable on (Tuesday)', $schedule_model->name));
	    }
	    else if ($ticket_day == 'Wed') {
		if ($schedule_model->wed == 0)
		    $this->addError($attribute, Yii::t('default', 'The schedule ({n}) is not avalable on (Wednesday)', $schedule_model->name));
	    }
	    else if ($ticket_day == 'Thu') {
		if ($schedule_model->thu == 0)
		    $this->addError($attribute, Yii::t('default', 'The schedule ({n}) is not avalable on (Thursday)', $schedule_model->name));
	    }
	    else if ($ticket_day == 'Fri') {
		if ($schedule_model->fri == 0)
		    $this->addError($attribute, Yii::t('default', 'The schedule ({n}) is not avalable on (Friday)', $schedule_model->name));
	    }   
	}
    }

    //concating between date and time in one variable
    public function concat_date_and_Time($date, $time) {
	$_time = date_create($time);
	$_time = date_format($_time, 'H:i:s');
	$_date = date_create($date);
	$_date = date_format($_date, 'Y-m-d');
	$dateTime = $_date . ' ' . $_time;
	return $dateTime;
    }

}