<?php
class MasregionController 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', 'Save', 'Delete'),
                'expression' => '$user->isMember()',
            ),
            array('deny', // deny all users
                'users' => array('*'),
            ),
        );
    }

    public function actionIndex() {
        $_GET  = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
        if(count($_GET) > 0){
            $this->render('index');
        }
        else{
              throw new CHttpException(404, 'Page not found.');
        }
    }

    // Uncomment the following methods and override them if needed
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    public function actionGetList() {
        $_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
        if(count($_POST) > 0){
            $model = new MasRegion();
            $draw = $_POST['draw'];
            $offset = $_POST['start'];
            $limit = $_POST['length'];
            $columns = array(
                // datatable column index  => database column name
                0 => 'id',
                1 => 'region_name',
                2 => 'currency_type',
                3 => 'sort_order'
            );
            $filterColumn = $columns[$_POST['order'][0]['column']];
            $filterOrder = $_POST['order'][0]['dir'];
            //$orderBy = 't.sort_order';
            $orderBy = $filterColumn . " " . $filterOrder;
            $condition = 't.is_active="Y"';
            if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
                $searchString = $_POST['search']['value'];
                $condition .= " and (region_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["master_region_edit"])) {
                     $div .=   '<div class="btn-wrap text-center"><button class="btn btn-primary btn-xs" onclick="loadPopupModal(\'masregion/create&id='.$row['id'].'\',\'Edit Price Type\',\'lg\')"><i class="fa fa-pencil"></i></button>';
                }
                $rowData[] = array($m,
                    $row['region_name'],
                     $row['currency_type'],
                      $row['sort_order'],
                    '<div class="btn-wrap text-center">' . $div . '</div>');
    
                $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_STRING);
        if(count($_GET) > 0){
            $model = new MasRegion();
            $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('create', array('model' => $model), false, false);
        }
        else{
              throw new CHttpException(404, 'Page not found.');
        }
    }

    public function actionSave() {
        $_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
        if(count($_POST) > 0){
            $model = new MasRegion();
            
            if (isset($_POST['MasRegion'])) {
                $model->created_by = Yii::app()->user->id;
                $model->created_date_time = date("Y-m-d H:i:s");
                if ((int) @$_POST['MasRegion']['id'] > 0) {
                    $id = (int) @$_POST['MasRegion']['id'];
                    $model = $model->findByPk($id);
                    $model->updated_by = Yii::app()->user->id;
		            $model->updated_date_time = date("Y-m-d H:i:s");
                }
                
                $model->attributes = $_POST['MasRegion'];
                $model->region_name=trim($_POST['MasRegion']['region_name']);
                $sort_order=$_POST['MasRegion']['sort_order'];
                if ($model->save()) {
                    $modMasRegion = new MasRegion();
                    $modMasRegion->find(['condition' => 'sort_order=' . $sort_order . ' AND id!=' . (int)$model->id]);
                    if (!empty($modMasRegion)) {
                        $mod_Region = new MasRegion();
                        $mod_history = $mod_Region->findAll(['condition' => 'sort_order>=' . $sort_order .' AND id!=' . (int)$model->id, 'order' => 'sort_order ASC']);
                        foreach ($mod_history as $each) {
                            $sort_order++;
                            $each->sort_order = (int)$sort_order;
                            $each->save(false);
                        }
                    }
                    $jsonData['status'] = 'success';
                    $jsonData['frm'] = $_POST['MasRegion'];
                    $jsonData['id'] = $model->id;
                    echo CJSON::encode($jsonData);
                } else {
                    $error = CActiveForm::validate($model, '', false);
                    if ($error != '[]')
                        echo $error;
                }
            }
        }
        else{
              throw new CHttpException(404, 'Page not found.');
        }
    }
}
