<?php

class DistributerController 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_SPECIAL_CHARS);
        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_SPECIAL_CHARS);
        if(count($_POST) > 0){
            $model = new Distributers();
            $draw = $_POST['draw'];
            $offset = $_POST['start'];
            $limit = $_POST['length'];
            $id=$_POST['distributer_id'];
            $columns = array(
                // datatable column index  => database column name
                0 => 't.id',
                1 => 'dis_det.distributer_type',
                2 => 'distributer_name',
                3 => 'alias_name',
                4 => 'alias_2_name',
                5 => 'region_det.region_name',
                6 => 't.id'
            );
            $filterColumn = $columns[$_POST['order'][0]['column']];
            $filterOrder = $_POST['order'][0]['dir'];
            $orderBy = $filterColumn . " " . $filterOrder;
            $condition = 't.isActive="Y"';
            if($id>0)
            {
              $condition.=' AND t.id ='. $id;    
            }
            if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
                $searchString = $_POST['search']['value'];
                $condition = " (distributer_name LIKE '%" . $searchString . "%' OR alias_name LIKE '%" . $searchString . "%' OR region_det.region_name LIKE '%" . $searchString . "%' OR dis_det.distributer_type LIKE '%" . $searchString . "%' )";
            }
            $count = $model->with('region_det','dis_det')->count(array('condition' => $condition));
            $model = $model->with('region_det','dis_det')->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_distributer_edit"])) {
                     $div .=   '<div class="btn-wrap text-center"><button class="btn btn-primary btn-xs" onclick="loadPopupModal(\'distributer/create&id='.$row['id'].'\',\'Edit Distributor\',\'lg\')"><i class="fa fa-pencil"></i></button>';
                }
                $rowData[] = array($m,
                    $row['dis_det']['distributer_type'],
                    $row['distributer_name'],
                    $row['alias_name'],
                    $row['alias_2_name'],
                    $row['alias_3_name'],
                    $row['region_det']['region_name'],
                    '<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_SPECIAL_CHARS);
        if(count($_GET) > 0){
            $model = new Distributers();
            $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_SPECIAL_CHARS);
        if(count($_POST) > 0){
            $model = new Distributers();
            if (isset($_POST['Distributers'])) {
                    $model->created_by = Yii::app()->user->id;
                    $model->created_date_time = date("Y-m-d H:i:s");
                if ((int) @$_POST['Distributers']['id'] > 0) {
                    $id = (int) @$_POST['Distributers']['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['Distributers'];
                $model->distributer_name    = trim($_POST['Distributers']['distributer_name']);
                $model->alias_name          = trim($_POST['Distributers']['alias_name']);
                $model->alias_2_name        = trim($_POST['Distributers']['alias_2_name']);
                $model->alias_3_name        = trim($_POST['Distributers']['alias_3_name']);
                $model->alias_4_name        = trim($_POST['Distributers']['alias_4_name']);
                $model->alias_5_name        = trim($_POST['Distributers']['alias_5_name']);
                $model->consider_for_ch_report= trim($_POST['Distributers']['consider_for_ch_report']);
                $model->area_id= trim($_POST['Distributers']['area_id']);
                if ($model->save()) {
                    $jsonData['status'] = 'success';
                    $jsonData['frm'] = $_POST['Distributers'];
                    $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.');
        }
    }

    /*public function actionDelete() {

        $id = $_POST['id'];
        $model_c = Customer::model()->findAll(array('condition' => 'customer_country = ' . $id . ' '));
        $model_com = Company::model()->findAll(array('condition' => 'shipping_country = ' . $id . ' '));
        if (empty($model_c) && empty($model_com)) {
            $model = new Distributers();
            $model->deleteByPk($id);
            echo "success";
        } else {
            echo "fail";
        }
    }*/


}
