<?php

namespace nota\controllers;

use Yii;
use nota\models\Usermember;
use nota\models\Cluster;
use nota\models\Nota;
use nota\models\NotaItem;
use nota\models\Barang;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\helpers\Html;

class NotaAjaxController extends Controller
{
    public function behaviors()
    {
        return [
            'verbs'=>[
                'class'=>VerbFilter::class,
                'actions'=>[
                    'delete'=>['POST','GET'],
                ]
            ]
        ];
    }

    public function beforeAction($action)
    {
        $user = Yii::$app->user->identity;

        // Admin & Kasir bisa Create/Update/Delete
        if (in_array($action->id, ['create','update','delete'])) {
            if (!$user || !in_array($user->eType,['ADMIN','KASIR'])) {
                throw new \yii\web\ForbiddenHttpException('Anda tidak memiliki hak akses!');
            }
        }

        // Supervisor & Bendahara hanya lihat laporan
        if ($action->id === 'report') {
            if (!$user || !in_array($user->eType,['ADMIN','SUPERVISOR','BENDAHARA'])) {
                throw new \yii\web\ForbiddenHttpException('Anda tidak memiliki hak akses!');
            }
        }

        return parent::beforeAction($action);
    }

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

        $query = Nota::find()->orderBy(['id' => SORT_DESC]);

        $data = [];
        foreach ($query->all() as $nota) {

            $data[] = [
                'id'        => $nota->id,
                'nomor'     => $nota->nomor,
                'pelanggan' => $nota->pelanggan,
                'tanggal'   => $nota->tanggal,
                'total'     => $nota->total,
                'ppn'       => $nota->ppn,
                'action'    => 
                    Html::a('Edit', ['update','id'=>$nota->id], [
                        'class'=>'btn btn-primary btn-sm'
                    ]) . ' ' .
                    Html::a('Hapus', 'javascript:void(0)', [
                        'class'=>'btn btn-danger btn-sm btn-delete-nota',
                        'data-id'=>$nota->id
                    ]) . ' ' .
                    Html::a('Print', ['view','id'=>$nota->id], [
                        'class'=>'btn btn-success btn-sm',
                        'target'=>'_blank'
                    ])
            ];
        }

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

    public function actionSelectProduct()
    {
        $barangList = Barang::find()->all();
        return $this->renderAjax('select-product', [
            'barangList' => $barangList,
        ]);
    }


public function actionDelete($id)
{
    Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
    $nota = Nota::findOne($id);
    if($nota){
        $nota->delete();
        return ['success'=>true,'message'=>'Nota berhasil dihapus'];
    }
    return ['success'=>false,'message'=>'Nota tidak ditemukan'];
}

// actionCreate dan actionUpdate tetap menggunakan form biasa (server-side submit)


    /* =====================
        INDEX / DataTables
    ====================== */
    public function actionIndex()
    {
        if(Yii::$app->request->isAjax){
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            $data = Nota::find()->orderBy(['id'=>SORT_DESC])->all();
            $rows = [];
            foreach($data as $d){
                $rows[] = [
                    'id'=>$d->id,
                    'tanggal'=>$d->tanggal,
                    'customer_name'=>$d->customer_name,
                    'total'=>$d->total,
                    'action'=> Html::a('Edit',['update','id'=>$d->id],[
                                    'class'=>'btn btn-primary btn-sm',
                                    'data-toggle'=>'modal',
                                    'data-target'=>'#modal-nota'
                                ]) . ' ' .
                                Html::a('Hapus','javascript:void(0)',[
                                    'class'=>'btn btn-danger btn-sm btn-delete-nota',
                                    'data-id'=>$d->id
                                ])
                ];
            }
            return ['data'=>$rows];
        }

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

    /* =====================
        CREATE
    ====================== */
    public function actionCreate()
{
    $model = new Nota();
    $model->tanggal = date('Y-m-d');

    $barangList = Barang::find()->where(['>', 'stok', 0])->orderBy('nama')->all();

    if (Yii::$app->request->isPost) {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $post = Yii::$app->request->post();
        $itemsPost = $post['items'] ?? [];
        $ppnUse    = $post['ppnUse'] ?? 0;

        $model->attributes = $post;

        // Validasi minimal customer
        if (empty($model->customer_name)) {
            return ['success'=>false,'message'=>'Nama pelanggan wajib diisi!'];
        }

        if (empty($itemsPost)) {
            return ['success'=>false,'message'=>'Item belum diisi!'];
        }

        // Cek stok
        foreach ($itemsPost as $it) {
            $barang = Barang::findOne($it['barang_id']);
            if (!$barang || $it['qty'] > $barang->stok) {
                return ['success'=>false,'message'=>"Stok {$barang->nama} tidak cukup!"];
            }
        }

        $trx = Yii::$app->db->beginTransaction();
        try {
            $totalBeforePPN = 0;
            foreach ($itemsPost as $it) {
                $barang = Barang::findOne($it['barang_id']);
                $diskon = $it['diskon'] ?? 0;
                $subtotal = $it['qty'] * $barang->harga * (1 - $diskon/100);
                $totalBeforePPN += $subtotal;
            }

            $ppn = $ppnUse ? $totalBeforePPN * 0.11 : 0;
            $grandTotal = $totalBeforePPN + $ppn;

            $model->nomor = 'NT'.date('YmdHis');
            $model->total = $grandTotal;
            $model->ppn   = $ppn;
            $model->created_at = time();
            $model->save(false);

            foreach ($itemsPost as $it) {
                $barang = Barang::findOne($it['barang_id']);
                $detail = new NotaItem();
                $detail->nota_id  = $model->id;
                $detail->barang_id = $barang->id;
                $detail->qty      = $it['qty'];
                $detail->diskon   = $it['diskon'] ?? 0;
                $detail->harga    = $barang->harga;
                $detail->subtotal = $it['qty'] * $barang->harga * (1 - ($it['diskon'] ?? 0)/100);
                $detail->save(false);

                $barang->stok -= $it['qty'];
                $barang->save(false);
            }

            $trx->commit();
            return ['success'=>true,'message'=>'Nota berhasil disimpan!'];

        } catch (\Throwable $e) {
            $trx->rollBack();
            return ['success'=>false,'message'=>$e->getMessage()];
        }
    }

    // Render modal form
    return $this->renderPartial('_form-nota', [
        'model' => $model,
        'barangList' => $barangList
    ]);
}


    /* =====================
        UPDATE
    ====================== */
    public function actionUpdate($id)
    {
        $model = Nota::findOne($id);
        if(!$model) throw new NotFoundHttpException('Data tidak ditemukan');

        return $this->saveNota($model);
    }

    /* =====================
        DELETE
    ====================== */

    /* =====================
        PRIVATE SAVE AJAX
    ====================== */
    protected function saveNota($model)
    {
        if(Yii::$app->request->isPost){
            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
            if($model->load(Yii::$app->request->post()) && $model->save()){
                return ['success'=>true,'message'=>'Transaksi berhasil disimpan'];
            } else {
                return [
                    'success'=>false,
                    'message'=>implode('<br>',$model->getFirstErrors())
                ];
            }
        }

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