<?php
namespace nota\controllers;

use Yii;
use nota\models\Barang;
use yii\web\Controller;
use yii\web\Response;
use yii\web\NotFoundHttpException;
use yii\helpers\Url;

class BarangController extends Controller
{
    public function actionIndex()
    {
        return $this->render('index');
    }

    public function actionList()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        $rows = Barang::find()->where(['idCluster'=>Yii::$app->user->identity->idCluster])->andWhere(['eDeleted'=>'Tidak'])->orderBy(['id' => SORT_DESC])->all();
        $data = [];

        foreach($rows as $r){
            $data[] = [
                'id' => $r->id,
                'kode' => $r->kode,
                'nama' => $r->nama,
                'harga' => $r->harga,
                'stok' => $r->stok,
                'status' => $r->status,
                'action' => '
                    <a href="'.Url::to(['barang/form','id'=>$r->id]).'"
                       class="btn btn-primary btn-sm"
                       data-toggle="modal"
                       data-target="#modal-barang">Edit</a>
                    <button class="btn btn-danger btn-sm btn-delete-barang" data-id="'.$r->id.'">
                        Hapus
                    </button>
                '
            ];
        }

        return ['data' => $data];
    }

    public function actionForm($id = null)
    {
        $model = $id ? Barang::findOne($id) : new Barang();

        if(!$model){
            throw new \yii\web\NotFoundHttpException('Data tidak ditemukan');
        }

        if(Yii::$app->request->isPost){
            Yii::$app->response->format = Response::FORMAT_JSON;
            $model->idCluster = Yii::$app->user->identity->idCluster;
            if($model->load(Yii::$app->request->post()) && $model->save()){
                return ['success'=>true, 'message'=>'Barang berhasil disimpan'];
            } else {
                return ['success'=>false,'message'=>implode('<br>',$model->getFirstErrors())];
            }
        }

        return $this->renderPartial('_form', [
            'model' => $model
        ]);
    }

    public function actionDelete()
    {
        Yii::$app->response->format = Response::FORMAT_JSON;

        $id = Yii::$app->request->post('id');
        $model = Barang::findOne($id);

        if(!$model){
            return ['success'=>false,'message'=>'Data tidak ditemukan'];
        }

        if($model->delete()){
            return ['success'=>true,'message'=>'Barang berhasil dihapus'];
        } else {
            return ['success'=>false,'message'=>'Gagal menghapus data'];
        }
    }


    protected function findModel($id)
    {
        if (($model = Barang::findOne($id)) !== null) {
            return $model;
        }
        throw new NotFoundHttpException('Produk tidak ditemukan.');
    }
}
