<?php

class MasSubBrandsController extends Controller
{
    public function filters()
    {
        return array('accessControl');
    }

    public function accessRules()
    {
        return array(
            array('allow',
                'actions'=>array('index','getList','create','disable'),
                'users'=>array('@'),
            ),
            array('deny',
                'users'=>array('*'),
            ),
        );
    }

    public function actionIndex()
    {
        $this->render('index');
    }

    public function actionGetList()
    {
        $model = new MasSubBrands();

        $draw   = $_POST['draw'];
        $offset = $_POST['start'];
        $limit  = $_POST['length'];

        $condition = '1=1';

        $count = $model->count(array('condition'=>$condition));

        $rows = $model->findAll(array(
            'condition'=>$condition,
            'limit'=>$limit,
            'offset'=>$offset,
            'order'=>'sub_brand_name ASC'
        ));

        $data['draw'] = $draw;
        $data['recordsTotal'] = $count;
        $data['recordsFiltered'] = $count;

        $result = array();
        $m = $offset;

        foreach($rows as $row){
            $result[] = array(
                ++$m,
                $row->sub_brand_name,
                array(
                    'id'=>$row->id,
                    'status'=>$row->isActive
                )
            );
        }

        $data['data'] = $result;

        echo json_encode($data);
        Yii::app()->end();
    }

    public function actionCreate()
    {
        $model = new MasSubBrands();
        $id = (int) Yii::app()->request->getParam('id');

        if($id>0){
            $model = MasSubBrands::model()->findByPk($id);
        }

        if(isset($_POST['MasSubBrands'])){
            $model->attributes = $_POST['MasSubBrands'];

            if($model->isNewRecord){
                $model->created_by = Yii::app()->user->id;
                $model->created_datetime = date('Y-m-d H:i:s');
                $model->isActive = 'Y';
            }

            $model->updated_by = Yii::app()->user->id;
            $model->updated_datetime = date('Y-m-d H:i:s');

            if($model->save()){
                $this->redirect(array('index'));
            }
        }

        $this->render('create', array('model'=>$model), false, true);
    }

    public function actionDisable()
    {
        $id = Yii::app()->request->getParam('id');

        $model = MasSubBrands::model()->findByPk($id);

        if($model){
            $model->isActive = ($model->isActive == 'Y') ? 'N' : 'Y';
            $model->updated_by = Yii::app()->user->id;
            $model->updated_datetime = date('Y-m-d H:i:s');
            $model->save();
        }

        echo json_encode(array('status'=>'success'));
        Yii::app()->end();
    }
}