<?php

class UsersController 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', 'GetList', 'SaveUsers', 'DeleteUsers'),

                'expression' => '$user->isMember()',

            ),

            array('deny', // deny all users

                'users' => array('*'),

            ),

        );

    }

    public function actionIndex()
    {
        
        $_GET  = filter_input_array(INPUT_GET, FILTER_SANITIZE_SPECIAL_CHARS);
         if(count($_GET) > 0 ){//&& isset(Yii::app()->user->havePermissionOn['admin_users_view'])
            $this->render('index');
         }
         else{
              throw new CHttpException(404, 'Page not found.');
         }

    }

    public function filters()
    {

        return array(

            'accessControl', // perform access control for CRUD operations

        );

    }

    public function actionGetList()
    {
         $_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_SPECIAL_CHARS);
         if(count($_POST) > 0  && $_POST['YII_CSRF_TOKEN'] === Yii::app()->request->csrfToken){// && isset(Yii::app()->user->havePermissionOn['admin_users_view'])
            $model = new User();
            $draw = $_POST['draw'];
            $offset = $_POST['start'];
            $limit = $_POST['length'];
            $status_id = $_POST['status_id'];
            $columns = array(
                // datatable column index  => database column name
                0 => 'username',
                1 => 'first_name',
                2 => 'user_group_id',
                3 => 'isActive',
                4 => 'id',
            );
    
            $filterColumn = $columns[$_POST['order'][0]['column']];
            $filterOrder = $_POST['order'][0]['dir'];
            $orderBy = $filterColumn . " " . $filterOrder;
           // $condition = 't.isActive="Y"';
             $condition = '1=1';
            if($status_id!=""){
                $condition.=' AND isActive="'. $status_id.'"';
                
            }
    
            if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
    
                $searchString = $_POST['search']['value'];
    
                $condition = "username LIKE '%" . $searchString . "%' OR first_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();
    
            foreach ($model as $row) {
    
                $rowData[] = array($row['username'], $row['first_name'] . " " . $row['last_name'],$row['userGroup']['group_name'], $row['isActive'] == 'Y' ? 'Active' : 'Blocked', '<div class="btn-wrap text-center"><button class="btn btn-primary btn-xs" onclick="loadPopupModal(\'users/create&id=' . $row['id'] . '\',\'Users\',\'lg\')"><i class="fa fa-pencil"></i></button></div>',
                 array('id' => $row['id'],'code'=>$row['username'], $row['first_name'] . " " . $row['last_name'], 'status' => $row->isActive));
    
            }
    
            $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 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.js' => false);
    
            $this->render('users_form', array('model' => $model), false, false);
         }
         else{
              //$this->render('../../../../404');
               throw new CHttpException(404, 'Page not found.');
         }
//  && isset(Yii::app()->user->havePermissionOn['admin_users_view'])
    }

    public function actionSaveUsers()
    {
        $_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_SPECIAL_CHARS);
         /*Count of $_POST*/
         if(count($_POST) > 0){
            $model = new User();
            if ((int) @$_POST['User']['id'] > 0) {
                $id = (int) @$_POST['User']['id'];
                $model = $model->findByPk($id);
            }else
            $model->scenario = 'add';
            
            $model->attributes = $_POST['User'];
            $model->isActive = htmlspecialchars($_POST['User']['isActive']);
            $password = trim(htmlspecialchars($_POST['User']['password']));
            if ($password != '') {
                $salt = '$2a$10$1qAz2wSx3eDc4rFv5tGb5t';
                $model->password = crypt($password, $salt);
            }
            $user_group_id = $_POST['User']['user_group_id'];
            if($user_group_id==2){
                $model->level =0;
            }else{
                 $model->level =1;
            }
            if ( $model->validate() ) {
                $model->company_id = 1;
                $model->save();
                echo CJSON::encode(array('status'=>'success'));
            } else {
                echo CActiveForm::validate($model, '', false);
            }
         }
         else{
             throw new CHttpException(404, 'Page not found.');
         }
    }

    public function actionDeleteUsers()
    {
         $_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_SPECIAL_CHARS);
         if(count($_POST) > 0){

            $id = (int) $_POST['id'];
    
            $model = new User();
    
            $model->deleteByPk($id);
    
            echo "success";
         }
         else{
             throw new CHttpException(404, 'Page not found.');
         }

    }

}
