<?php

class UsersController extends Controller {

    public function accessRules() {
        return array(
            array('allow', // allow all users to perform 'index' and 'view' actions
                'actions' => array('login', 'error', 'logout'),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('Index', 'Create', 'GetList', 'SaveUsers', 'DeleteUsers', 'UploadSignature', 'EditUser', 'EditSaveUsers', 'getemployeedetails',
                    'BlockUser'),
                'expression' => '$user->isMember()',
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function actionIndex() {

        $user_id   = (int) Yii::app()->user->id; 
        $modeluser = User::model()->findByPk($user_id);

        if ($modeluser->user_group_id != 1) { 
            $this->redirect(Yii::app()->baseUrl . '/index.php');
            Yii::app()->end();
        }

        $this->render('index');
    }
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }
    public function actionGetList() {
        $model = new User();
        $draw = $_POST['draw'];
        $offset = $_POST['start'];
        $limit = $_POST['length'];

        $user_id = (int) Yii::app()->user->id;
        $modeluser = User::model()->findByPk($user_id);

        $condition = 'isActive="Y"';

        if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
            $searchString = $_POST['search']['value'];
            $searchString_en = $this->ciphertext($searchString, "e");
            $condition .= " AND (id LIKE '%".$searchString."%' 
            OR first_name LIKE '%".$searchString."%' 
            OR designation LIKE '%".$searchString_en."%')";
        }


        if ($modeluser->user_group_id != 1) {
            $condition .= " AND (created_by = ".$user_id." OR id = ".$user_id.")";
        }

        $count = $model->count(array('condition' => $condition));

        $users = $model->findAll(array(
            'condition' => $condition,
            'limit' => $limit,
            'offset' => $offset,
            'order' => 'first_name ASC'
        ));

        $recordsTotal = $count;
        $recordsFiltered = $count;

        $data = array(
            'draw' => $draw,
            'recordsTotal' => $recordsTotal,
            'recordsFiltered' => $recordsFiltered,
            'data' => array()
        );

        $m = $offset;
        foreach ($users as $user) {
            $data['data'][] = array(
                ++$m,
                $user->first_name,
                $user->username,  
                $user->email,
                array('id' => $user->id, 'code' => $user->first_name)
            );
        }

        echo json_encode($data);
    }


    public function actionCreate() {
        $model = new User();
        
    
        $id = (int) Yii::app()->request->getParam('id');
        if ($id > 0) {
            $model = $model->findByPk($id);
        }
        
        Yii::app()->clientScript->scriptMap = array(
            '*jquery.js' => false,
            '*jquery.min.js' => false,
            'jquery.min.js' => false,
            '*jquery-ui.js' => false,
            '*jquery-ui.min.js' => false,
            'jquery-2.1.4.min.js' => false
        );

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


    public function actionEditSaveUsers() {
        $model = new User();
        $other = array();

        $validate = True;
        if (isset($_POST['User'])) {
            if ((int) $_POST['User']['id'] > 0) {
                $model->updated_by = Yii::app()->user->id;
                $model->updated_date_time = date('Y-m-d h:i:s');
                $id = (int) $_POST['User']['id'];
                $model = $model->findByPk($id);
                $model->scenario = 'update';
            }
            $model->attributes = $_POST['User'];
            $model->email = $_POST['User']['email'];
            $model->phno = $_POST['User']['phno'];
            $model->password = $_POST['User']['password'];
            $model->level = '1';
            $model->branch_id = "";
            $model->department_head_id = $_POST['User']['department_head_id'];
            $model->hr_connected_employee_id = $_POST['User']['hr_connected_employee_id'];
            if (isset($_POST['User']['branch_id'])) {
                $model->branch_id = implode(',', $_POST['User']['branch_id']);
            }
            $model->company_id = User::DEFAULT_COMPANY_ID;
            $flag = 0;
            $flag_user_group = 0;
            foreach ($_POST['MasUser'] as $i => $each) {
                if ($each['user_group_id'] > 0) {
                    $database_name_1 = $each['data_base_name'];
                    $usertable_name_1 = $each['user_table_name'];
                    if ($each['id'] > 0) {
                        $sql_username_exist = "SELECT id FROM $database_name_1.$usertable_name_1 WHERE username= '" . $model->username . "' AND id!='" . $each['id'] . "'";
                        $user_name_exist = Yii::app()->db->createCommand($sql_username_exist)->queryScalar();
                        if (!empty($user_name_exist)) {
                            $flag = 1;
                            $validate = false;
                        }
                    }
                } else {
                    if (in_array($each['portal_id'], $_POST['arraycid'])) {
                        $flag_user_group = 1;
                        $validate = false;
                    }
                }
            }
            if ($flag == 1) {
                $other [] = "This Username is already taken.";
            }
            if ($flag_user_group == 1) {
                $other [] = "Portal Usergroup Cannot be Blank.";
            }
            if ($model->validate() && $validate) {
                if (isset($_POST['MasUser'])) {
                    foreach ($_POST['MasUser'] as $i => $each) {
                        if ($flag == 0) {
                                $id = $each['id'];
                                $employee_id = $model->hr_connected_employee_id;
                                $database_name = $each['data_base_name'];
                                $usertable_name = $each['user_table_name'];
                            if (isset($_POST['arraycid']) && is_array($_POST['arraycid'])) {
                                $username = $model->username;
                                $salt = '$2a$10$1qAz2wSx3eDc4rFv5tGb5t';
                                $password = crypt($username, $salt);
                                $first_name = $model->first_name;
                                $last_name = $model->last_name;
                                $designation = $model->designation;
                                $branch_id = $model->branch_id;
                                $department_head_id = $model->department_head_id;
                                $email = $model->email;
                                $phno = $model->phno;
                                $company_id = User::DEFAULT_COMPANY_ID;
                                $user_group_id = $each['user_group_id'];
                                $created_by = Yii::app()->user->id;
                                $created_date_time = date('Y-m-d h:i:s');
                                if (in_array($each['portal_id'], $_POST['arraycid'])) {
                                    //created by not added in data base there is no field in user tables other than HR
                                    // $SQLUPDATE = "UPDATE $database_name.$usertable_name SET username = '" . $username. "', password = '" . $password . "', hr_connected_employee_id = '" . $employee_id . "', first_name = '" . $first_name . '", last_name = "' . $last_name . '", designation = '" . $designation . "',user_group_id='".$user_group_id."' WHERE hr_connected_employee_id="' . $employee_id . ' AND id='".$id."'";
                                    //  branch_id='$branch_id',
                                    //   department_head_id='$department_head_id',
                                    if ($each['portal_id'] == 5) {
                                        if ($id > 0) {
                                            $SQLUPDATE = "UPDATE $database_name.$usertable_name 
                                          SET 
                                              username = '$username', 
                                              password = '$password', 
                                              hr_connected_employee_id = '$employee_id', 
                                              first_name = '$first_name', 
                                              last_name = '$last_name', 
                                              designation = '$designation', 
                                              user_group_id = '$user_group_id',
                                              email ='$email',
                                              phno  ='$phno',  
                                              branch_id='$branch_id',
                                              department_head_id='$department_head_id',    
                                              isActive='Y'    
                                          WHERE 
                                              hr_connected_employee_id = '$employee_id' 
                                              AND id = '$id'";
                                            $result_execute = Yii::app()->db->createCommand($SQLUPDATE)->execute();
                                            if ($result_execute != 1) {
                                                $other [] = "Data insertion Failed in $database_name.$usertable_name";
                                            }
                                        } else {
                                            $sql_insert = "INSERT INTO $database_name.$usertable_name (`username`, `password`, `hr_connected_employee_id`, `first_name`, `last_name`,`email`,`phno`,`designation`,`branch_id`,`department_head_id`,`level`,`company_id`, `isActive`,`user_group_id`,`created_by`,`created_date_time`) VALUES ('$username', '$password','$employee_id','$first_name','$last_name','$email','$phno','$designation','$branch_id','$department_head_id', 1,'$company_id', 'Y','$user_group_id','$created_by','$created_date_time');";
                                            $result_execute = Yii::app()->db->createCommand($sql_insert)->execute();
                                            if ($result_execute != 1) {
                                                $other [] = "Data insertion Failed in $database_name.$usertable_name";
                                            }
                                        }
                                    } else {
                                        if ($id > 0) {
                                            $SQLUPDATE = "UPDATE $database_name.$usertable_name 
                                          SET 
                                              username = '$username', 
                                              password = '$password', 
                                              hr_connected_employee_id = '$employee_id', 
                                              first_name = '$first_name', 
                                              last_name = '$last_name', 
                                              designation = '$designation', 
                                              user_group_id = '$user_group_id',
                                              email ='$email',
                                              phno  ='$phno',  
                                              isActive='Y'    
                                          WHERE 
                                              hr_connected_employee_id = '$employee_id' 
                                              AND id = '$id'";
                                            $result_execute = Yii::app()->db->createCommand($SQLUPDATE)->execute();
                                            if ($result_execute != 1) {
                                                $other [] = "Data insertion Failed in $database_name.$usertable_name";
                                            }
                                        } else {
                                            $sql_insert = "INSERT INTO $database_name.$usertable_name (`username`, `password`, `hr_connected_employee_id`, `first_name`, `last_name`,`email`,`phno`,`designation`,`level`,`company_id`, `isActive`,`user_group_id`) VALUES ('$username', '$password','$employee_id','$first_name','$last_name','$email','$phno','$designation', 1,'$company_id', 'Y','$user_group_id');";
                                            $result_execute = Yii::app()->db->createCommand($sql_insert)->execute();
                                            if ($result_execute != 1) {
                                                $other [] = "Data insertion Failed in $database_name.$usertable_name";
                                            }
                                        }
                                    }
                                } else {
                                    if($id>0){
                                    $SQLUPDATE = "UPDATE $database_name.$usertable_name SET  isActive='N' WHERE hr_connected_employee_id = '$employee_id' AND id = '$id'";
                                    $result_execute = Yii::app()->db->createCommand($SQLUPDATE)->execute();
                                    }
                                }
                            }else{
                                $SQLUPDATE = "UPDATE $database_name.$usertable_name SET  isActive='N' WHERE hr_connected_employee_id = '$employee_id' AND id = '$id'";
                                $result_execute = Yii::app()->db->createCommand($SQLUPDATE)->execute();
  
                            }
                        }
                    }
                }

                $jsonData['status'] = 'success';
                $jsonData['id'] = $model->id;
                echo CJSON::encode($jsonData);
            } else {
                $error1 = array();
                $error1 = json_decode(CActiveForm::validate($model, '', false), true);
                $error = CJSON::encode(array_merge_recursive($error1, $other));
                if ($error != '[]')
                    echo $error;
            }
        }
    }

    public function actionSaveUsers()
    {
        $model = new User();
        $other = [];

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

            if (!empty($_POST['User']['id'])) {
                $model = User::model()->findByPk((int)$_POST['User']['id']);
                $model->scenario = 'update';
                $model->updated_by = Yii::app()->user->id;
                $model->updated_date_time = date('Y-m-d H:i:s');

                $oldPassword = $model->password;
            } else {
                $model->scenario = 'add';
                $model->created_by = Yii::app()->user->id;
                $model->created_date_time = date('Y-m-d H:i:s');
            }

            $model->attributes = $_POST['User'];
            $model->company_id = Yii::app()->user->master_user_company_id;
            $model->level = '1';
            $model->branch_id = "";

            if (!empty($model->password)) {
                $salt = '$2a$10$1qAz2wSx3eDc4rFv5tGb5t';
                $model->password = crypt($model->password, $salt);
            } else {
                if (!empty($_POST['User']['id'])) {
                    $model->password = $oldPassword;
                }
            }

            if ($model->validate()) {
                $model->save();

                echo CJSON::encode([
                    'status' => 'success',
                    'id' => $model->id
                ]);
                Yii::app()->end();
            } else {
                $error = CActiveForm::validate($model, '', false);
                if ($error != '[]') {
                    echo $error;
                }
            }
        }
    }

    public function actionDeleteUsers() {
        $id = $_POST['id'];
        $model = new User();
        $model->deleteByPk($id);
        echo "success";
    }

    public function actionUploadSignature($folder = null) {
        Yii::import("ext.EAjaxUpload.qqFileUploader");
        $folder = Yii::getPathOfAlias('webroot') . '/' . $folder . '/';
        // make the directory to store the pic:
        if (!is_dir($folder)) {
            mkdir($folder, 0777, TRUE);
        }
        $allowedExtensions = array();
        $sizeLimit = 1 * 1024 * 1024; // maximum file size in bytes
        $uploader = new qqFileUploader($allowedExtensions, $sizeLimit);
        $result = $uploader->handleUpload($folder);
        $result['fileType'] = pathinfo($folder . $result['filename'], PATHINFO_EXTENSION);
        $return = htmlspecialchars(json_encode($result), ENT_NOQUOTES);
        $fileName = $result['filename']; //GETTING FILE NAME
        $this->CropuploadImage($folder, $fileName);
        echo $return; // it's array
    }

    function CropuploadImage($folder, $fileName) {
        $imagefile = getimagesize($folder . $fileName);
        if (is_array($imagefile)) {
            $width = 150;
            $height = 200;
            $thumb = Yii::app()->phpThumb->create($folder . '/' . $fileName);
            $thumb->resize($width, $height);
            $thumb->save($folder . '/' . $width . $height . '_' . $fileName);
        }
    }

    public function actionBlockUser() {
        $id = $_POST['id'];
        if ($id > 0) {
            User::model()->updateByPK($id, array('isActive' => "N", 'updated_by' => Yii::app()->user->id, 'updated_date_time' => date('Y-m-d H:i:s')));
            $status['status'] = 'success';
        } else {
            $status['status'] = 'error';
        }
        echo CJSON::encode($status);
    }

    public function actiongetemployeedetails() {
        $employee_id = $_POST['employee_id'];
        if ($employee_id > 0) {
            $model_employee = User::model()->findbyPk($employee_id);
            $data['first_name'] = $this->ciphertext($model_employee->first_name, "d");
            $data['last_name'] = $this->ciphertext($model_employee->last_name, "d");
            $data['phone'] = $model_employee->phone;
            $data['email'] = $model_employee->email;
            $data['designation_name'] = $model_employee->designationdetail->designation_name;
            $data['status'] = 'success';
        } else {
            $data['status'] = 'error';
        }
        echo CJSON::encode($data);
        Yii::app()->end();
    }

}
