<?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 PersonController 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', 'delete', 'updateStatus', 'download', 'manageBadges', 'ExportToExcel'),
                 '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 Status
      * to server and Update all persons Status At system .
      */
     public function actionUpdateStatus()
     {
         $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/ldapbatch
             $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/updatestatus/' . $file_name);


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


                 // Begin Transaction For Add ALL Person In Excel File AS LDAP Person In System
                 // 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;
                     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];
                             $Status = $data->sheets[0]['cells'][$i][2];
                             $person = Person::model()->findByAttributes(array('number' => $number));
                             if ($person != null)
                             {
                                 $old_status = $person->status;
                                 $person->status = $Status;
                                 if ( ! $person->save())
                                 {
                                     $isRollBack = true;
                                     $transaction->rollback();
                                     Yii::app()->user->setFlash('error', CHtml::errorSummary($person));
                                     break;
                                 }
                                 else
                                     Person::updateBadgesStatus($person->badges, $old_status, $Status);
                             }
                             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 Persons have been updated 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));
                             }
                         }

                         $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));
                     unlink($filePath);
                     return;
                 }
             }
             else
             {
                 Yii::app()->user->setFlash('error', yii::t("default", "Please browse a file"));
             }
         }
         $this->render('updateStatus', array(
             'model' => $file_model,
         ));
     }


     /**
      * Deletes a particular model.
      * If deletion is successful, the browser will be redirected to the 'admin' page.
      * @param integer $id the ID of the model to be deleted
      */
     public function actionDelete($id)
     {
         $model = $this->loadModel($id);
         $success_msg = Yii::t('default', 'The Person ({n}) has been deleted successfully', $model->name);
         $failer_msg = Yii::t('default', 'You cannot delete this element because it is referenced by other element');
         try
         {
             $model->delete();
             if ( ! isset($_GET['ajax']))
             { // Check Wether the data grid will be updated through AJAX or Not
                 Yii::app()->user->setFlash('success', $success_msg);
             }
             else
             {
                 Yii::app()->user->setFlash('success', $success_msg);
                 echo "<div class='flash-msg'>" . "<br>";
                 $this->widget('bootstrap.widgets.TbAlert');
                 echo "</div>";
             }
         }
         catch (CDbException $e)
         { // here the item is referenced by another item
             if ( ! isset($_GET['ajax']))
             {
                 Yii::app()->user->setFlash('error', $failer_msg);
             }
             else
             {
                 Yii::app()->user->setFlash('error', $failer_msg);
                 echo "<div class='flash-msg'>" . "<br>";
                 $this->widget('bootstrap.widgets.TbAlert');
                 echo "</div>";
             }
         }
     }


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

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


     // for excel export extension
     public function behaviors()
     {
         return array(
             'eexcelview' => array(
                 'class' => 'ext.eexcelview.EExcelBehavior',
             ),
         );
     }


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

         $columns = array(
             array('header' => 'Number', 'name' => 'number'),
             array('header' => 'Name', 'name' => 'name'),
             array('header' => 'Alias', 'name' => 'alias'),
             array('header' => 'Person Type', 'name' => 'type.name'),
             array('header' => 'Mobile', 'name' => 'mobile'),
             array('header' => 'Email', 'name' => 'email'),
             array('header' => 'Manager', 'name' => 'manager'),
             array('header' => 'Geomarket Name', 'name' => 'department.location.geomarket.name'),
             array('header' => 'Location Name', 'name' => 'department.location.code'),
             array('header' => 'Department Name', 'name' => 'department.name'),
             array('header' => 'LDAP Person', 'name' => 'is_Ldap'),
             array('header' => 'Manager', 'name' => 'is_manager_custome'),
             array('header' => 'Food Manager', 'name' => 'is_food_manager_custome'),
             array('header' => 'Receive Emails', 'name' => 'receive_emails_custome'),
             array('header' => 'Status', 'name' => 'status'),
         );
         $data = $model->with(array('type', 'department'))->searchWithUserFiltering();
         $data->pagination->pageSize = $data->getTotalItemCount();
         $this->toExcel($data, $columns, Yii::t('default', 'Persons'), array('creator' => 'LSMS',), 'Excel5');
     }
  


     public function actionManageBadges($id)
     {
         $model = new Badge('search');
         $person = Person::model()->findByPk($id);
         $model->person_id = $id;

         if (isset($_GET['Badge']))
             $model->attributes = $_GET['Badge'];

         $this->render('manageBadges', array(
             'model' => $model,
             'id' => $id,
             '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 = Person::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-form')
         {
             echo CActiveForm::validate($model);
             Yii::app()->end();
         }
     }


     function actionDownload($filename)
     {
         $filecontent = file_get_contents($filename);
         header("Content-Type: text/plain");
         $list = explode("/", $filename);
         $saved_file_name = $list[4];
         header("Content-disposition: attachment; filename=" . $saved_file_name);
         header("Pragma: no-cache");
         echo $filecontent;
         exit;
     }
     }

