<?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
 */

class PosScheduleController extends Controller
    {

    /**
     * @var string the default layout for the views. Defaults to '//layouts/column2', meaning
     * using two-column layout. See 'protected/views/layouts/column2.php'.
     */
    public $layout = '//layouts/column2';

    /**
     * @return array action filters
     */
    public function filters()
    {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules()
    {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('create'),
                'roles' => array('System Admin','Super Admin'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    /**
     * manage assign schedules to POS 
     * If assign is successful, the browser will be back you to POS view page.
     */
    public function actionCreate( $posId )
    {
        $model = new PosSchedule;
        $model->pos_id = $posId;

        if (isset($_POST['PosSchedule']))
        {
            $model->attributes = $_POST['PosSchedule'];

            if (isset($_POST['PosSchedule']['assigned_schedules']))
            {
                $model->assigned_schedules = $_POST['PosSchedule']['assigned_schedules'];
            }
            else
            {
                $model->assigned_schedules = array();
            }
            $assigned_schedules_array = $model->assigned_schedules;

            if (isset($assigned_schedules_array) && count($assigned_schedules_array) >= 0)
            {
                // begin transaction start with delete all assigned schedule and add new schedules
                // abort the transaction if there is conflict between schedules or throw exception
                $transaction = Yii::app()->db->beginTransaction();
                try
                {
                    PosSchedule::model()->deleteAll('pos_id=' . $model->pos_id);
                    $rollback = false;
                    foreach ($assigned_schedules_array as $assigned_schedule)
                    {
                        $model = new PosSchedule;
                        $model->schedule_id = $assigned_schedule;
                        $model->pos_id = $posId;
                        if (!$model->save())
                        {
                            Yii::app()->user->setFlash('error', CHtml::errorSummary($model));
                            $this->widget('bootstrap.widgets.TbAlert');
                            $transaction->rollback();
                            $rollback = true;
                            return;
                        }
                    }
                    if (!$rollback)
                    {
                        $transaction->commit(); // commit transactions now
                        Yii::app()->user->setFlash('success', Yii::t('default', 'The Schedules have been saved successfully'));
                        $this->widget('bootstrap.widgets.TbAlert');
                        return;
                    }
                }
                catch (Exception $ex)
                {
                    $transaction->rollback();
                    Yii::app()->user->setFlash('error', CHtml::errorSummary($model));
                    $this->widget('bootstrap.widgets.BootAlert');
                    return;
                }
            }
        }
        $this->render('create', array(
            'model' => $model,
            'posId'=>$posId,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     * @param integer the ID of the model to be loaded
     */
    public function loadModel( $id )
    {
        $model = PosSchedule::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    /**
     * Performs the AJAX validation.
     * @param CModel the model to be validated
     */
    protected function performAjaxValidation( $model )
    {
        if (isset($_POST['ajax']) && $_POST['ajax'] === 'pos-schedule-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    }
