<?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() {
        $this->render('index');
    }

    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    public function actionGetList() {
        $model = new Employee();
        $draw = $_POST['draw'];
        $offset = $_POST['start'];
        $limit = $_POST['length'];
        $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 de_first_name LIKE '%".$searchString."%' OR employee_code LIKE '%".$searchString_en."%')";
        }
        $count = $model->count(array('condition' => $condition));
        $model = $model->findAll(array('condition' => $condition, 'limit' => $limit, 'offset' => $offset, 'order' => 'de_first_name asc'));
        $recordsTotal = $count;
        $recordsFiltered = $count;
        $data['draw'] = $draw;
        $data['recordsTotal'] = $recordsTotal;
        $data['recordsFiltered'] = $recordsFiltered;
        $rowData = array();
        $m = $offset;
        foreach ($model as $row) {
            $rowData[] = array(++$m,$row['employeecode'],$row['employeefullname'],$row->designationdetail->designation_name,array('id' => $row['id'], 'code' => $row['employeefullname']));
        }
        $data['data'] = $rowData;
        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);
        $this->render('users_form', array('model' => $model), false, false);
    }

    public function actionEditUser() {
        $model = new User();
        $modelemployee = new Employee();
        $id = (int) Yii::app()->request->getParam('id');
        if ($id > 0) {
            $condition = 'hr_connected_employee_id ="' . $id . '"';
            $query = 'SELECT * FROM blskymine_nia_hr_main.view_user_details WHERE ' . $condition . ' GROUP BY hr_connected_employee_id';
            $userList = Yii::app()->db->createCommand($query)->queryRow();
            if(!empty($userList)){
                $model->hr_connected_employee_id = $userList['hr_connected_employee_id'];
                $model->username = $userList['username'];
                $model->email = $userList['email'];
                $model->phno = $userList['phno'];
                $model->first_name = $userList['first_name'];
                $model->last_name = $userList['last_name'];
                $model->company_id = $userList['company_id'];
                $model->designation = $userList['designation'];
                $model->user_group_id = $userList['user_group_id'];
                $model->level = $userList['level'];
            }else{
               $userList= $modelemployee->findbyPK($id); 
                $model->hr_connected_employee_id = $id;
                $model->email = $userList['email'];
                $model->phno = $userList['phone'];
                $model->first_name = $this->ciphertext($userList->first_name, "d");
                $model->last_name = $this->ciphertext($userList->last_name, "d");
                $model->company_id = User::DEFAULT_COMPANY_ID;
                $model->username = $this->ciphertext($userList->first_name, "d")."_".$this->ciphertext($userList->employee_code,"d");
                
                $designationquery = 'SELECT designation_name FROM blskymine_nia_hr_data.erp_hr_designation  WHERE id="'.$userList->designation.'"';
                $designation = Yii::app()->db->createCommand($designationquery)->queryRow();
                $model->designation = $designation['designation_name'];
              //  $model->user_group_id = $userList['user_group_id'];
                $model->level = 1;
            }
            $dbname=  MasCompany::MainDB;
            $portalquery = 'SELECT branch_id,department_head_id FROM '.$dbname .'.erp_user WHERE ' . $condition . ' GROUP BY hr_connected_employee_id';
            $user = Yii::app()->db->createCommand($portalquery)->queryRow();
            if(!empty($user)){
                $model->branch_id = $user['branch_id'];
                $model->department_head_id = $user['department_head_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);
        $this->render('users_edit_form', array('model' => $model, 'model_user' => $userList, 'employee_id' => $id), 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 = 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';
            } else {
                $model->created_by = Yii::app()->user->id;
                $model->created_date_time = date('Y-m-d h:i:s');
                $model->scenario = 'add';
            }
            $model->attributes = $_POST['User'];
            $model->is_lead_owner = $_POST['User']['is_lead_owner'];
            $model->signature = $_POST['User']['signature'];
            $model->level = '1';
            $model->branch_id = "";
            $model->email = $_POST['User']['email'];
            $model->phno = $_POST['User']['phno'];
            $model->department_head_id = $_POST['User']['department_head_id'];
            $model->hr_connected_employee_id = $_POST['User']['hr_connected_employee_id'];
            $model->password = $_POST['User']['password'];
            if (isset($_POST['User']['branch_id'])) {
                $model->branch_id = implode(',', $_POST['User']['branch_id']);
            }

            //$company=MasCompany::model()->findByPk(Yii::app()->user->master_user_company_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'];
                    $sql_username_exist = "SELECT id FROM $database_name_1.$usertable_name_1 WHERE username= '" . $model->username . "'";
                    $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;
                    }
                }
            }
            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'])) {
                    if ($flag == 0) {
                        foreach ($_POST['MasUser'] as $i => $each) {
                            if (isset($_POST['arraycid']) && is_array($_POST['arraycid'])) {
                                if (in_array($each['portal_id'], $_POST['arraycid'])) {
                                    $employee_id = $model->hr_connected_employee_id;
                                    $database_name = $each['data_base_name'];
                                    $usertable_name = $each['user_table_name'];
                                    $username = $model->username;
                                    $salt = '$2a$10$1qAz2wSx3eDc4rFv5tGb5t';
                                    $password = crypt($model->password, $salt);
                                    $first_name = $model->first_name;
                                    $last_name = $model->last_name;
                                    $designation = $model->designation;
                                    $user_group_id = $each['user_group_id'];
                                    $email = $model->email;
                                    $phno = $model->phno;
                                    $branch_id = $model->branch_id;
                                    $department_head_id = $model->department_head_id;
                                    $company_id = User::DEFAULT_COMPANY_ID;
                                    $created_by = Yii::app()->user->id;
                                    $created_date_time = date('Y-m-d h:i:s');
                                    //created by not added in data base there is no field in user tables other than HR
                                    // ,
                                    if ($each['portal_id'] == 5) {
                                        $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 {
                                        $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";
                                        }
                                    }
                                }
                            }
                        }
                    }

                    $jsonData['status'] = 'success';
                    $jsonData['frm'] = $users_form;
                    $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 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 = Employee::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();
    }

}
