<?php

class CategorytypeController 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()
	{
		//if (isset(Yii::app()->user->havePermissionOn['master_category_type_name_view']) || Yii::app()->user->authorised_user == 1) {
		$_GET  = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
		if (count($_GET) > 0) {
			$this->render('index');
		} else {
			throw new CHttpException(404, 'Page not found.');
		}
		/*} else {
			throw new CHttpException(401, 'Unauthorized Access');
		}*/
	}

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


	/**
	 * Creates a new model.
	 * If creation is successful, the browser will be redirected to the 'view' page.
	 */


	public function actionCreate()
	{
		$_GET  = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
		if (count($_GET) > 0) {
			$model = new MasCategoryType();
			$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 actionGetList()
	{
		$_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
		if (count($_POST) > 0) {
			$model = new MasCategoryType();
			$draw = $_POST['draw'];
			$offset = $_POST['start'];
			$limit = $_POST['length'];
			$columns = array(
				// datatable column index  => database column name
				0 => 'id',
				1 => 'category_type_name',
				2 => 'id',
			);
			$filterColumn = $columns[$_POST['order'][0]['column']];
			$filterOrder = $_POST['order'][0]['dir'];
			$orderBy = $filterColumn . " " . $filterOrder;
			$condition = '1=1 ';
			if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
				$searchString = $_POST['search']['value'];
				$condition .= " and (category_type_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_category_type_name_edit"])) {
					$div .=   '<div class="btn-wrap text-center"><button class="btn btn-primary btn-xs" onclick="loadPopupModal(\'categorytype/create&id=' . $row['id'] . '\',\'Edit Category Type\',\'xs\')"><i class="fa fa-pencil"></i></button>';
				//}
				$rowData[] = array(
					$m,
					$row['category_type_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 actionSave()
	{
		$_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);
		if (count($_POST) > 0) {
			$model = new MasCategoryType();
			if (isset($_POST['MasCategoryType'])) {
				$model->created_by = Yii::app()->user->id;
				$model->created_datetime = date("Y-m-d H:i:s");
				if ((int) @$_POST['MasCategoryType']['id'] > 0) {
					$id = (int) @$_POST['MasCategoryType']['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['MasCategoryType'];
				if ($model->save()) {
					$jsonData['status'] = 'success';
					$jsonData['frm'] = $_POST['MasCategoryType'];
					$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.');
		}
	}
}
