<?php

/* 
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

class MasproductcategoryController 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 MasProductCategory();
            $draw = $_POST['draw'];
            $offset = $_POST['start'];
            $limit = $_POST['length'];
            $columns = array(
                // datatable column index  => database column name
                0 => 'id',
                1 => 'product_category',
                2 => 'is_active',
                3 => 'sort_order',4 => 'report_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 (product_category 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_product_edit"])) {
                     $div .=   '<div class="btn-wrap text-center"><button class="btn btn-primary btn-xs" onclick="loadPopupModal(\'masproductcategory/create&id='.$row['id'].'\',\'Edit Product Category\',\'lg\')"><i class="fa fa-pencil"></i></button>';
                }
                /*      if($row['supply_month_type']=='CM'){
                           $month_type='Current Month';
                        }
                        else if($row['supply_month_type']=='CM-1'){
                         $month_type='Current Month-1';   
                        }
                        else if($row['supply_month_type']=='CM-2'){
                         $month_type='Current Month-2';   
                        }
                        else if($row['supply_month_type']=='CM-3'){
                         $month_type='Current Month-3';   
                        }
                        else{
                            $month_type='Current Month-4'; 
                        }
                        */
                $rowData[] = array($m,
                    $row['product_category'],
                    
                    $row['is_active'],
                     $row['sort_order'],$row['report_sort_order'].'/'.$row['report_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 MasProductCategory();
            $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 MasProductCategory();
            if (isset($_POST['MasProductCategory'])) {
                $model->created_by = Yii::app()->user->id;
                $model->created_date_time = date("Y-m-d H:i:s");
                if ((int) @$_POST['MasProductCategory']['id'] > 0) {
                    $id = (int) @$_POST['MasProductCategory']['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['MasProductCategory'];
                $model->product_category=trim($_POST['MasProductCategory']['product_category']);
                if ($model->save()) {
                    $jsonData['status'] = 'success';
                    $jsonData['frm'] = $_POST['MasProductCategory'];
                    $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 MasProductCategory();
            $model->deleteByPk($id);
            echo "success";
        } else {
            echo "fail";
        }
    }*/


}
