<?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 "schedule".
 *
 * The followings are the available columns in table 'schedule':
 * @property integer $id
 * @property string $name
 * @property string $start_time
 * @property string $end_time
 * @property integer $sat
 * @property integer $sun
 * @property integer $mon
 * @property integer $tue
 * @property integer $wed
 * @property integer $thu
 * @property integer $fri
 * @property string $status
 * @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 PosSchedule[] $posSchedules
 * @property Ticket[] $tickets
 */
class Schedule extends LsmsActiveRecord
{


    /**
     * Returns the static model of the specified AR class.
     * @param string $className active record class name.
     * @return Schedule the static model class
     */
    // identifer have the days and the time as string value
    public $description;

    public static function model($className=__CLASS__)
    {
        return parent::model($className);
    }

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

    /**
     * @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('name, start_time, end_time, sat, sun, mon, tue, wed, thu, fri, status', 'required'),
            array('name', 'unique'),
            array('sat, sun, mon, tue, wed, thu, fri', 'numerical', 'integerOnly' => true),
            array('name', 'length', 'max' => 255),
            array('status', 'length', 'max' => 8),
            //Check If Start Time less Than End Time
            array('end_time', 'timeValidate'),
            // The following rule is used by search().
            // Please remove those attributes that should not be searched.
            array('id, name, start_time, end_time, sat, sun, mon, tue, wed, thu, fri, status, 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(
            'posSchedules' => array(self::HAS_MANY, 'PosSchedule', 'schedule_id'),
            'tickets' => array(self::HAS_MANY, 'Ticket', 'schedule_id'),
        );
    }

    /**
     * @return array customized attribute labels (name=>label)
     */
    public function attributeLabels()
    {
        return array(
            'name' => yii::t('default', 'Name'),
            'start_time' => yii::t('default', 'Start Time'),
            'end_time' => yii::t('default', 'End Time'),
            'sat' => yii::t('default', 'Saturday'),
            'sun' => yii::t('default', 'Sunday'),
            'mon' => yii::t('default', 'Monday'),
            'tue' => yii::t('default', 'Tuesday'),
            'wed' => yii::t('default', 'Wednesday'),
            'thu' => yii::t('default', 'Thursday'),
            'fri' => yii::t('default', 'Friday'),
            'status' => yii::t('default', 'Status'),
            'days' => yii::t('default', 'Days'),
            'all_days' => yii::t('default', 'All Days'),
        );
    }

    /**
     * @return array customized attribute labels Tooltips (name=>label tooltips)
     */
    public function attributeLabelsPopover()
    {
        return array();
    }

    /**
     * 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('name', $this->name, true);
        $criteria->compare('start_time', $this->start_time, true);
        $criteria->compare('end_time', $this->end_time, true);
        $criteria->compare('status', $this->status, false);

        $pageSize = $this->yiiparam('pageSize');
        return new CActiveDataProvider($this, array(
            'pagination' => array('pageSize' => $pageSize,),
            'criteria' => $criteria,
        ));
    }

    public static function getAll($status=null)
    {
        if ($status == "Active")
        {
            return Schedule::model()->active()->findAll(array('order' => 'name'));
        }
        else
        {
            return Schedule::model()->findAll(array('order' => 'name'));
        }
    }

    // The following function is responsible for getting all free (unassigned ) Schedule  which we can assign it to selected POS it to the
    // Input :
    //         1- $posId : the POS which edited and assign or unassign schedule to it,
    // Output:
    //         List of unassigned Schedule models to the POS
    public static function getFreeSchedule($posId=null)
    {
        // Get all Free schedules
        $all_Schedule = Schedule::model()->active()->findAll(array('order' => 'name'));
        if ($posId != '' && $posId != null && $all_Schedule != null)
        {
            // Get all Assigned schedules
            $assigned_schedule = PosSchedule::model()->findAllByAttributes(array('pos_id' => $posId));
            if ($assigned_schedule != null)
            {
                //remove duplicated or assigned schedule from all schedules
                foreach ($assigned_schedule as $schedule)
                {
                    $key = array_search($schedule->schedule, $all_Schedule);
                    if ($key !== null)
                    {
                        unset($all_Schedule[$key]);
                    }
                }
            }
        }
        return $all_Schedule;
    }

    /*
     * return string contains schedule's days
     */

    public function getDays()
    {
        $days = "";
        if ($this->sat == 1)
        {
            $days .="," . yii::t('default', 'Sat');
        }
        if ($this->sun == 1)
        {
            $days .="," . yii::t('default', 'Sun');
        }
        if ($this->mon == 1)
        {
            $days .="," . yii::t('default', 'Mon');
        }
        if ($this->tue == 1)
        {
            $days .="," . yii::t('default', 'Tue');
        }
        if ($this->wed == 1)
        {
            $days .="," . yii::t('default', 'Wed');
        }
        if ($this->thu == 1)
        {
            $days .="," . yii::t('default', 'Thu');
        }
        if ($this->fri == 1)
        {
            $days .="," . yii::t('default', 'Fri');
        }
        if (substr($days, 0, 1) == ",")
        {
            $days = substr($days, 1);
        }
        return $days;
    }

    /*
     * Check If Start Time less Than End Time
     */

    public function timeValidate($attribute, $params)
    {
        if (($this->start_time != "" ) && ($this->end_time != ""))
        {
            if (strtotime($this->start_time) >= strtotime($this->end_time))
            {
                $this->addError($attribute, Yii::t('default', 'Start time must be less than end time'));
            }
        }
    }

    /*
     *  override the after find method in order to format the time to "H:i", i.e. to omit the seconds
     *  and set description value
     */

    protected function afterFind()
    {
        parent::afterFind();
        $this->start_time = date("H:i", strtotime($this->start_time));
        $this->end_time = date("H:i", strtotime($this->end_time));
        $this->description = $this->name . ": (" . $this->getDays() . ") (" . $this->start_time . "," . $this->end_time . ")";
        return true;
    }

    /*
     * check if tow schedule have conflict in days
     * return true if any day have this two schedules
     * and return false if not 
     */

    public function checkConflictDays($addedSchedule=null)
    {
        if (isset($addedSchedule) && $addedSchedule != null)
        {
            if (($addedSchedule->sat && $this->sat) ||
                    ($addedSchedule->sun && $this->sun) ||
                    ($addedSchedule->mon && $this->mon) ||
                    ($addedSchedule->tue && $this->tue) ||
                    ($addedSchedule->wed && $this->wed) ||
                    ($addedSchedule->thu && $this->thu) ||
                    ($addedSchedule->fri && $this->fri))
            {
                // there is conflict in schedules days
                return true;
            }
            else
            {
                // there is no conflict in schedules days
                return false;
            }
        }
        else
        {
            return false;
        }
    }

    /*
     * check if tow schedule have conflict in time
     * return true if there is no conflict in times
     * and false if not 
     */

    public function checkConflict($schedule_id=null)
    {
        if (isset($schedule_id) && $schedule_id != null)
        {
            $addedSchedule = Schedule::model()->findByPk($schedule_id);

            //check if there is conflict in days first
            if ($this->checkConflictDays($addedSchedule))
            {
                // the start time and end time must out range old schedule [start-end] time
                if (strtotime($this->start_time) > strtotime($addedSchedule->end_time) || strtotime($this->end_time) < strtotime($addedSchedule->start_time))
                {
                    // there is no conflict in schedules
                    return true;
                }
                else
                {
                    // there is  conflict in schedules
                    return false;
                }
            }
            else
            {
                return true;
            }
        }
        else
        {
            return true;
        }
    }

}