<?php

class UsergroupController extends Controller
{
    /*public function init() {
        parent::init();
        $this->initAjaxCsrfToken();
    }
 
    // this function will work to post csrf token.
    protected function initAjaxCsrfToken() {
 
        Yii::app()->clientScript->registerScript('AjaxCsrfToken', ' $.ajaxSetup({
                         data: {"' . Yii::app()->request->csrfToken . '": "' . Yii::app()->request->csrfToken . '"},
                         cache:false
                    });', CClientScript::POS_HEAD);
    } 
*/
    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', 'GetUsergroupList', 'SaveUsers', 'DeleteUsers','SaveUserGroup'),

                '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()
    {
        $_GET  = filter_input_array(INPUT_GET, FILTER_SANITIZE_SPECIAL_CHARS);
        if(count($_GET) > 0){

            $this->render('index');
        }
        else{
              throw new CHttpException(404, 'Page not found.');
         }

    }
    public function actionGetUserGroupList() {
        $_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_SPECIAL_CHARS);
        if(count($_POST) > 0){
            $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 = 't.isActive="Y"';
            if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
                $searchString = $_POST['search']['value'];
                $condition .= " AND (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']));
                $m++;
            }
    
            $data['data'] = $rowData;
    
            echo json_encode($data);
         }
         else{
              throw new CHttpException(404, 'Page not found.');
         }
    }
    public function actionCreate() {
        $_GET  = filter_input_array(INPUT_GET, FILTER_SANITIZE_SPECIAL_CHARS);
        if(count($_GET) > 0){
            $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.js' => false);
            //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);
        }
        else{
              throw new CHttpException(404, 'Page not found.');
        }
    }
     public function actionSaveUserGroup() {
        $_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_SPECIAL_CHARS);
        if(count($_POST) > 0){
        $model = new MasUserGroup();
        /*         * ********** START Code for Save ************** */
            if (isset($_POST['MasUserGroup'])) {
                if ((int) @$_POST['MasUserGroup']['id'] > 0) {
                    $model->id = (int) $_POST['MasUserGroup']['id'];
                    $model = $model->findByPK($model->id);
                }
                $model->attributes = $_POST['MasUserGroup'];
                $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()) {
                    $jsonData['status'] = 'success';
                    echo CJSON::encode($jsonData);
                } else {
                    $error = CActiveForm::validate($model, '', false);
                    if ($error != '[]')
                        echo $error;
                }
            }
        }
        else{
              throw new CHttpException(404, 'Page not found.');
        }
    }

}
