<?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 NonLDAPPersonController 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('view', 'create', 'update', 'addBatch', 'personSearch', 'convertToLDAP'),
                 'roles' => array('System Admin', 'Facility Admin', 'Super Admin'),
             ),
             array('deny', // deny all users
                 'users' => array('*'),
             ),
         );
     }


     /**
      * Creates a new model.
      * If creation is successful, the browser will be redirected to the 'view' page.
      */
     public function actionConvertToLDAP($alias, $id)
     {
         if (isset($alias) && ($alias != ""))
         {
             $model = LDAPPerson::model()->findByPk($id);
             // Uncomment the following line if AJAX validation is needed
             // $this->performAjaxValidation($model);

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

                 //get IDfor LDAPType Name
                 $type_id = PersonType::getLDAPTypeID($model->type_id);

                 if ($type_id == -1)
                 {
                     // When user does not insert the LDAP type to system and and new person have that Type
                     Yii::app()->user->setFlash('error', Yii::t('default', 'The Person Type has not been added to the system'));
                 }
                 else
                 {
                     $LDAP_type = $model->type_id;
                     $model->type_id = $type_id;
                     if ($model->save())
                     {
                         Person::updateBadgesStatus($model->badges, $old_status, $model->status);
                         Yii::app()->user->setFlash('success', Yii::t('default', 'The Person has been converted successfully to LDAP'));
                         $this->redirect(array('/lDAPPerson/view', 'id' => $model->id));
                     }
                     else
                     {
                         // When found error at validation we must return Person type from Id to  string
                         $model->type_id = $LDAP_type;
                         Yii::app()->user->setFlash('error', CHtml::errorSummary($model));
                     }
                 }
             }
             else
             {
                 $error_message = LDAP::getPersonByAlias($alias, $person);
                 if ($person != null)
                 {
                     $model->alias = $person['alias'];
                     $model->name = $person['cn'];
                     // Get just Manager CN
                     $arr = explode(",", $person['manager']);
                     $manager = "";
                     // remove "cn=" from string
                     $manager = substr($arr[0], 3);
                     if ($manager)
                     {
                         // Searching for manager information at LDAP System and set manager value at sysytem as 'cn-number'
                         $error_message = LDAP::getPersonByCn($manager, $LDAP_manager);
                         if ($LDAP_manager != null)
                         {
                             $model->manager = $LDAP_manager['cn'] . '-' . $LDAP_manager['employeenumber'];
                         }
                         else
                         {
                             Yii::app()->user->setFlash('error', $error_message);
                             $model->manager = "";
                         }
                     }
                     else
                     {
                         $model->manager = "";
                     }
                     $model->type_id = $person['employeetype'];
                     $model->email = $person['mail'];
                     $model->mobile = $person['mobile'];
                     $model->number = $person['employeenumber'];
                 }
                 else
                 {
                     Yii::app()->user->setFlash('error', $error_message);
                 }
             }

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


     /**
      * The Following Action Responsible for searching for person on LDAP To Convert Non-LDAP person To LDAP Person.
      */
     public function actionPersonSearch($id)
     {
         $person_value = "";
         $arrayDataProvider = null;
         if ((isset($_POST['person_information'])) && ($_POST['person_information'] != ""))
         {
             $person_value = $_POST['person_information'];
             $message_error = LDAP::getUsers($_POST['person_information'], $arrayDataProvider);
             if ($message_error != "")
             {
                 Yii::app()->user->setFlash('error', $message_error);
             }
         }
         else
         {
             $arrayDataProvider = null;
         }

         $this->render('personSearch', array(
             'arrayDataProvider' => $arrayDataProvider,
             'id' => $id,
             'person_value' => $person_value,
         ));
     }


     /**
      * The Following Action Responsible for Upload Excel file to server and
      * add all Non-LDAP person in file to system and update who exist before .
      */
     public function actionAddBatch()
     {
         $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/nonldapbatch
             $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/nonldapbatch/' . $file_name);


                 //Read Excel File and Fetch data
                 $filePath = './protected/upload/nonldapbatch/' . $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 Non-LDAP Person In System
                 // Abort The Transaction If There Is Validate Error any Exception
                 $transaction = Yii::app()->db->beginTransaction();
                 $isRollBack = false;
                 try
                 {
                     for ($i = 2; $i <= count($data->sheets[0]['cells']); $i ++ )
                     {
                         $is_empty = TRUE;
                         for ($j = 1; $j <= 5; $j ++ )
                         {
                             if (isset($data->sheets[0]['cells'][$i][$j]) && ($data->sheets[0]['cells'][$i][$j] != ""))
                             {
                                 $is_empty = FALSE;
                                 break;
                             }
                         }

                         if ( !$is_empty)
                         {
                             $a=$data->sheets[0]['cells'][$i];
                             $name = isset($data->sheets[0]['cells'][$i][1]) ? $data->sheets[0]['cells'][$i][1] : null;
                             $person_type_name = isset($data->sheets[0]['cells'][$i][2]) ? $data->sheets[0]['cells'][$i][2] : null;
                             $mobile = isset($data->sheets[0]['cells'][$i][3]) ? $data->sheets[0]['cells'][$i][3] : null;
                             $manager_number = isset($data->sheets[0]['cells'][$i][4]) ? $data->sheets[0]['cells'][$i][4] : null;
                             $email = isset($data->sheets[0]['cells'][$i][5]) ? $data->sheets[0]['cells'][$i][5] : null;
                             $badge_number = isset($data->sheets[0]['cells'][$i][6]) ? $data->sheets[0]['cells'][$i][6] : null;
                             $badge_type_name = isset($data->sheets[0]['cells'][$i][7]) ? $data->sheets[0]['cells'][$i][7] : null;

                             $model = new NonLDAPPerson;
                             //auto generated number for Non-LDAP person
                             $model->number = NonLDAPPerson::generateCode($model->tableName(), Yii::app()->params['numOfDigitsForCodes']);
                             $model->name = $name;
                             // there is no Alias at Non-LDAP person
                             $model->alias = "";

                             //Check if the person type exist and is nonLDAP Type
                             $personType_model = PersonType::model()->findByAttributes(array('name' => $person_type_name));
                             if ($personType_model == null)
                             {
                                 $isRollBack = true;
                                 $transaction->rollback();
                                 Yii::app()->user->setFlash('error', Yii::t('default', 'The Person Type ({n}) is not found in system', $person_type_name));
                                 break;
                             }
                             else
                             {
                                 if ($personType_model->is_ldap == 1)
                                 {
                                     $isRollBack = true;
                                     $transaction->rollback();
                                     Yii::app()->user->setFlash('error', Yii::t('default', 'You can not use an LDAP person type ({n}) when you add a batch of non-LDAP persons.', $person_type_name));
                                     break;
                                 }
                                 else
                                 {
                                     $model->type_id = $personType_model->id;
                                 }
                             }
                             $model->email = $email;
                             $model->mobile = $mobile;
                             //Check if the manager number is refer to person in system and is manager
                             $manager_model = Person::model()->findByAttributes(array('number' => $manager_number));
                             if ($manager_model == null)
                             {
                                 $isRollBack = true;
                                 $transaction->rollback();
                                 if($manager_number!='')
                                 Yii::app()->user->setFlash('error', Yii::t('default', 'The Manager number ({n}) is not found in the system', $manager_number));
                                 else
                                 Yii::app()->user->setFlash('error', Yii::t('default', 'The Manager number cannot be empty or blank'));
                                 break;
                             }
                             else
                             {
                                 if ($manager_model->is_manager == 1)
                                 {
                                     $model->manager = $manager_model->name . '-' . $manager_model->number;
                                     $model->department_id = $manager_model->department_id;
                                 }
                                 else
                                 {
                                     $isRollBack = true;
                                     $transaction->rollback();
                                     Yii::app()->user->setFlash('error', Yii::t('default', 'The person that has the number ({n}) is not marked as a manager in the system.', $manager_number));
                                     break;
                                 }
                             }

                             $model->is_manager = 0;
                             $model->is_food_manager = 0;
                             $model->receive_emails = 1;
                             $model->status = 'Active';


                             if ( ! $model->save())
                             {
                                 $isRollBack = true;
                                 $transaction->rollback();
                                 Yii::app()->user->setFlash('error', CHtml::errorSummary($model));
                                 break;
                             }
                             else
                             {
                                 //Add Badge and Assign it after add Ldap person
                                 $error = '';
                                 $result = Badge::addAndAssignBadge($badge_number, $badge_type_name, $model, $error);
                                 if (($result == false) && ($error != ''))
                                 {
                                     $isRollBack = true;
                                     $transaction->rollback();
                                     $error.= yii::t('default', ' at row ({n})', $i);
                                     Yii::app()->user->setFlash('error', $error);
                                     break;
                                 }
                             }
                         }
                     }
                     if ( ! $isRollBack)
                     {
                         Yii::app()->user->setFlash('success', Yii::t('default', 'The Persons have been updated successfully'));
                         $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($model));
                     unlink($filePath);
                     return;
                 }
             }
             else
             {
                 Yii::app()->user->setFlash('error', yii::t("default", "Please browse a file"));
             }
         }
         $this->render('addBatch', array(
             'model' => $file_model,
         ));
     }


     /**
      * Displays a particular model.
      * @param integer $id the ID of the model to be displayed
      */
     public function actionView($id)
     {
         $badges = new Badge('search');
         $person = Person::model()->findByPk($id);
         $badges->person_id = $id;

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

         $this->render('view', array(
             'model' => $this->loadModel($id),
             'id' => $id,
             'badges' => $badges,
         ));
     }


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

         //auto generated number for Non-LDAP person
         $model->number = NonLDAPPerson::generateCode($model->tableName(), Yii::app()->params['numOfDigitsForCodes']);

         // there is no Alias at Non-LDAP person
         $model->alias = "";

         if (isset($_POST['NonLDAPPerson']))
         {
             $model->attributes = $_POST['NonLDAPPerson'];
             $model->is_manager = 0;
             $model->is_food_manager = 0;
             $manager = $model->manager;
             if ($manager != null || $manager != "")
             {
                 $manager_attribute = explode('-', $manager);
                 $manager_number = end($manager_attribute);
                 $manager_model = Person::model()->findByAttributes(array('number' => $manager_number));
                 if ($manager_model != null)
                 {
                     $model->department_id = $manager_model->department_id;
                 }
                 else
                 {
                     Yii::app()->user->setFlash('error', Yii::t('default', 'The Manager ({n}) is not found in system', $manager));
                     $model->manager = "";
                 }
             }
             else
             {
                 $model->department_id = "";
             }
             if ($model->save())
             {
                 Yii::app()->user->setFlash('success', Yii::t('default', 'The Person has been added successfully'));
                 $this->redirect(array('view', 'id' => $model->id));
             }
             else
             {
                 Yii::app()->user->setFlash('error', CHtml::errorSummary($model));
             }
         }

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


     /**
      * 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 actionUpdate($id)
     {
         $model = $this->loadModel($id);

         // there is no Alias at Non-LDAP person
         $model->alias = "";

         $old_status = $model->status;

         if (isset($_POST['NonLDAPPerson']))
         {
             $model->attributes = $_POST['NonLDAPPerson'];
             $manager = $model->manager;
             // set person department as his manager department
             if ($manager != null || $manager != "")
             {
                 $manager_attribute = explode('-', $manager);
                 $manager_number = end($manager_attribute);
                 $manager_model = Person::model()->findByAttributes(array('number' => $manager_number));
                 if ($manager_model != null)
                 {
                     $model->department_id = $manager_model->department_id;
                 }
                 else
                 {
                     Yii::app()->user->setFlash('error', Yii::t('default', 'The Manager ({n}) is not found in system', $manager));
                     $model->manager = "";
                 }
             }
             else
             {
                 $model->department_id = "";
             }
             if ($model->save())
             {
                 Person::updateBadgesStatus($model->badges, $old_status, $model->status);
                 Yii::app()->user->setFlash('success', Yii::t('default', 'The Person has been updated successfully'));
                 $this->redirect(array('view', 'id' => $model->id));
             }
             else
             {
                 Yii::app()->user->setFlash('error', CHtml::errorSummary($model));
             }
         }

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

