<?php

class SubcategoryController extends Controller
{   
    public function accessRules() {
        return array(
            array('allow',
                'actions' => array('login', 'error', 'logout', 'newlogin'),
                'users' => array('*'),
            ),
            array('allow',
                'actions' => array('Index', 'GetList', 'create', 'save','Disable'),
                'expression' => '$user->isMember()',
            ),
            array('deny',
                'users' => array('*'),
            ),
        );
    }

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

    public function actionGetList()
    {
        $draw   = isset($_POST['draw'])   ? (int) $_POST['draw']   : 1;
        $offset = isset($_POST['start'])  ? (int) $_POST['start']  : 0;
        $limit  = isset($_POST['length']) ? (int) $_POST['length'] : 50;

        $criteria = new CDbCriteria();
        $criteria->with = array('category');
        $criteria->together = true;

        if (!empty($_POST['search']['value'])) {
            $search = $_POST['search']['value'];
            $criteria->addSearchCondition('t.id', $search, true, 'OR');
            $criteria->addSearchCondition('t.sub_category_name', $search, true, 'OR');
            $criteria->addSearchCondition('category.category_name', $search, true, 'OR');
        }

        $total = SubCategory::model()->count($criteria);

        $criteria->limit  = $limit;
        $criteria->offset = $offset;
        $criteria->order  = 'category.category_name ASC';

        $models = SubCategory::model()->findAll($criteria);

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

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

        foreach ($models as $row) {
            $status = ($row->isActive === 'Y')
                ? '<span class="label label-success">Active</span>'
                : '<span class="label label-warning">Inactive</span>';

            $rowData[] = array(
                ++$m,
                !empty($row->category) ? $row->category->category_name : '-',
                $row->sub_category_name,
                $status,
                array(
                    'id'     => $row->id,
                    'code'   => $row->sub_category_name,
                    'status' => $row->isActive
                )
            );
        }

        $data['data'] = $rowData;

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

    public function actionCreate()
    {
        $model = new SubCategory();

        $id = (int) Yii::app()->request->getParam('id');

        if ($id > 0) {
            $model = SubCategory::model()->findByPk($id);
            if ($model === null) {
                throw new CHttpException(404, 'Sub Category not found');
            }
        }

        $categories = Category::getCategories();

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

    public function actionSave()
    {
        if (!isset($_POST['SubCategory'])) {
            throw new CHttpException(400, 'Invalid request.');
        }

        $post   = $_POST['SubCategory'];
        $isEdit = isset($post['id']) && (int)$post['id'] > 0;

        if ($isEdit) {
            $model = SubCategory::model()->findByPk((int)$post['id']);
            if (!$model) {
                echo CJSON::encode(array(
                    'status'  => 'error',
                    'message' => 'Sub Category not found'
                ));
                Yii::app()->end();
            }
            $model->updated_by       = Yii::app()->user->id;
            $model->updated_datetime = date('Y-m-d H:i:s');
        } else {
            $model = new SubCategory();
            $model->created_by       = Yii::app()->user->id;
            $model->created_datetime = date('Y-m-d H:i:s');
            $model->isActive         = 'Y';
        }

        $model->attributes = $post;

        if (!$isEdit) {
            $categoryId = (int)$post['category_id'];
            $subNo      = (int)$post['sub_category_name'];
            $model->id  = ($categoryId * 100) + $subNo;
        }

        if (!$model->save()) {
            $errors        = $model->getErrors();
            $errorMessages = array();
            foreach ($errors as $fieldErrors) {
                $errorMessages = array_merge($errorMessages, $fieldErrors);
            }
            echo CJSON::encode(array(
                'status'  => 'error',
                'message' => implode(', ', $errorMessages)
            ));
        } else {
            echo CJSON::encode(array(
                'status' => 'success',
                'id'     => $model->id
            ));
        }

        Yii::app()->end();
    }

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

    $model = new SubCategory();
    $model = $model->findByPk($id);

    if($model === null){
        echo json_encode(array('status' => 'fail'));
        Yii::app()->end();
    }

    $model->isActive = ($status == 'Y') ? 'N' : 'Y';
    $model->save();

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