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

    /**
     * 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),
            'badges' => $badges,
        ));
    }

    /**
     * The Following Action Responsible for Upload Excel file to server and
     * add all 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/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/ldapbatch/' . $file_name);


                //Read Excel File and Fetch data
                $filePath = './protected/upload/ldapbatch/' . $file_name;
                Yii::import('ext.phpexcelreader.JPhpExcelReader');
                $data = new JPhpExcelReader($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
                {
                    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;
                                break;
                            }
                        }
                        if (!$is_empty)
                        {
                            $number = isset($data->sheets[0]['cells'][$i][1]) ? $data->sheets[0]['cells'][$i][1] : null;
                            $department_name = isset($data->sheets[0]['cells'][$i][2]) ? $data->sheets[0]['cells'][$i][2] : null;
                            $badge_type_name = isset($data->sheets[0]['cells'][$i][3]) ? $data->sheets[0]['cells'][$i][3] : null;
                            if ($number != null)
                            {
                                $error_message = LDAP::getPersonByNumber($number, $person);
                            }
                            else
                            {
                                $person = null;
                                $error_message = yii::t('default', 'This Employee Number at row {n} is empty .', $i);
                            }

                            if ($person != null)
                            {
                                $model = $this->loadModelByNumber($number);
                                $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
                                    {
                                        $isRollBack = true;
                                        $transaction->rollback();
                                        Yii::app()->user->setFlash('error', $error_message);
                                        break;
                                    }
                                }
                                else
                                {
                                    $model->manager = "";
                                }
                                $model->type_id = $person['employeetype'];
                                $model->email = $person['mail'];
                                $model->mobile = $person['mobile'];
                                $model->number = $person['employeenumber'];
                                $badge_number = $person['badge_number'];

                                // LDAP Type Is String So We Must Get It's ID At System
                                $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
                                    $isRollBack = true;
                                    $transaction->rollback();
                                    Yii::app()->user->setFlash('error', Yii::t('default', 'The Person Type (person_type) for person number (person_number) is not found in system', array('person_number' => $number, 'person_type' => $model->type_id)));
                                    break;
                                }
                                else
                                {
                                    $model->type_id = $type_id;
                                }

                                $department_id = Department::getDepartmentID($department_name);
                                if ($department_id != null)
                                {
                                    $model->department_id = $department_id;
                                }
                                else
                                {
                                    // When user does not insert the LDAP type to system and and new person have that Type
                                    $isRollBack = true;
                                    $transaction->rollback();
                                    if ($department_name == "")
                                        Yii::app()->user->setFlash('error', Yii::t('default', 'The Department Name is empty at row {n}', $i));
                                    else
                                        Yii::app()->user->setFlash('error', Yii::t('default', 'The Department Name ({n}) is not found in the system', $department_name));

                                    break;
                                }
                                if (!$model->save())
                                {
                                    $isRollBack = true;
                                    $transaction->rollback();
                                    Yii::app()->user->setFlash('error', CHtml::errorSummary($model));
                                    break;
                                }
                                else if (($badge_type_name != '') && ($badge_type_name != null))
                                {
                                    //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;
                                    }
                                }
                            }
                            else
                            {
                                $isRollBack = true;
                                $transaction->rollback();
                                Yii::app()->user->setFlash('error', $error_message);
                                break;
                            }
                        }
                    }
                    If (!$isRollBack)
                    {
                        Yii::app()->user->setFlash('success', Yii::t('default', 'The batch of persons has been saved 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,
        ));
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     */
    public function actionCreate($alias)
    {
        if (isset($alias) && ($alias != ""))
        {
            $model = new LDAPPerson;

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

            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())
                    {
                        Yii::app()->user->setFlash('success', Yii::t('default', 'The Person has been added successfully'));
                        $this->redirect(array('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('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);

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

        $_old_is_food_manager = $model->is_food_manager;
        $old_status = $model->status;
        if (isset($_POST['LDAPPerson']))
        {
            $model->attributes = $_POST['LDAPPerson'];
            $LDAP_type = $model->type_id;
            $model->type_id = PersonType::getLDAPTypeID($model->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 updated successfully'));
                if (($_old_is_food_manager == 1) && ($model->is_food_manager == 0))
                {
                    Yii::app()->user->setFlash('warning', Yii::t('default', 'NOTE: The user ({n}) will no longer be able to issue new department tickets',$model->alias));
                }
                // Update the departments of all the non-LDAP persons that are reported to this LDAP person
                // This will be usefull if the department of the LDAP person is changed. If so, then we need the departments of all the Non-LDAP persons reprted to this person to be updated as well)
                if($model->is_manager == 1){ // i.e. we may find some Non-ldap persons that are reported to this person
                    // find all the non-ldap persons reported to this person
                    $non_ldap_persons = NonLDAPPerson::model()->findAllByAttributes(array('manager'=>$model->name."-".$model->number));
                    foreach($non_ldap_persons as $non_ldap_person){
                        $non_ldap_person->department_id = $model->department_id;
                        $non_ldap_person->save();
                    }
                }
                $this->redirect(array('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($model->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
            {
                $model->type_id = $model->type->name;
                Yii::app()->user->setFlash('error', $error_message);
            }
        }

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

    /**
     * The Following Action Responsible for searching for person on LDAP and return result.
     */
    public function actionPersonSearch()
    {
        $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,
            'person_value' => $person_value,
        ));
    }

    /**
     * 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 = LDAPPerson::model()->findByPk($id);
        if ($model === null)
            throw new CHttpException(404, 'The requested page does not exist.');
        return $model;
    }

    //The Following Function Check if there is LDAP preson in System have the iput Number
    // Input: LDAP Person Number
    //Output: LDAP Person if Found or New object of LDAPPerson Model If not found
    public function loadModelByNumber($number)
    {
        $model = null;
        $model = LDAPPerson::model()->findByAttributes(array('number' => $number));
        if ($model === null)
        {
            $model = new LDAPPerson;
            $model->is_manager = 0;
            $model->is_food_manager = 0;
            $model->receive_emails = 1;
            $model->status = 'Active';
        }
        return $model;
    }

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

}

