<?php

class UsergroupController 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',
                    'GetUsergroupList',
                    'hrcreate',
                    'SaveHRUserGroup',
                    'Create',
                    'GetUserGroupLis',
                    'DeleteUserGroup',
                    'SaveUserGroup',
                    'Create_new',
                    'Create_new2',
                    'CopyUsergroup',
                    'SaveCopyUserGroup',
                    'DisableUserGroup'
                ),
                'expression' => '$user->isMember()',
            ),
            array(
                'deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function filters()
    {

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

    public function actionIndex()
    {

        // if (isset(Yii::app()->user->havePermissionOn['admin_usergroup_view']) || Yii::app()->user->authorised_user == 1) {

        // $this->render('index', array(), false, true);

        // }else {
        //         $this->layout = false;
        //         $this->render('/site/unauthorised');
        //         Yii::app()->end();
        //     }
        if (
            Yii::app()->user->authorised_user == 1 ||
            (
                isset(Yii::app()->user->havePermissionOn['admin_menu_view']) &&
                isset(Yii::app()->user->havePermissionOn['admin_usergroup_view']) &&
                Yii::app()->user->havePermissionOn['admin_menu_view'] &&
                Yii::app()->user->havePermissionOn['admin_usergroup_view']
            )
        ) {
            $this->render('index', array(), false, true);
        } else {
            $this->layout = false;
            $this->render('/site/unauthorised');
            Yii::app()->end();
        }
    }
    public function actionCreate()
    {

        $model = new MasUserGroup();
        $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('usergroup_form', array('model' => $model, 'id' => $id), false, true);
        $this->render('usergroup_form_new', array('model' => $model, 'id' => $id), false, true);
    }

    public function actionCreate_new()
    {

        $model = new MasUserGroup();
        $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('usergroup_form_new', array('model' => $model, 'id' => $id), false, true);
    }

    public function actionGetUserGroupList()
    {

        $model = new MasUserGroup();

        $draw = $_POST['draw'];

        $offset = $_POST['start'];

        $limit = $_POST['length'];

        $columns = array(
            // datatable column index  => database column name

            0 => 'group_name',
        );

        $filterColumn = $columns[$_POST['order'][0]['column']];

        $filterOrder = $_POST['order'][0]['dir'];

        $orderBy = $filterColumn . " " . $filterOrder;

        // $condition = '1=1';
        $condition = 't.isActive="Y"';

        if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {

            $searchString = $_POST['search']['value'];

            $condition = " (group_name LIKE '%" . $searchString . "%')";
        }

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

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

        $recordsTotal = $count;

        $recordsFiltered = $count;

        $data['draw'] = $draw;

        $data['recordsTotal'] = $recordsTotal;

        $data['recordsFiltered'] = $recordsFiltered;

        $rowData = array();
        $m = 1;

        foreach ($model as $row) {
            $div = '';
            if (Yii::app()->user->authorised_user == 1 || ((int) Yii::app()->user->havePermissionOn["admin_usergroup_edit"])) {
                // $div .= '<button class="btn btn-primary btn-xs" onclick="loadPopupModal(\'usergroup/create&id='.$row['id'].'\',\'Edit User Group\',\'lg\')"><i class="fa fa-pencil"></i></button> ';
            }
            if (Yii::app()->user->authorised_user == 1 || ((int) Yii::app()->user->havePermissionOn["admin_usergroup_delete"])) {
                // $div .= '<a href ="#" class="btn btn-danger btn-xs" onclick="deleteUserGroup('.$row['id'].')"><i class="fa fa-trash-o "></i></a>';
            }
            $rowData[] = array(
                $row['group_name'],
                '<div class="btn-wrap text-center">' . $div . '</div>',
                array('id' => $row['id'], 'code' => $row['group_name'], 'isActive' => $row['isActive'])
            );

            $m++;
        }


        //      foreach ($model as $row)
//
//      {
//
//
//
//          $rowData[]=array($row['group_name'],'<div class="btn-wrap text-center"><button class="btn btn-primary btn-xs" onclick="loadPopupModal(\'usergroup/create&id='.$row['id'].'\',\'Edit User Group\',\'lg\')"><i class="fa fa-pencil"></i></button> '
//             .'<a href ="#" class="btn btn-danger btn-xs" onclick="deleteUserGroup('.$row['id'].')"><i class="fa fa-trash-o "></i></a></div>');
//                    $m++;
//
//      }

        $data['data'] = $rowData;

        echo json_encode($data);
    }

    public function actionDeleteUserGroup()
    {
        $id = $_POST['id'];
        $model = new MasUserGroup();
        $del = $model->findByPk($id);
        $model->deleteByPk($id);
        // inserting to audit log
        AuditLog::saveAuditLogs(
            'USER_GROUPS',
            Yii::app()->user->id,
            'DELETED',
            " with groupname: - {$del->group_name}  ",
            "",
            ""
        );
        echo "success";
    }

    public function actionSaveUserGroup()
    {
        $model = new MasUserGroup();
        /*         * ********** START Code for Save ************** */
        if (isset($_POST['MasUserGroup'])) {
            $model->created_by = Yii::app()->user->id;
            $model->created_datetime = date('Y-m-d h:i:s');
            if ((int) @$_POST['MasUserGroup']['id'] > 0) {
                $model->updated_by = Yii::app()->user->id;
                $model->updated_datetime = date('Y-m-d h:i:s');
                $model->id = (int) $_POST['MasUserGroup']['id'];
                $model = $model->findByPK($model->id);
                $audit_type = 'UPDATED';
            } else {
                $audit_type = 'CREATED';
                $model->hr_permissions = '{}';
            }
            $model->attributes = $_POST['MasUserGroup'];
            $model->qtn_approval_val_limit = $_POST['MasUserGroup']['qtn_approval_val_limit'];
            $model->order_approval_val_limit = $_POST['MasUserGroup']['order_approval_val_limit'];
            $model->purchase_order_approval_val_limit = $_POST['MasUserGroup']['purchase_order_approval_val_limit'];
            $model->min_profit_percentage = $_POST['MasUserGroup']['min_profit_percentage'];
            $allPermissions = array();
            foreach ($_POST['MasUserGroup']['permissions'] as $eachPermissionArray) {
                if (is_array($eachPermissionArray)) {
                    foreach ($eachPermissionArray as $eachPermission) {
                        $allPermissions[$eachPermission] = 1;
                    }
                }
            }
            $model->permissions = json_encode($allPermissions);
            //            $model->hr_permissions ='{}';
            if ($model->save()) {
                // inserting to audit log
                AuditLog::saveAuditLogs(
                    'USER_GROUPS',
                    Yii::app()->user->id,
                    $audit_type,
                    " with groupname: - {$model->group_name}  ",
                    "",
                    ""
                );
                $jsonData['status'] = 'success';
                echo CJSON::encode($jsonData);
            } else {
                $error = CActiveForm::validate($model, '', false);
                if ($error != '[]')
                    echo $error;
            }
        }
    }

    public function actionhrcreate()
    {

        $model = new MasUserGroup();
        $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('hr_usergroup_form', array('model' => $model, 'id' => $id), false, true);
    }

    public function actionSaveHRUserGroup()
    {
        $model = new MasUserGroup();
        /*         * ********** START Code for Save ************** */
        if (isset($_POST['MasUserGroup'])) {
            $model->created_by = Yii::app()->user->id;
            $model->created_datetime = date('Y-m-d h:i:s');
            if ((int) @$_POST['MasUserGroup']['id'] > 0) {
                $model->updated_by = Yii::app()->user->id;
                $model->updated_datetime = date('Y-m-d h:i:s');
                $model->id = (int) $_POST['MasUserGroup']['id'];
                $model = $model->findByPK($model->id);
                $model->scenario = 'update';
            } else {
                $model->scenario = 'add';
            }
            $model->group_name = $_POST['MasUserGroup']['group_name'];
            $allPermissions = array();
            foreach ($_POST['MasUserGroup']['permissions'] as $eachPermissionArray) {
                if (is_array($eachPermissionArray)) {
                    foreach ($eachPermissionArray as $eachPermission) {
                        $allPermissions[$eachPermission] = 1;
                    }
                }
            }
            $model->hr_permissions = json_encode($allPermissions);
            if (isset($_POST['MasUserGroup']['snapshot_tab_permission']) && count($_POST['MasUserGroup']['snapshot_tab_permission']) > 0) {
                $model->snapshot_tab_permission = implode(',', $_POST['MasUserGroup']['snapshot_tab_permission']);
            } else {
                $model->snapshot_tab_permission = "";
            }
            if (isset($_POST['MasUserGroup']['personal_tab_permission']) && count($_POST['MasUserGroup']['personal_tab_permission']) > 0) {
                $model->personal_tab_permission = implode(',', $_POST['MasUserGroup']['personal_tab_permission']);
            } else {
                $model->personal_tab_permission = "";
            }
            if (isset($_POST['MasUserGroup']['nominee_tab_permission']) && count($_POST['MasUserGroup']['nominee_tab_permission']) > 0) {
                $model->nominee_tab_permission = implode(',', $_POST['MasUserGroup']['nominee_tab_permission']);
            } else {
                $model->nominee_tab_permission = "";
            }
            if (isset($_POST['MasUserGroup']['contact_tab_permission']) && count($_POST['MasUserGroup']['contact_tab_permission']) > 0) {
                $model->contact_tab_permission = implode(',', $_POST['MasUserGroup']['contact_tab_permission']);
            } else {
                $model->contact_tab_permission = "";
            }
            if (isset($_POST['MasUserGroup']['document_tab_permission']) && count($_POST['MasUserGroup']['document_tab_permission']) > 0) {
                $model->document_tab_permission = implode(',', $_POST['MasUserGroup']['document_tab_permission']);
            } else {
                $model->document_tab_permission = "";
            }
            if (isset($_POST['MasUserGroup']['assets_tab_permission']) && count($_POST['MasUserGroup']['assets_tab_permission']) > 0) {
                $model->assets_tab_permission = implode(',', $_POST['MasUserGroup']['assets_tab_permission']);
            } else {
                $model->assets_tab_permission = "";
            }
            if (isset($_POST['MasUserGroup']['salary_tab_permission']) && count($_POST['MasUserGroup']['salary_tab_permission']) > 0) {
                $model->salary_tab_permission = implode(',', $_POST['MasUserGroup']['salary_tab_permission']);
            } else {
                $model->salary_tab_permission = "";
            }
            if (isset($_POST['MasUserGroup']['loan_tab_permission']) && count($_POST['MasUserGroup']['loan_tab_permission']) > 0) {
                $model->loan_tab_permission = implode(',', $_POST['MasUserGroup']['loan_tab_permission']);
            } else {
                $model->loan_tab_permission = "";
            }
            if (isset($_POST['MasUserGroup']['bank_tab_permission']) && count($_POST['MasUserGroup']['bank_tab_permission']) > 0) {
                $model->bank_tab_permission = implode(',', $_POST['MasUserGroup']['bank_tab_permission']);
            } else {
                $model->bank_tab_permission = "";
            }
            if (isset($_POST['MasUserGroup']['eos_tab_permission']) && count($_POST['MasUserGroup']['eos_tab_permission']) > 0) {
                $model->eos_tab_permission = implode(',', $_POST['MasUserGroup']['eos_tab_permission']);
            } else {
                $model->eos_tab_permission = "";
            }
            if (isset($_POST['MasUserGroup']['other_tab_permission']) && count($_POST['MasUserGroup']['other_tab_permission']) > 0) {
                $model->other_tab_permission = implode(',', $_POST['MasUserGroup']['other_tab_permission']);
            } else {
                $model->other_tab_permission = "";
            }
            if (isset($_POST['MasUserGroup']['inout_doc_tab_permission']) && count($_POST['MasUserGroup']['inout_doc_tab_permission']) > 0) {
                $model->inout_doc_tab_permission = implode(',', $_POST['MasUserGroup']['inout_doc_tab_permission']);
            } else {
                $model->inout_doc_tab_permission = "";
            }
            if (isset($_POST['MasUserGroup']['issue_doc_tab_permission']) && count($_POST['MasUserGroup']['issue_doc_tab_permission']) > 0) {
                $model->issue_doc_tab_permission = implode(',', $_POST['MasUserGroup']['issue_doc_tab_permission']);
            } else {
                $model->issue_doc_tab_permission = "";
            }
            if (isset($_POST['MasUserGroup']['training_tab_permission']) && count($_POST['MasUserGroup']['training_tab_permission']) > 0) {
                $model->training_tab_permission = implode(',', $_POST['MasUserGroup']['training_tab_permission']);
            } else {
                $model->training_tab_permission = "";
            }
            if (isset($_POST['MasUserGroup']['notes_tab_permission']) && count($_POST['MasUserGroup']['notes_tab_permission']) > 0) {
                $model->notes_tab_permission = implode(',', $_POST['MasUserGroup']['notes_tab_permission']);
            } else {
                $model->notes_tab_permission = "";
            }
            if (isset($_POST['MasUserGroup']['leave_tab_permission']) && count($_POST['MasUserGroup']['leave_tab_permission']) > 0) {
                $model->leave_tab_permission = implode(',', $_POST['MasUserGroup']['leave_tab_permission']);
            } else {
                $model->leave_tab_permission = "";
            }
            if (isset($_POST['MasUserGroup']['level_tab_permission']) && count($_POST['MasUserGroup']['level_tab_permission']) > 0) {
                $model->level_tab_permission = implode(',', $_POST['MasUserGroup']['level_tab_permission']);
            } else {
                $model->level_tab_permission = "";
            }
            if (isset($_POST['MasUserGroup']['qualification_tab_permission']) && count($_POST['MasUserGroup']['qualification_tab_permission']) > 0) {
                $model->qualification_tab_permission = implode(',', $_POST['MasUserGroup']['qualification_tab_permission']);
            } else {
                $model->qualification_tab_permission = "";
            }
            if ($model->save()) {
                $jsonData['status'] = 'success';
                echo CJSON::encode($jsonData);
            } else {
                $error = CActiveForm::validate($model, '', false);
                if ($error != '[]')
                    echo $error;
            }
        }
    }


    public function actionCopyUsergroup()
    {

        $model = new MasUserGroup();
        $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('usergroup_copy_form', array('model' => $model, 'id' => $id, 'type' => 'Copy'), false, true);
    }

    public function actionSaveCopyUserGroup()
    {

        $model = new MasUserGroup();
        $type = $_POST['type'];
        if (isset($_POST['MasUserGroup'])) {
            $id = $_POST['MasUserGroup']['id'];
            if ($type == "Copy") {
                $id = 0;
            }


            $model->created_by = Yii::app()->user->id;
            $model->created_datetime = date('Y-m-d h:i:s');
            if ($id > 0) {
                $model->updated_by = Yii::app()->user->id;
                $model->updated_datetime = date('Y-m-d h:i:s');
                $model->id = (int) $_POST['MasUserGroup']['id'];
                $model = $model->findByPK($model->id);
                $audit_type = 'UPDATED';
            } else {
                $audit_type = 'CREATED';
                $model->hr_permissions = '{}';
            }
            $model->attributes = $_POST['MasUserGroup'];
            $model->group_name = $_POST['MasUserGroup']['group_name'];
            $model->qtn_approval_val_limit = $_POST['MasUserGroup']['qtn_approval_val_limit'];
            $model->order_approval_val_limit = $_POST['MasUserGroup']['order_approval_val_limit'];
            $model->purchase_order_approval_val_limit = $_POST['MasUserGroup']['purchase_order_approval_val_limit'];
            $model->min_profit_percentage = $_POST['MasUserGroup']['min_profit_percentage'];
            $allPermissions = array();
            foreach ($_POST['MasUserGroup']['permissions'] as $eachPermissionArray) {
                if (is_array($eachPermissionArray)) {
                    foreach ($eachPermissionArray as $eachPermission) {
                        $allPermissions[$eachPermission] = 1;
                    }
                }
            }
            $model->permissions = json_encode($allPermissions);
            if ($model->save()) {
                // inserting to audit log
                AuditLog::saveAuditLogs(
                    'USER_GROUPS',
                    Yii::app()->user->id,
                    $audit_type,
                    " with groupname: - {$model->group_name}  ",
                    "",
                    ""
                );
                $jsonData['status'] = 'success';
                echo CJSON::encode($jsonData);
            } else {
                $error = CActiveForm::validate($model, '', false);
                if ($error != '[]')
                    echo $error;
            }
        }
    }

    public function actionDisableUserGroup()
    {
        $jsonData = array();

        if (isset($_POST['id']) && isset($_POST['status'])) {
            $id = $_POST['id'];
            $status = $_POST['status'];

            $model = MasUserGroup::model()->findByPk($id);

            if ($model !== null) {
                $model->isActive = ($status == 'Y') ? 'N' : 'Y';

                if ($model->save(false)) {
                    $jsonData['status'] = 'success';
                } else {
                    $jsonData['status'] = 'fail';
                    $jsonData['message'] = 'Failed to update the record.';
                }
            } else {
                $jsonData['status'] = 'fail';
                $jsonData['message'] = 'User group not found.';
            }
        }

        echo CJSON::encode($jsonData);
        Yii::app()->end();
    }

}
