<?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 PersonPosController 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', 'BatchPersonPOSs'),
                 'roles' => array('System Admin', 'Facility Admin', 'Super Admin'),
             ),
             array('deny', // deny all users
                 'users' => array('*'),
             ),
         );
     }


     /**
      * The Following Action Responsible for Upload Excel file Contain Persons Number and POSs Name
      * to server and Update all persons POSs assigned At system .
      */
     public function actionBatchPersonPOSs()
     {
         $file_model = new File;

         if (isset($_POST['File']))
         {

             $file_model->attributes = $_POST['File'];

             // get file name and upload it to server at foler /protected/upload/person_poss
             $file_model->file = CUploadedFile::getInstance($file_model, 'file');

             if (isset($file_model->file) && ($file_model->file != null))
             {
                 $formatted_file_name = $file_model->file->name;
                 $file_name = str_replace(":", "_", $formatted_file_name); // the ":" is not allowed in the file name
                 $file_model->file->saveAs('./protected/upload/person_poss/' . $file_name);


                 //Read Excel File and Fetch data
                 $filePath = './protected/upload/person_poss/' . $file_name;
                 Yii::import('ext.phpexcelreader.JPhpExcelReader');
                 $data = new JPhpExcelReader();
                 $data->Spreadsheet_Excel_Reader($filePath);


                 // Begin Transaction For Assign ALL Person To POSs In Excel File 
                 // Abort The Transaction If There Is Validate Error Or Connection To LDAP Error
                 $transaction = Yii::app()->db->beginTransaction();
                 $isRollBack = false;
                 try
                 {
                     $numbers_not_found = null;
                     $POSs_not_found = null;
                     for ($i = 2; $i <= count($data->sheets[0]['cells']); $i ++ )
                     {
                         $is_empty = TRUE;
                         for ($j = 1; $j <= 2; $j ++ )
                         {
                             if (isset($data->sheets[0]['cells'][$i][$j]) && ($data->sheets[0]['cells'][$i][$j] != ""))
                             {
                                 $is_empty = FALSE;
                             }
                             else
                             {
                                 $is_empty = true;
                                 break;
                             }
                         }
                         if ( ! $is_empty)
                         {
                             $number = $data->sheets[0]['cells'][$i][1];
                             $pos_name = $data->sheets[0]['cells'][$i][2];
                             $person_model = Person::model()->findByAttributes(array('number' => $number));
                             if ($person_model != null)
                             {
                                 $pos_model = Pos::model()->findByAttributes(array('name' => $pos_name));
                                 if ($pos_model != null)
                                 {
                                     $PersonPos_model = PersonPos::model()->findByAttributes(array('pos_id' => $pos_model->id, 'person_id' => $person_model->id));
                                     if ($PersonPos_model == NULL)
                                     {
                                         $PersonPos_model = new PersonPos;
                                         $PersonPos_model->pos_id = $pos_model->id;
                                         $PersonPos_model->person_id = $person_model->id;
                                         if ( ! $PersonPos_model->save())
                                         {
                                             $isRollBack = true;
                                             $transaction->rollback();
                                             Yii::app()->user->setFlash('error', CHtml::errorSummary($PersonPos_model));
                                             break;
                                         }
                                     }
                                 }
                                 else
                                 {
                                     if ($POSs_not_found == null)
                                     {
                                         $POSs_not_found = " " . $pos_name;
                                     }
                                     else
                                     {
                                         $POSs_not_found.=", " . $pos_name;
                                     }
                                 }
                             }
                             else
                             {
                                 if ($numbers_not_found == null)
                                 {
                                     $numbers_not_found = " " . $number;
                                 }
                                 else
                                 {
                                     $numbers_not_found.=", " . $number;
                                 }
                             }
                         }
                     }
                     If ( ! $isRollBack)
                     {
                         Yii::app()->user->setFlash('success', Yii::t('default', 'The batch assignment of the persons to the POSs has completed successfully'));
                         if ($numbers_not_found != null)
                         {
                             // check if there is multiple not found numbers in order to format the message
                             if (strpos($numbers_not_found, ",") === false)
                             {
                                 Yii::app()->user->setFlash('warning', Yii::t('default', 'The person number ({n}) didn’t exist', $numbers_not_found));
                             }
                             else
                             {
                                 Yii::app()->user->setFlash('warning', Yii::t('default', 'The persons’ numbers ({n}) didn’t exist', $numbers_not_found));
                             }
                         }
                         if ($POSs_not_found != null)
                         {
                             // check if there is multiple not found POSs' names in order to format the message
                             if (strpos($POSs_not_found, ",") === false)
                             {
                                 Yii::app()->user->setFlash('warning', Yii::t('default', 'The POS name ({n}) didn’t exist', $POSs_not_found));
                             }
                             else
                             {
                                 Yii::app()->user->setFlash('warning', Yii::t('default', 'The POSs’ names ({n}) didn’t exist', $POSs_not_found));
                             }
                         }

                         $transaction->commit(); // commit transactions now
                         unlink($filePath);
                         $this->redirect(array('/person/index'));
                     }
                     unlink($filePath);
                 }
                 catch (Exception $ex)
                 {
                     $transaction->rollback();
                     Yii::app()->user->setFlash('error', CHtml::errorSummary($person_model));
                     unlink($filePath);
                     return;
                 }
             }
             else
             {
                 Yii::app()->user->setFlash('error', yii::t("default", "Please browse a file"));
             }
         }
         $this->render('batchPersonPOSs', array(
             'model' => $file_model,
         ));
     }


     /**
      * Creates a new model.
      * If creation is successful, the browser will be redirected to the 'view' page.
      */
     public function actionCreate($personId)
     {
         $model = new PersonPos;
         $model->person_id = $personId;

         // get person Information for routing view url in breadcrumbs
         $person = Person::model()->findByPk($personId);

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

             if (isset($_POST['PersonPos']['assigned_POSs']))
             {
                 $model->assigned_POSs = $_POST['PersonPos']['assigned_POSs'];
             }
             else
             {
                 $model->assigned_POSs = array();
             }
             $assigned_POSs_array = $model->assigned_POSs;

             if (isset($assigned_POSs_array) && count($assigned_POSs_array) >= 0)
             {
                 // begin transaction start with delete all assigned POS and add new POS
                 // abort the transaction if there is not validate item
                 $transaction = Yii::app()->db->beginTransaction();
                 try
                 {
                     PersonPos::model()->deleteAll('person_id=' . $model->person_id);
                     $rollback = false;
                     foreach ($assigned_POSs_array as $assigned_POS)
                     {
                         $model = new PersonPos;
                         $model->pos_id = $assigned_POS;
                         $model->person_id = $personId;
                         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 Assigned POSs 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,
             'person' => $person
         ));
     }


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

