<?php
class InventoryProductsController 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()
    {
        $user_id = (int) Yii::app()->user->id;
        $modeluser = User::model()->findByPk($user_id);
        if ($modeluser->user_group_id != 1) {
            $this->redirect(Yii::app()->baseUrl . '/index.php');
            Yii::app()->end();
        }

        $this->render('index');
    }

public function actionGetList()
{
    header('Content-Type: application/json');

    $draw   = isset($_POST['draw']) ? intval($_POST['draw']) : 1;
    $start  = isset($_POST['start']) ? intval($_POST['start']) : 0;
    $length = isset($_POST['length']) ? intval($_POST['length']) : 10;

    $criteria = new CDbCriteria();
    $total = InventoryProducts::model()->count();

    $criteria->limit  = $length;
    $criteria->offset = $start;
    $criteria->order  = "id DESC";

    $rows = InventoryProducts::model()->findAll($criteria);

    $data = [];

    foreach ($rows as $row) {
        $data[] = [
            "id" => $row->id,
            "sku" => $row->sku,
            "product_name" => $row->product_name,
            "brand" => $row->brand,
            "category" => $row->category,
            "quantity" => $row->quantity,
            "price" => $row->price,
            "isActive" => $row->isActive
        ];
    }

    echo json_encode([
        "draw" => $draw,
        "recordsTotal" => $total,
        "recordsFiltered" => $total,
        "data" => $data
    ]);

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

   public function actionCreate()
{
    // Force Yii to reload the table columns
    Yii::app()->db->schema->refresh();

    $id = (int) Yii::app()->request->getParam('id');
    $model = ($id > 0) ? InventoryProducts::model()->findByPk($id) : new InventoryProducts();

    Yii::app()->clientScript->scriptMap = array(
        '*jquery.js' => false,
        '*jquery.min.js' => false,
        '*jquery-ui.js' => false,
        '*jquery-ui.min.js' => false
    );

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

public function actionSave()
{
    header('Content-Type: application/json');

    if (!isset($_POST['InventoryProducts'])) {
        echo CJSON::encode(['status' => 'error', 'message' => ['Invalid Request']]);
        Yii::app()->end();
    }

    $id = (int) $_POST['InventoryProducts']['id'];

    if ($id > 0) {
        $model = InventoryProducts::model()->findByPk($id);
        if ($model === null) {
            echo CJSON::encode(['status' => 'error', 'message' => ['Record not found']]);
            Yii::app()->end();
        }
        $model->updated_date_time = date('Y-m-d H:i:s');
    } else {
        $model = new InventoryProducts();
        $model->created_date_time = date('Y-m-d H:i:s');
        $model->isActive = 'Y';
    }

    $model->attributes = $_POST['InventoryProducts'];

    $image = CUploadedFile::getInstance($model, 'image');
    if ($image) {
        $fileName = time() . '_' . $image->name;
        $image->saveAs(Yii::getPathOfAlias('webroot.uploads') . '/' . $fileName);
        $model->image = $fileName;
    }

    if (!$model->save()) {

        $errors = $model->getErrors();
        $errorMessages = [];

        foreach ($errors as $fieldErrors) {
            $errorMessages = array_merge($errorMessages, $fieldErrors);
        }

        echo CJSON::encode([
            'status' => 'error',
            'message' => $errorMessages
        ]);
        Yii::app()->end();
    }

    echo CJSON::encode(['status' => 'success']);
    Yii::app()->end();
}

  public function actionDisable()
{
    header('Content-Type: application/json');

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

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

    if($model){
        $model->isActive = ($status == 'Y') ? 'N' : 'Y';
        $model->updated_date_time = date('Y-m-d H:i:s');
        $model->save(false);

        echo CJSON::encode(['status'=>'success']);
    } else {
        echo CJSON::encode(['status'=>'fail']);
    }

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