<?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 nota\models\Voucher;
use nota\models\SettingPdf;
use nota\models\KasirShift;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use Mpdf\Mpdf;
use yii\helpers\Html;
use yii\filters\AccessControl;

class NotaController extends Controller
{


    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::class,
                'only' => ['create','update','delete','index','report'],
                'rules' => [
                    [
                        'allow' => true,
                        'roles' => ['@'], // harus login
                    ],
                ],
                'denyCallback' => function () {
                    return $this->redirect(['/site/login']);
                },
            ],
        ];
    }

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

    if (!$user) {
        return parent::beforeAction($action);
    }

    if (in_array($action->id, ['create','update','delete','index'])) {
        if (!in_array($user->eType, ['ADMIN','KASIR'])) {
            Yii::$app->session->setFlash('error','Anda tidak memiliki akses!');
            return $this->redirect(['/site/index']);
        }
    }

    if ($action->id === 'report') {
        if (!in_array($user->eType, ['ADMIN','SUPERVISOR','BENDAHARA'])) {
            Yii::$app->session->setFlash('error','Anda tidak memiliki akses!');
            return $this->redirect(['/site/index']);
        }
    }

    return parent::beforeAction($action);
}


    // public function behaviors()
    // {
    //     return [
    //         'verbs' => [
    //             'class' => \yii\filters\VerbFilter::class,
    //             'actions' => [
    //                 'delete' => ['POST','GET'], // sekarang bisa GET juga
    //             ],
    //         ],
    //     ];
    // }  

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

    //     // Hanya admin dan kasir yang bisa input transaksi
    //     if (in_array($action->id, ['create', 'update', 'delete','index'])) {
    //         if (!$user || !in_array($user->eType, ['ADMIN','KASIR'])) {
    //             throw new \yii\web\ForbiddenHttpException('Anda tidak memiliki hak akses!');                

    //         }
    //     }

    //     // Supervisor dan bendahara hanya bisa 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 actionResetNomor($id)
{
    $model = $this->findModel($id);
    $model->nomor_terakhir = 0;
    $model->save(false);

    Yii::$app->session->setFlash('success', 'Nomor berhasil direset');
    return $this->redirect(['update', 'id' => $id]);
}


    /* =====================
        INDEX
    ====================== */
    public function actionIndex()
    {
        $data = Nota::find()->orderBy(['id'=>SORT_DESC])->all();

        return $this->render('index-ajax',[
            'data'=>$data
        ]);
    }

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

        $query = Nota::find()->where(['idCluster'=>Yii::$app->user->identity->idCluster])->andWhere(['eDeleted'=>'Tidak'])->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',
                    ])
            ];
        }

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

    public function actionSelectProduct()
    {
        $barangList = Barang::find()->where(['>', 'stok', 0])->andWhere(['idCluster'=>Yii::$app->user->identity->idCluster])->andWhere(['eDeleted'=>'Tidak'])
        ->orderBy('nama')
        ->all();;
        return $this->renderAjax('select-product', [
            'barangList' => $barangList,
        ]);
    }

    public function actionDelete()
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        $id = Yii::$app->request->post('id');
        $nota = Nota::findOne($id);

        if ($nota) {
            $trx = Yii::$app->dbnota->beginTransaction();
            try {

                // Soft delete semua item terkait
                NotaItem::updateAll(
                    ['eDeleted' => 'Ya'],
                    ['nota_id' => $nota->id]
                );

                // Soft delete nota
                $nota->eDeleted = 'Ya';
                $nota->save(false);

                $trx->commit();

                return [
                    'success' => true,
                    'message' => 'Nota beserta itemnya berhasil dihapus'
                ];

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

        return [
            'success' => false,
            'message' => 'Nota tidak ditemukan'
        ];
    }


    /* =====================
        VIEW
    ====================== */
    public function actionView($id)
    {
        $user = Usermember::find()->where(['id'=>Yii::$app->user->identity->id])->one();
        $cluster = Cluster::find()->select(['*'])->where(['eDeleted'=>'Tidak'])->where(['idCluster'=>$user->idCluster])->one();
        return $this->render('view',[
            'model'=>$this->findModel($id), 'cluster'=>$cluster
        ]);
    }

    /* =====================
        CREATE
    ====================== */
    public function actionCreate()
{   
    $shift = KasirShift::getActiveShift();

    if (!$shift) {
        return $this->redirect(['kasir-shift/buka']);
    }

    $model = new Nota();
    $model->tanggal = date('Y-m-d');

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

    if ($model->load(Yii::$app->request->post())) {

        if(empty($model->pelanggan)){
            $model->pelanggan = 'User';
        }

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

        // ===== Voucher =====
        $model->voucher_id   = Yii::$app->request->post('voucher_id');
        $model->voucher      = Yii::$app->request->post('voucher_value', 0);
        $model->voucher_type = Yii::$app->request->post('voucher_type');
        $model->voucher_code = Yii::$app->request->post('voucher_code');

        $model->uang_diterima = Yii::$app->request->post('uang_diterima');
        $model->kembalian = Yii::$app->request->post('kembalian');
        // var_dump($model->kembalian);die;

        $totalBeforeVoucher = 0;
        $formItems = [];

        foreach ($itemsPost as $it) {
            if (!empty($it['barang_id'])) {

                $barang = Barang::findOne($it['barang_id']);

                $tmp = new NotaItem();
                $tmp->barang_id = $barang->id;
                $tmp->qty       = $it['qty'] ?? 0;
                $tmp->diskon    = $it['diskon'] ?? 0;
                $tmp->harga     = $barang->harga;

                $tmp->subtotal  = $tmp->qty * $tmp->harga * (1 - $tmp->diskon/100);

                $totalBeforeVoucher += $tmp->subtotal;
                $formItems[] = $tmp;
            }
        }

        $model->formItems = $formItems;

        // ===== Hitung Voucher =====
        $discount = 0;

        if ($model->voucher > 0) {
            if ($model->voucher_type === 'percent') {
                $discount = $totalBeforeVoucher * ($model->voucher / 100);
            } else {
                $discount = $model->voucher;
            }
        }

        $totalAfterVoucher = $totalBeforeVoucher - $discount;
        if ($totalAfterVoucher < 0) $totalAfterVoucher = 0;

        // ===== Hitung PPN =====
        $model->ppn = $model->ppnUse ? round($totalAfterVoucher * 0.11) : 0;

        $model->total      = $totalBeforeVoucher;
        $model->grand_total = $totalAfterVoucher + $model->ppn;

        $model->voucher_code = $model->voucher_code;
        $model->voucher_id = $model->voucher_id;
        $model->voucher = $discount;

        $shift = KasirShift::getActiveShift();

        if (!$shift) {
            throw new \yii\web\ForbiddenHttpException('Kasir belum dibuka!');
        }

        $model->shift_id = $shift->id;

        $shift->total_penjualan += $model->grand_total;
        $shift->save(false);


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

            $errors = [];

            foreach ($model->errors as $field => $msgs) {
                foreach ($msgs as $msg) {
                    $errors[] = $msg;
                }
            }

            Yii::$app->session->setFlash('error', implode("\\n", $errors));

            return $this->render('create', [
                'model' => $model,
                'barangList' => $barangList
            ]);
        }



        // ================= VALIDASI =================
        if (!$model->validate()) {
            return $this->render('create', compact('model','barangList'));
        }

        if (empty($itemsPost)) {
            Yii::$app->session->setFlash('error','Item belum diisi!');
            return $this->render('create', compact('model','barangList'));
        }

        // ===== Simpan =====
        $trx = Yii::$app->dbnota->beginTransaction();

        try {

            // $model->nomor = 'NT'.date('YmdHis');
            $model->nomor = Nota::generateNomor();
            $model->created_at = time();
            $model->idCluster = Yii::$app->user->identity->idCluster;
            $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();

            Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

            return [
            'success' => true,
            'redirect' => \yii\helpers\Url::to(['view', 'id' => $model->id])
        ];
            // return $this->redirect(['view','id'=>$model->id]);

        } catch (\Throwable $e) {
            $trx->rollBack();
            Yii::$app->session->setFlash('error',$e->getMessage());
            return $this->render('create', compact('model','barangList'));
        }
    }

    return $this->render('create', compact('model','barangList'));
}


    public function actionCreateOLD()
    {
        $model = new Nota();
        $model->tanggal = date('Y-m-d');

        // Ambil daftar barang yang stoknya > 0
        $barangList = Barang::find()
            ->where(['>', 'stok', 0])
            ->orderBy('nama')
            ->all();

        if ($model->load(Yii::$app->request->post())) {

            $itemsPost = Yii::$app->request->post('items', []);
            $ppnUse    = Yii::$app->request->post('ppnUse', 0); // checkbox PPN

            $voucher = Yii::$app->request->post('voucherValue') ?? 0;
            $model->voucher = $voucher;

            $formItems = [];
            $total = 0;

            // Buat objek NotaItem sementara untuk render kembali jika ada error            
            foreach ($itemsPost as $it) {
                if (!empty($it['barang_id'])) {
                    $barang = Barang::findOne($it['barang_id']);
                    $tmp = new NotaItem();
                    $tmp->barang_id = $barang->id;
                    $tmp->qty       = $it['qty'] ?? 0;
                    $tmp->diskon    = $it['diskon'] ?? 0;
                    $tmp->harga     = $barang->harga; // Ambil dari DB
                    $tmp->subtotal  = $tmp->qty * $tmp->harga * (1 - $tmp->diskon/100);
                     $total += $tmp->subtotal;
                    $formItems[] = $tmp;

                }
            }
            $model->formItems = $formItems;
            // WAJIB supaya data tidak hilang saat error
            // Hitung PPN & Grand Total
            $model->total = $total;
            $model->ppn   = isset($post['ppnUse']) && $post['ppnUse'] ? round($total*0.11) : 0;
            $model->grand_total = $model->total + $model->ppn;

            // Validasi server-side
            if (!$model->validate()) {
                Yii::$app->session->setFlash('error','Pelanggan wajib diisi!');
                return $this->render('create', [
                    'model' => $model,
                    'barangList' => $barangList
                ]);
            }

            if (empty($itemsPost)) {
                Yii::$app->session->setFlash('error','Item belum diisi!');
                return $this->render('create', [
                    'model' => $model,
                    'barangList' => $barangList
                ]);
            }

            // Cek stok
            foreach ($itemsPost as $it) {
                $barang = Barang::findOne($it['barang_id']);
                if ($barang && $it['qty'] > $barang->stok) {
                    Yii::$app->session->setFlash('error',"Stok {$barang->nama} tidak cukup!");
                    return $this->render('create', [
                        'model' => $model,
                        'barangList' => $barangList
                    ]);
                }
            }

            // Simpan data ke DB
            $trx = Yii::$app->dbnota->beginTransaction();
            try {
                $totalBeforePPN = 0;

                // Hitung subtotal tiap item + diskon
                foreach ($itemsPost as $it) {
                    $barang = Barang::findOne($it['barang_id']);
                    $diskon = $it['diskon'] ?? 0;
                    $subtotal = $it['qty'] * $barang->harga * (1 - $diskon/100);
                    $totalBeforePPN += $subtotal;
                }

                // Hitung PPN 11% jika dicentang
                $ppn = $ppnUse ? $totalBeforePPN * 0.11 : 0;
                $grandTotal = $totalBeforePPN + $ppn;

                // Simpan Nota
                $model->nomor = 'NT' . date('YmdHis');
                $model->total = $grandTotal;
                $model->ppn   = $ppn; // HARUS ADA KOLM ppn DI TABEL nota
                $model->created_at = time();
                $model->save(false);

                // Simpan NotaItem
                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);

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

                $trx->commit();

                return $this->redirect(['view','id'=>$model->id]);

            } catch (\Throwable $e) {
                $trx->rollBack();
                Yii::$app->session->setFlash('error', $e->getMessage());
                return $this->render('create', [
                    'model' => $model,
                    'barangList' => $barangList
                ]);
            }
        }

        return $this->render('create', [
            'model' => $model,
            'barangList' => $barangList
        ]);
    }

    public function actionCheckVoucher($kode){
        $voucher = Voucher::find()->where(['kode'=>$kode,'active'=>1])->andWhere(['idCluster'=>Yii::$app->user->identity->idCluster])->one();

        if($voucher){
            return $this->asJson([
                'status'=>'ok',
                'id'=>$voucher->id,
                'type'=>$voucher->type,
                'value'=>$voucher->value,
            ]);
        }

        return $this->asJson([
            'status'=>'error',
            'message'=>'Kode voucher tidak valid atau sudah tidak aktif'
        ]);
    }


    
    /* =====================
        UPDATE
    ====================== */
    public function actionUpdate($id)
    {
        $model = Nota::findOne($id);

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

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

        // Kembalikan stok lama dulu
        foreach ($model->items as $oldItem) {
            $barang = Barang::findOne($oldItem->barang_id);
            if ($barang) {
                $barang->stok += $oldItem->qty;
                $barang->save(false);
            }
        }

        if ($model->load(Yii::$app->request->post())) {

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

            $model->voucher_id     = Yii::$app->request->post('voucher_id');
            $model->voucher      = Yii::$app->request->post('voucher_value', 0);
            $model->voucher_type   = Yii::$app->request->post('voucher_type');

            $totalBeforeVoucher = 0;

            foreach ($itemsPost as $it) {
                if (!empty($it['barang_id'])) {
                    $barang = Barang::findOne($it['barang_id']);
                    $diskon = $it['diskon'] ?? 0;

                    $subtotal = $it['qty'] * $barang->harga * (1 - $diskon/100);
                    $totalBeforeVoucher += $subtotal;
                }
            }

            // =========================
            // HITUNG VOUCHER
            // =========================
            $discount = 0;

            if ($model->voucher_id > 0) {
                if ($model->voucher_type === 'percent') {
                    $discount = $totalBeforeVoucher * ($model->voucher / 100);
                } else {
                    $discount = $model->voucher;
                }
            }
            // var_dump($discount);die;
            $totalAfterVoucher = $totalBeforeVoucher - $discount;
            if ($totalAfterVoucher < 0) $totalAfterVoucher = 0;

            // =========================
            // HITUNG PPN
            // =========================
            $ppn = $ppnUse ? round($totalAfterVoucher * 0.11) : 0;
            $grandTotal = $totalAfterVoucher + $ppn;

            // =========================
            // SET KE MODEL
            // =========================
            $model->total       = $totalAfterVoucher;
            $model->ppn         = $ppn;
            $model->grand_total = $grandTotal;

            $model->voucher = $discount;
            

            if (!$model->validate()) {
                return $this->render('update', [
                    'model' => $model,
                    'barangList' => $barangList
                ]);
            }

            $trx = Yii::$app->dbnota->beginTransaction();

            try {

                // Hapus item lama
                NotaItem::deleteAll(['nota_id' => $model->id]);

                $model->save(false);

                // Simpan item baru + kurangi stok
                foreach ($itemsPost as $it) {
                    if (!empty($it['barang_id'])) {

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

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

                $trx->commit();
                return $this->redirect(['view','id'=>$model->id]);

            } catch (\Throwable $e) {
                $trx->rollBack();
                Yii::$app->session->setFlash('error', $e->getMessage());

                return $this->render('update', [
                    'model' => $model,
                    'barangList' => $barangList
                ]);
            }
        }

        return $this->render('update', [
            'model' => $model,
            'barangList' => $barangList
        ]);
    }

        public function actionUpdateOLD($id)
    {
        $model = $this->findModel($id);
        $barangList = Barang::find()->where(['>','stok',0])->orderBy('nama')->all();

        if ($model->load(Yii::$app->request->post())) {
            $itemsPost = Yii::$app->request->post('items', []);
            $ppnUse = Yii::$app->request->post('ppnUse', 0);

            if (!$itemsPost) {
                Yii::$app->session->setFlash('error','Item belum diisi!');
                return $this->render('update', ['model'=>$model,'barangList'=>$barangList]);
            }

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

                $model->ppn = $ppnUse ? $total * 0.11 : 0;
                $model->total = $total + $model->ppn;
                $model->save(false);

                // hapus item lama
                NotaItem::deleteAll(['nota_id'=>$model->id]);

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

                $trx->commit();
                return $this->redirect(['view','id'=>$model->id]);

            } catch (\Throwable $e) {
                $trx->rollBack();
                Yii::$app->session->setFlash('error',$e->getMessage());
            }
        }

        return $this->render('update', [
            'model'=>$model,
            'barangList'=>$barangList
        ]);
    }


    /* =====================
        DELETE
    ====================== */	
	public function actionHapus($id)
    {
        $model = $this->findModel($id);
        // var_dump($model);die;
        foreach ($model->items as $it){
            $barang = Barang::findOne($it->barang_id);
            if ($barang){
                $barang->stok += $it->qty;
                $barang->save(false);
            }
        }

        NotaItem::deleteAll(['nota_id'=>$id]);
        $model->delete();

        return $this->redirect(['nota/index']);
    }
    /* =====================
        PRINT
    ====================== */
    public function actionPrint2($id)
    {
        $user = Usermember::find()->where(['id'=>Yii::$app->user->identity->id])->one();
        $cluster = Cluster::find()->select(['*'])->where(['eDeleted'=>'Tidak'])->where(['idCluster'=>$user->idCluster])->one();
        
        return $this->renderPartial('print',[
            'model'=>$this->findModel($id), 'cluster'=>$cluster
        ]);
    }

    public function actionPrint($id, $print_id = null)
{
    $model = $this->findModel($id);
    $user = Usermember::findOne(Yii::$app->user->identity->id);
    $cluster = Cluster::find()->where(['eDeleted'=>'Tidak', 'idCluster'=>$user->idCluster])->one();

    $setting = SettingPdf::findOne($cluster->print_id);
    // var_dump($setting);die;

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


    /* =====================
        PDF
    ====================== */
    public function actionPdf($id)
{
    $model = $this->findModel($id);
    $user = Usermember::findOne(Yii::$app->user->id);
    $cluster = Cluster::find()
        ->where(['eDeleted'=>'Tidak','idCluster'=>$user->idCluster])
        ->one();

    $setting = SettingPdf::findOne($cluster->pdf_id);

    $html = $this->renderPartial('print_auto_setting', [
        'model'   => $model,
        'cluster' => $cluster,
        'setting' => $setting,
        'isPdf'   => true, // penting
    ]);

    $mpdf = new \Mpdf\Mpdf([
        'mode'=>'utf-8',
        'format'=>$this->getPdfFormat($setting->paper_size, $model),
        'margin_left'=>$setting->margin_left ?? 5,
        'margin_right'=>$setting->margin_right ?? 5,
        'margin_top'=>$setting->margin_top ?? 5,
        'margin_bottom'=>$setting->margin_bottom ?? 5,
    ]);
    $mpdf->SetAutoPageBreak(false);

    $mpdf->WriteHTML($html);
    $mpdf->Output("nota-{$model->nomor}.pdf","I");
}

    private function getPdfFormat($paperSize, $model)
{
    switch(strtolower($paperSize)){

        case 'a4':
            return 'A4';

        case 'a5':
            return 'A5';

        case 'thermal58':

            $itemCount = count($model->items);
            $height = 120 + ($itemCount * 8); // rumus tinggi
            return [58, $height];

        case 'thermal80':

            $itemCount = count($model->items);
            $height = 120 + ($itemCount * 8);
            return [80, $height];

        default:
            return 'A4';
    }
}



    public function actionPrintUniversal($id, $pdf_id = null, $type = 'print')
{
    $model = $this->findModel($id);
    $user = \nota\models\Usermember::findOne(Yii::$app->user->id);
    $cluster = \nota\models\Cluster::find()
        ->where(['eDeleted' => 'Tidak', 'idCluster' => $user->idCluster])
        ->one();

    // Ambil setting PDF / print jika ada
    $setting = $pdf_id ? \nota\models\SettingPdf::findOne($pdf_id) : null;

    // Default paper size dan margin
    if ($setting) {
        $paperSize = $setting->paper_size;
        $orientation = strtoupper(substr($setting->orientation, 0, 1)); // P/L
        $margin_left = $setting->margin_left;
        $margin_right = $setting->margin_right;
        $margin_top = $setting->margin_top;
        $margin_bottom = $setting->margin_bottom;
    } else {
        $paperSize = ($type == 'print') ? [58, 200] : 'A4';
        $orientation = 'P';
        $margin_left = $margin_right = $margin_top = $margin_bottom = 3;
    }

    $html = $this->renderPartial('print_universal', [
        'model' => $model,
        'cluster' => $cluster,
        'setting' => $setting,
        'paperSize' => $paperSize,
        'orientation' => $orientation,
        'type' => $type,
    ]);

    if ($type == 'pdf') {
        $mpdf = new \Mpdf\Mpdf([
            'mode' => 'utf-8',
            'format' => $paperSize,
            'orientation' => $orientation,
            'margin_left' => $margin_left,
            'margin_right' => $margin_right,
            'margin_top' => $margin_top,
            'margin_bottom' => $margin_bottom,
        ]);

        if ($setting && $setting->header_text) {
            $mpdf->SetHTMLHeader($setting->header_text);
        }
        if ($setting && $setting->footer_text) {
            $mpdf->SetHTMLFooter($setting->footer_text);
        }

        $mpdf->WriteHTML($html);
        $mpdf->Output("nota-{$model->nomor}.pdf", "I");
    } else {
        // Thermal print → langsung render HTML
        return $html;
    }
}

    public function actionPrintPdf($id, $pdf_id=null, $type='pdf')
    {
        $model = Nota::findOne($id);
        $user = Usermember::findOne(Yii::$app->user->id);
        $cluster = Cluster::find()
            ->where(['eDeleted'=>'Tidak', 'idCluster'=>$user->idCluster])
            ->one();

        // Ambil setting PDF / print jika ada
        $setting = $pdf_id ? SettingPdf::findOne($pdf_id) : null;

        // Default paper size
        if($setting){
            $paperSize = $setting->paper_size;
            $orientation = strtoupper(substr($setting->orientation,0,1)); // P/L
            $margin_left = $setting->margin_left;
            $margin_right = $setting->margin_right;
            $margin_top = $setting->margin_top;
            $margin_bottom = $setting->margin_bottom;
        } else {
            $paperSize = ($type=='print') ? [58,200] : 'A4';
            $orientation = 'P';
            $margin_left=$margin_right=$margin_top=$margin_bottom=3;
        }

        $html = $this->renderPartial('print_universal', [
            'model'=>$model,
            'cluster'=>$cluster,
            'setting'=>$setting,
            'paperSize'=>$paperSize,
            'orientation'=>$orientation,
            'type'=>$type,
        ]);

        // Jika type pdf / thermal PDF
        if($type=='pdf' || $type=='print'){
            $mpdf = new Mpdf([
                'mode'=>'utf-8',
                'format'=>$paperSize,
                'orientation'=>$orientation,
                'margin_left'=>$margin_left,
                'margin_right'=>$margin_right,
                'margin_top'=>$margin_top,
                'margin_bottom'=>$margin_bottom,
            ]);

            if($setting && $setting->header_text){
                $mpdf->SetHTMLHeader($setting->header_text);
            }
            if($setting && $setting->footer_text){
                $mpdf->SetHTMLFooter($setting->footer_text);
            }

            $mpdf->WriteHTML($html);
            $mpdf->Output("nota-{$model->nomor}.pdf","I");
        } else {
            // fallback: tampilkan HTML biasa
            return $html;
        }
    }
    public function actionPdf2($id)
    {
        $model = $this->findModel($id);
        $user = Usermember::find()->where(['id'=>Yii::$app->user->identity->id])->one();
        $cluster = Cluster::find()->select(['*'])->where(['eDeleted'=>'Tidak'])->where(['idCluster'=>$user->idCluster])->one();
        
        $html = $this->renderPartial('print',[
            'model'=>$model, 'cluster'=>$cluster
        ]);

        $mpdf = new Mpdf([
            'mode'=>'utf-8',
            'format'=>[58,200],
            'margin_left'=>3,
            'margin_right'=>3,
            'margin_top'=>3,
            'margin_bottom'=>3,
        ]);

        $mpdf->WriteHTML($html);
        $mpdf->Output("nota-{$model->nomor}.pdf","I");
    }

    /* =====================
    CREATE
===================== */
public function actionCreateAjax()
{
    $model = new Nota();

    if (Yii::$app->request->isPost) {
        $model->attributes = Yii::$app->request->post('Nota');
        $model->created_by = Yii::$app->user->id;

        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        if($model->save()){
            return ['success'=>true,'message'=>'Transaksi berhasil ditambahkan'];
        } else {
            return ['success'=>false,'message'=>implode('<br>',$model->getFirstErrors())];
        }
    }

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

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

    if (Yii::$app->request->isPost) {
        $model->attributes = Yii::$app->request->post('Nota');
        Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
        if($model->save()){
            return ['success'=>true,'message'=>'Transaksi berhasil diperbarui'];
        } else {
            return ['success'=>false,'message'=>implode('<br>',$model->getFirstErrors())];
        }
    }

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

/* =====================
    DELETE
===================== */
public function actionDeleteAjax($id)
{
    $model = Nota::findOne($id);
    Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

    if($model && $model->delete()){
        return ['success'=>true,'message'=>'Transaksi berhasil dihapus'];
    }

    return ['success'=>false,'message'=>'Gagal menghapus transaksi'];
}


    /* =====================
        FIND MODEL
    ====================== */
    protected function findModel($id)
    {
        if (($model = Nota::find()
            ->with('items')
            ->where(['id'=>$id])
            ->one()) !== null) {
            return $model;
        }

        throw new NotFoundHttpException('Nota tidak ditemukan.');
    }
}
