<?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 TicketController 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('index', 'view', 'GetDepartments', 'GetSchedules', 'ConvertToPDF'),
                'roles' => array('Super Admin', 'System Admin', 'Facility Admin', 'Finance', 'Food Manager'),
            ),
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('CreateDepartmentTicket', 'SendTicketEmail'),
                'roles' => array('Super Admin', 'System Admin', 'Facility Admin', 'Food Manager'),
            ),
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('cancelled'),
                'roles' => array('Super Admin', 'System Admin'),
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function behaviors()
    {
        return array(
            'pdfable' => array(
                'class' => 'ext.pdfable.Pdfable',
                'pdfOptions' => array(
                    'bin' => __DIR__ . '/../extensions/pdfable/wkhtmltopdf/wkhtmltopdf.exe',
                    'page-size' => 'A4',
                ),
            ),
        );
    }

    public function actionConvertToPDF($preview=0, $download=0, $ticket_id=0)
    {
        $this->layout = '//layouts/pdfLayout';
        if ($preview)
        // Render this view as PDF and display in the browser tab:
            $this->render('ticket', array('ticket_id' => $ticket_id), array());
        else
        // Render this view as PDF and display inline in the browser:
            $this->renderPdf('ticket', array('ticket_id' => $ticket_id), array(), $download ? 'Ticket-' . $ticket_id . '.pdf' : null);
    }

    /**
     * Displays a particular model.
     * @param integer $id the ID of the model to be displayed
     */
    public function actionView($id, $new_ticket=0)
    {
        $this->render('view', array(
            'model' => $this->loadModel($id),
            'new_ticket' => $new_ticket,
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreateDepartmentTicket($ticket_id=0)
    {
        $model = new Ticket('CreateDepartmentTicketAtServer');

        $model->cancelled = 0;
        $model->issued_at_server = 1;
        $model->user_id = Yii::app()->user->id;
        $user_model = User::model()->findByPk(Yii::app()->user->id);
        $person_model = null;
        if (Yii::app()->user->checkAccess('Food Manager'))
        {
            $user_model = User::model()->findByPk(Yii::app()->user->id);
            $person_model = Person::model()->findByAttributes(array('alias' => $user_model->username));
            if ($person_model->is_food_manager == 0)
                $this->redirect(array('index'));
            $model->location = $user_model->location->code;
            $model->department_id = $person_model->department->name;
        }

        // Uncomment the following line if AJAX validation is needed
        // $this->performAjaxValidation($model);

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


            //Set Department ID when the user is food manager
            if (Yii::app()->user->checkAccess('Food Manager'))
            {
                $model->department_id = $person_model->department->id;
            }
            //Set Location ID after submit it is the form
            else if (isset($_POST['Location']) && ($_POST['Location'] != ''))
            {
                $model->location = $_POST['Location'];
            }
            //Set POS ID after submit it is the form
            if (($_POST['POS'] != '' ) && ( $model->pos_id == null))
            {
                $model->pos_id = $_POST['POS'];
            }
            //Create Ticket Id 
            if ($model->pos_id != '')
            {
                $dateTime_now = date("YmdHis");
                $id = $model->pos_id . $dateTime_now;
                $model->id = $id;
            }
            if ($model->save())
            {
                Yii::app()->user->setFlash('success', Yii::t('default', 'The Ticket has been issued successfully'));
                //Send ticket as email
                $ticket_id = $model->id;
                $this->layout = '//layouts/pdfLayout';
                $this->saveAsPdf('ticket', array('ticket_id' => $ticket_id), array(), 'protected\upload\pdfs\Ticket-' . $ticket_id . '.pdf');

                // Send email to food manager and his manager or send email to Facility Admin
                if (($person_model != null) && ($person_model->is_food_manager == 1))
                {
                    $manager_food_manager = $person_model->manager;
                    $cc_email = null;
                    if (($manager_food_manager != '') && (Yii::app()->user->checkAccess('Food Manager')))
                    {
                        $arr = explode('-', $manager_food_manager);
                        $manager_food_model = Person::model()->findByAttributes(array('number' => $arr[1]));
                        if ($manager_food_model != null)
                            $cc_email = $manager_food_model->email;
                    }

//                    LSMSMail::sendMail('Meals generated for ' . $model->department->name . '–' . $ticket_id, 'Dear ' . $person_model->alias . ' ,<br/> You have successfully requested (' . $model->quantity . ') meal(s) for the department (' . $model->department->name . ')  . <br/> The attached file contains full details about the request.', $user_model->email, null, 'protected\upload\pdfs\Ticket-' . $ticket_id . '.pdf', $cc_email);
                }
                else
                {
//                    LSMSMail::sendMail('Meals generated for ' . $model->department->name . '–' . $ticket_id, 'Dear ' . $user_model->identifier . ' ,<br/> You have successfully requested (' . $model->quantity . ') meal(s) for the department (' . $model->department->name . ')  . <br/> The attached file contains full details about the request.', $user_model->email, null, 'protected\upload\pdfs\Ticket-' . $ticket_id . '.pdf');
                }

//                unlink('protected\upload\pdfs\Ticket-' . $ticket_id . '.pdf');
                $this->layout = '//layouts/column2';
                //redirect to view page
                $this->redirect(array('view', 'id' => $model->id, 'new_ticket' => 1));
            }
            else
            {
                if (Yii::app()->user->checkAccess('Food Manager'))
                {
                    $user_model = User::model()->findByPk(Yii::app()->user->id);
                    $person_mode = Person::model()->findByAttributes(array('alias' => $user_model->username));
                    $model->location = $user_model->location->code;
                    $model->department_id = $person_mode->department->name;
                }
                Yii::app()->user->setFlash('error', CHtml::errorSummary($model));
            }
        }

        $this->render('createDepartmentTicket', array(
            'model' => $model,
        ));
    }

    public function actionSendTicketEmail($ticket_id)
    {
        if ($ticket_id != '')
        {
            $model = Ticket::model()->findByPk($ticket_id);
            if ($model != null)
            {
                $department_name = $model->department->name;
                $ticket_id = $model->id;
                $quantity = $model->quantity;
                $user_model = User::model()->findByPk(Yii::app()->user->id);
                $person_model = null;
                if (Yii::app()->user->checkAccess('Food Manager'))
                {
                    $person_model = Person::model()->findByAttributes(array('alias' => $user_model->username));
                }
                $cc_email = null;
                if (($person_model != null) && ($person_model->is_food_manager == 1))
                {
                    $manager_food_manager = $person_model->manager;
                    $cc_email = null;
                    if (($manager_food_manager != '') && (Yii::app()->user->checkAccess('Food Manager')))
                    {
                        $arr = explode('-', $manager_food_manager);
                        $manager_food_model = Person::model()->findByAttributes(array('number' => $arr[1]));
                        if ($manager_food_model != null)
                            $cc_email = $manager_food_model->email;
                    }
                    $person_model_alias = $person_model->alias;
                }else
                {
                    $person_model_alias = $user_model->identifier;
                }
                $user_model_email = $user_model->email;
                if ($cc_email == null)
                {
                    LSMSMail::sendMail('Meals generated for ' . $department_name . '–' . $ticket_id, 'Dear ' . $person_model_alias . ' ,<br/> You have successfully requested (' . $quantity . ') meal(s) for the department (' . $department_name . ')  . <br/> The attached file contains full details about the request.', $user_model_email, null, 'protected\upload\pdfs\Ticket-' . $ticket_id . '.pdf');
                }
                else
                {
                    LSMSMail::sendMail('Meals generated for ' . $department_name . '–' . $ticket_id, 'Dear ' . $person_model_alias . ' ,<br/> You have successfully requested (' . $quantity . ') meal(s) for the department (' . $department_name . ')  . <br/> The attached file contains full details about the request.', $user_model_email, null, 'protected\upload\pdfs\Ticket-' . $ticket_id . '.pdf', $cc_email);
                }
                unlink('protected\upload\pdfs\Ticket-' . $ticket_id . '.pdf');
            }
        }
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id the ID of the model to be updated
     */
    public function actionCancelled($id)
    {
        $model = $this->loadModel($id);

        if ($model->cancelled == 1)
        {
            $model->cancelled = 0;
            $message = Yii::t('default', 'The Ticket ({n}) has been activated successfully', $model->id);
        }
        elseif ($model->cancelled == 0)
        {
            $model->cancelled = 1;
            $message = Yii::t('default', 'The Ticket ({n}) has been cancelled successfully', $model->id);
        }
        if ($model->save())
        {
            Yii::app()->user->setFlash('success', $message);
            $this->redirect(array('index'));
        }
        else
        {
            Yii::app()->user->setFlash('error', CHtml::errorSummary($model));
        }


        $this->redirect(array('/ticket/index'));
    }

    /**
     * Lists all models.
     */
    public function actionIndex()
    {
        $model = new Ticket('search');
        $model->unsetAttributes();  // clear any default values
        if (isset($_GET['Ticket']))
            $model->attributes = $_GET['Ticket'];

        $this->render('index', array(
            'model' => $model,
        ));
    }

    /**
     * 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 = Ticket::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'] === 'ticket-form')
        {
            echo CActiveForm::validate($model);
            Yii::app()->end();
        }
    }

    /*
     * Action for return department in selected location  in cascading dropdown list
     */

    public function actionGetDepartments()
    {
        if (Yii::app()->request->isAjaxRequest)
        {
            $location = $_GET['selected'];
            $departments = array();
            $departments[] = array('label' => yii::t('default', 'Select Department'), 'value' => '');
            if ($location != '')
            {
                $selected_location = Location::model()->findByPk($location);

                if (isset($selected_location->departments) && ($selected_location->departments != null))
                {
                    foreach ($selected_location->departments as $department)
                    {
                        $departments[] = array('label' => $department->name, 'value' => $department->id);
                    }
                }
            }
            echo json_encode($departments);
            Yii::app()->end();
        }
        else
        {
            throw new CHttpException(400, 'Invalid request.');
        }
    }

    /*
     * Action for return assigned Schedules  to selected Pos  in cascading dropdown list
     */

    public function actionGetSchedules()
    {
        if (Yii::app()->request->isAjaxRequest)
        {
            $pos = $_GET['selected'];
            $schedules = array();
            $schedules[] = array('label' => yii::t('default', 'Select Schedule'), 'value' => '');
            if ($pos != '')
            {
                $selected_pos = Pos::model()->findByPk($pos);

                if (isset($selected_pos->posSchedules) && ($selected_pos->posSchedules != null))
                {
                    foreach ($selected_pos->posSchedules as $posSchedules)
                    {
                        $schedules[] = array('label' => $posSchedules->schedule->name, 'value' => $posSchedules->schedule->id);
                    }
                }
            }
            echo json_encode($schedules);
            Yii::app()->end();
        }
        else
        {
            throw new CHttpException(400, 'Invalid request.');
        }
    }

}