<?php
class MasinvbinController extends Controller
{
    public function getViewPath($checkTheme=false)
    {
        return Yii::getPathOfAlias('application.views.front.masinvbin');
    }

    public function accessRules()
    {
        return array(
            array('allow',
                'actions' => array('login', 'error', 'logout', 'newlogin'),
                'users' => array('*'),
            ),
            array('allow',
                'actions' => array('index', 'GetList', 'Create', 'SaveBin', 'Disable'),
                'expression' => '$user->isMember()',
            ),
            array('deny',
                'users' => array('*'),
            ),
        );
    }

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

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

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

        $criteria = new CDbCriteria();
        $criteria->condition = '1=1';

        if (isset($_POST['search']['value']) && $_POST['search']['value'] != "") {
            $searchString = $_POST['search']['value'];
            // Join rack table for search
            $criteria->join = 'LEFT JOIN {{mas_inv_rack}} r ON t.rack_id = r.id';
            $criteria->addCondition(
                "(t.bin_name LIKE :search OR r.rack_name LIKE :search)"
            );
            $criteria->params[':search'] = '%' . $searchString . '%';
        }

        $count = $model->count($criteria);

        $criteria->with  = array('rack'); // load relation for display only
        $criteria->limit  = $limit;
        $criteria->offset = $offset;
        $criteria->order  = 't.id ASC';

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

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

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

        foreach ($models as $row) {
            $status    = $row->isActive   == 'Y' ? 'Active'  : 'Inactive';
            $isDefault = $row->is_base_bin == 'Y' ? true : false;
            $rackName  = $row->rack ? $row->rack->rack_name : '-';

            $rowData[] = array(
                ++$m,
                $row->bin_name,
                $rackName,
                $status,
                array(
                    'id'         => $row->id,
                    'status'     => $row->isActive,
                    'is_default' => $row->is_base_bin
                )
            );
        }

        $data['data'] = $rowData;
        echo json_encode($data);
    }

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

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

        // Load active racks for dropdown
        $racks = MasInvRack::model()->findAll(array(
            'condition' => "isActive = 'Y'",
            'order'     => 'rack_name ASC'
        ));
        $rackList = CHtml::listData($racks, 'id', 'rack_name');

        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
        );

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

    public function actionSaveBin()
    {
        if (isset($_POST['MasInvBin'])) {
            $id = (int) $_POST['MasInvBin']['id'];

            // Server-side validation
            $errors = array();
            if (empty(trim($_POST['MasInvBin']['bin_name']))) {
                $errors[] = "Bin Name should not be empty.";
            }
            if (empty($_POST['MasInvBin']['rack_id'])) {
                $errors[] = "Rack should not be empty.";
            }
            if (empty($_POST['MasInvBin']['isActive'])) {
                $errors[] = "Status should not be empty.";
            }
            if (!empty($errors)) {
                echo CJSON::encode(array('status' => 'error', 'message' => implode(' ', $errors)));
                return;
            }

            if ($id > 0) {
                $model = MasInvBin::model()->findByPk($id);
                $model->attributes       = $_POST['MasInvBin'];
                $model->updated_by       = Yii::app()->user->id;
                $model->updated_datetime = date('Y-m-d H:i:s');
            } else {
                $model = new MasInvBin();
                $model->attributes       = $_POST['MasInvBin'];
                $model->created_by       = Yii::app()->user->id;
                $model->updated_by       = Yii::app()->user->id;
                $model->created_datetime = date('Y-m-d H:i:s');
                $model->updated_datetime = date('Y-m-d H:i:s');
            }

            // If setting as default, clear previous default and force Active
            if ($model->is_base_bin == 'Y') {
                Yii::app()->db->createCommand()
                    ->update('{{mas_inv_bin}}', array('is_base_bin' => 'N'));
                $model->isActive = 'Y'; // default bin must always be active
            }

            if ($model->save()) {
                $jsonData['status'] = 'success';
                $jsonData['frm']    = $_POST['bin-form'];
                $jsonData['id']     = $model->id;
                echo CJSON::encode($jsonData);
            } else {
                echo CActiveForm::validate($model);
            }
        }
    }

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

        $model = MasInvBin::model()->findByPk($id);
        if ($model) {
            // Block disabling if this is the default bin
            if ($model->is_base_bin == 'Y' && $status == 'Y') {
                echo json_encode(array("status" => "error", "message" => "Default bin cannot be set as inactive."));
                return;
            }
            $model->isActive         = ($status == "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"));
    }


}
?>