<?php

namespace nota\controllers;

use Yii;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\helpers\ArrayHelper;
use yii\filters\AccessControl;
use yii\web\UploadedFile;
use yii\helpers\BaseInflector;
use yii\helpers\Html;
use yii\db\Expression;
use nota\models\Usermember;
use nota\models\Pembayaran;
use nota\models\Cluster;
use kartik\mpdf\Pdf;


/**
 * MateriController implements the CRUD actions for Sessionkelas model.
 */
class AdminController extends Controller
{
    /**
     * {@inheritdoc}
     */
    public function behaviors()
    {
        return [
            'access' => [
                'class' => AccessControl::className(),
                'rules' => [
                    [
                        'actions' => ['login', 'error'],
                        'allow' => true,
                    ],
                    [
                        'actions' => ['index','warga','wargadetail','detail','update','aktifkan','deleteaccount','blastwa','emailtes','delete','siswa','subcat','create','reportpembayaran','updatemetode','reportpembayaran-index','notifwa','notifwaold','notifemail','notifwabulan','status-lap','viewdet','reporttambahan','reportpengeluaranall','reportpengeluaran','updatepengeluaran','reportpembayaran-all','reportpembayaran-cetak','bantuinput','editprofile', 'detailkolomwarga','kolomwarga', 'laporan-bulanan','checkotp','dashboard','bayar','bayar2','bayaradmin','onproses','status','pengeluaran','updatetambahan','tambahan','deletetambahan','deletepengeluaran','notif','bayar-form','bayar-form-user','simpan-bayar','simpan-bayar-user','verif','verif-bayar','duplikat','detail-member','hapus-duplikat','hapus-data','log-hist','create-warga','cluster','invoice','create-inv','view-inv','invoice-pdf','konfirmasi-inv','invoice-all','verif-inv','faq','detail-faq','reportpembayaran-index-verif'], 
                        'allow' => true,
                        'roles' => ['@'],
                    ],
                    
                ],
            ],
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'logout' => ['post'],
                ],
            ],
        ];
    }

    public function actions()
    {
        return [
            'error' => [
                'class' => 'yii\web\ErrorAction',
            ],
            'captcha' => [
                'class' => 'yii\captcha\CaptchaAction',
                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
            ],
        ];
    }

    
    public function actionDashboard()
    {
        $user = Usermember::findOne(Yii::$app->user->id);

        $cluster = Cluster::find()
            ->where(['eDeleted' => 'Tidak', 'idCluster' => $user->idCluster])
            ->one();

        $pembayaran = Pembayaran::find()
            ->where(['idCluster' => $cluster->idCluster, 'eDeleted' => 'Tidak'])
            ->orderBy(['iId' => SORT_DESC])
            ->one();

        if ($pembayaran && $pembayaran->eStatus == 'PROSES') {
            return $this->redirect(['admin/invoice']);
        }
        if ($pembayaran && $pembayaran->dateFinish < date('Y-m-d H:i:s')) {
            return $this->redirect(['admin/create-inv']);
        }


    	$user = Yii::$app->user->identity;
        $role = $user->eType;

        $today = date('Y-m-d');
        $bulan = date('m');
        $tahun = date('Y');

        /* =============================
         * SUMMARY TODAY (Realtime)
         * ============================= */
        $totalOmset = \nota\models\Nota::find()
            ->where(['DATE(tanggal)' => $today])->andWhere(['idCluster'=> Yii::$app->user->identity->idCluster])
            ->sum('grand_total') ?? 0;

        $totalCash = \nota\models\Nota::find()
            ->where(['DATE(tanggal)' => $today])
            ->andWhere(['payment_method_id' => '1'])
            ->andWhere(['idCluster'=> Yii::$app->user->identity->idCluster])
            ->sum('grand_total') ?? 0;

        $NonCash = \nota\models\Nota::find()
            ->where(['DATE(tanggal)' => $today])
            ->andWhere('payment_method_id != "1"')
            ->andWhere(['idCluster'=> Yii::$app->user->identity->idCluster])
            ->sum('grand_total') ?? 0;

        $totalTransaksi = \nota\models\Nota::find()
            ->where(['DATE(tanggal)' => $today])->andWhere(['idCluster'=> Yii::$app->user->identity->idCluster])
            ->count();

        /* =============================
         * STOK ALERT
         * ============================= */
        $stokMinimum = \nota\models\Barang::find()
            ->where('stok <= stok_minimum')
            ->andWhere(['>', 'stok', 0])->andWhere(['idCluster'=> Yii::$app->user->identity->idCluster])
            ->orderBy(['stok' => SORT_ASC])
            ->limit(5)
            ->all();

        $stokHabis = \nota\models\Barang::find()
            ->where(['stok' => 0])->andWhere(['idCluster'=> Yii::$app->user->identity->idCluster])
            ->all();

         // $this->kirimNotifikasiStok($stokMinimum, $stokHabis);
        //  $today = date('Y-m-d');

    	// $alreadySent = Yii::$app->cache->get('stok_alert_'.$today);

    	// if (!$alreadySent) {
    	//     $this->kirimNotifikasiStok($stokMinimum, $stokHabis);
    	//     Yii::$app->cache->set('stok_alert_'.$today, true, 86400);
    	// }

        /* =============================
         * RANKING KASIR
         * ============================= */
        $ranking = \nota\models\KasirShift::find()
            ->alias('s')
            ->select([
                'u.vNama',
                'SUM(s.total_penjualan) as total_omset'
            ])
            ->leftJoin('member u', 'u.id = s.user_id')
            ->where(['MONTH(s.tanggal_buka)' => $bulan])
            ->andWhere(['YEAR(s.tanggal_buka)' => $tahun])
            ->andWhere(['s.status' => 'closed'])->andWhere(['u.idCluster'=> Yii::$app->user->identity->idCluster])
            ->groupBy('s.user_id')
            ->orderBy(['total_omset' => SORT_DESC])
            ->asArray()
            ->all();

        /* =============================
         * TOP PRODUK
         * ============================= */
        $topProduk = \nota\models\NotaItem::find()
            ->alias('ni')
            ->select([
                'b.nama',
                'SUM(ni.qty) as total_qty'
            ])
            ->joinWith(['barang b', 'nota n'])
            ->where(['MONTH(n.tanggal)' => $bulan])
            ->andWhere(['YEAR(n.tanggal)' => $tahun])->andWhere(['b.idCluster'=> Yii::$app->user->identity->idCluster])
            ->groupBy('ni.barang_id')
            ->orderBy(['total_qty' => SORT_DESC])
            ->limit(10)
            ->asArray()
            ->all();

        return $this->render('dashboard', compact(
        	'role',
            'totalOmset',
            'totalCash','NonCash',
            'totalTransaksi',
            'stokMinimum',
            'stokHabis',
            'ranking',
            'topProduk'
        ));
    }

	private function kirimNotifikasiStok($stokMinimum, $stokHabis)
{
    if (empty($stokMinimum) && empty($stokHabis)) {
        return;
    }

    $pesan = "LAPORAN STOK TOKO\n\n";

    if (!empty($stokHabis)) {
        $pesan .= "🚨 STOK HABIS:\n";
        foreach ($stokHabis as $b) {
            $pesan .= "- {$b->nama}\n";
        }
        $pesan .= "\n";
    }

    if (!empty($stokMinimum)) {
        $pesan .= "⚠ STOK HAMPIR HABIS:\n";
        foreach ($stokMinimum as $b) {
            $pesan .= "- {$b->nama} (Stok: {$b->stok})\n";
        }
    }

    Yii::$app->mailer->compose()
        ->setTo('anak.sarerea@email.com') // ganti email owner
        ->setFrom(['noreply@tokokamu.com' => 'Sistem Toko'])
        ->setSubject('⚠ Notifikasi Stok Hampir Habis')
        ->setTextBody($pesan)
        ->send();
}

	private function kirimWA($pesan)
{
    $token = "ISI_TOKEN_API_KAMU";

    $curl = curl_init();

    curl_setopt_array($curl, array(
      CURLOPT_URL => 'https://api.fonnte.com/send',
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_POST => true,
      CURLOPT_POSTFIELDS => [
          'target' => '628xxxxxxxxxx',
          'message' => $pesan,
      ],
      CURLOPT_HTTPHEADER => [
        "Authorization: $token"
      ],
    ));

    curl_exec($curl);
    curl_close($curl);
}
    
    public function actionInvoiceAll()
    {

        $dateNow    = date('Y-m-d');
        $bulan      = date("m",strtotime($dateNow));
        $tahun      = date("Y",strtotime($dateNow));
        $namabulan = ValidationHelper::bulan($bulan);
        $idcluster = Usermember::find()->where(['id'=>Yii::$app->user->id])->andWhere(['eDeleted'=>"Tidak"])->one();
        $loghist = Pembayaran::find()->select([
                          'm_pembayaran.*','member.vNama'
                      ])->leftJoin('member', 'member.idCluster = m_pembayaran.idCluster')->where(['m_pembayaran.eDeleted'=>'Tidak'])->andWhere(['YEAR(m_pembayaran.tCreated)' => $tahun])->orderBy(['m_pembayaran.iId' => SORT_DESC])->all();
        //var_dump($pengeluaran);die;
        return $this->render('invoice', [
            'loghist'=>$loghist,
        ]);
    }

    public function actionInvoice()
    {

        $dateNow    = date('Y-m-d');
        $bulan      = date("m",strtotime($dateNow));
        $tahun      = date("Y",strtotime($dateNow));
        $namabulan = ValidationHelper::bulan($bulan);
        $idcluster = Usermember::find()->where(['id'=>Yii::$app->user->id])->andWhere(['eDeleted'=>"Tidak"])->one();
        $loghist = Pembayaran::find()->select([
                          'm_pembayaran.*','member.vNama'
                      ])->leftJoin('member', 'member.idCluster = m_pembayaran.idCluster')->where(['m_pembayaran.idCluster'=>$idcluster->idCluster])->andWhere(['m_pembayaran.eDeleted'=>'Tidak'])->andWhere(['YEAR(m_pembayaran.tCreated)' => $tahun])->orderBy(['m_pembayaran.iId' => SORT_DESC])->all();
        //var_dump($pengeluaran);die;
        return $this->render('invoice', [
            'loghist'=>$loghist,
        ]);
    }

    public function actionCreateInv()
    {
        $model = new Pembayaran();
        $idcluster = Usermember::find()->where(['id'=>Yii::$app->user->id])->andWhere(['eDeleted'=>"Tidak"])->one();
        $cluster = Cluster::find()->select(['*'])->where(['eDeleted'=>'Tidak'])->where(['idCluster'=>$idcluster->idCluster])->one();
        $jmlrumah = Usermember::find()->where(['idCluster'=>$idcluster->idCluster])->andWhere(['eDeleted'=>"Tidak"])->count();

        // harga per bulan
        $hargaPerBulan = 65000;

        // default start sekarang
        $dateStart = date('Y-m-d H:i:s');

        // var_dump(BaseInflector::slug($cluster->vNama));die;
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {

            // input dari form (bulan)
            $jumlahBulan = (int)$model->jumlah_bulan;

            // hitung finish
            $dateFinish = date(
                'Y-m-d H:i:s',
                strtotime("+{$jumlahBulan} months", strtotime($dateStart))
            );

            // total bayar
            $totalBayar = $jumlahBulan * $hargaPerBulan;

            $last = Pembayaran::find()
                ->where(['like', 'vKode', 'INV-'.$cluster->iId.''. date('Y')])
                ->orderBy(['iId' => SORT_DESC])
                ->one();

            $no = $last ? ((int)substr($last->vKode, -2)) + 1 : 1;

            $model->vKode = 'INV-'.$cluster->iId.''. date('Y') . '' . str_pad($no, 2, '0', STR_PAD_LEFT);

            // assign ke model
            $model->dateStart  = $dateStart;
            $model->dateFinish = $dateFinish;
            $model->vNilai = $totalBayar;
            $model->jumlah_bulan = $jumlahBulan;
            $model->idCluster = $cluster->idCluster;
            $model->idMember = Yii::$app->user->id;

            $nama           = $cluster->vNama;
            $kodeInvoice    = $model->vKode;
            $bulan          = $jumlahBulan;
            $harga          = $hargaPerBulan;
            $total          = $bulan * $harga;

            $bank           = 'BSI - BANK SYARIAH INDONESIA';
            $rek            = '2788781710';
            $atas           = 'Husnul Aspiana';

            $linkInvoice = Yii::$app->urlManager->createAbsoluteUrl([
                'admin/view-inv',
                'id' => $kodeInvoice
            ]);

            Yii::$app->mailer2
                ->compose()
                ->setFrom(['noreply@myipl.my.id' => 'IPL'])
                ->setTo($cluster->vEmail)
                ->setSubject('[Order Pembayaran] '.$kodeInvoice)
                ->setHtmlBody('
                    <div style="max-width:650px;margin:auto;font-family:Arial,sans-serif;background:#ffffff;border:1px solid #ddd;border-radius:6px;">

            <!-- HEADER -->
            <div style="background:#2c3e50;color:#fff;padding:20px;text-align:center;">
            <img width="72" src="https://play-lh.googleusercontent.com/5hxSeQ2M30e52U4mxWci8I2Dhi6Chq9LnNP4o2x6FAPz_294iGZB2Hvd-5v08jK_6sW_=w240-h480-rw" />
                <h2 style="margin:0;">INSTRUKSI PEMBAYARAN</h2>
            </div>

            <!-- CONTENT -->
            <div style="padding:25px;font-size:14px;color:#333;">

                <p>Yth. <strong>'.$nama.'</strong>,</p>

                <p>
                    Terima kasih telah melakukan pemesanan layanan kami.<br>
                    Berikut detail invoice Anda:
                </p>

                <!-- BOX INVOICE -->
                <div style="background:#f8f9fa;padding:15px;border-radius:5px;margin:15px 0;">
                    <table width="100%" cellpadding="0" cellspacing="0">
                        <tr>
                            <td>Kode Invoice</td>
                            <td>: <strong>'.$kodeInvoice.'</strong></td>
                        </tr>
                        <tr>
                            <td>Paket</td>
                            <td>: Langganan '.$bulan.' Bulan</td>
                        </tr>
                        <tr>
                            <td>Total Pembayaran</td>
                            <td>: <strong>Rp '.number_format($total,0,",",".").'</strong></td>
                        </tr>
                    </table>
                </div>

                <!-- BANK -->
                <h4 style="margin-top:20px;">Informasi Transfer</h4>

                <div style="background:#f8f9fa;padding:15px;border-radius:5px;margin:10px 0;">
                    <table width="100%" cellpadding="0" cellspacing="0">
                        <tr>
                            <td>Bank</td>
                            <td>: '.$bank.'</td>
                        </tr>
                        <tr>
                            <td>No Rekening</td>
                            <td>: '.$rek.'</td>
                        </tr>
                        <tr>
                            <td>Atas Nama</td>
                            <td>: '.$atas.'</td>
                        </tr>
                    </table>
                </div>

                <p>
                    Setelah melakukan pembayaran, silakan klik tombol berikut:
                </p>

                <!-- BUTTON -->
                <a href="'.$linkInvoice.'" 
                   style="display:block;background:#27a2db;color:#ffffff !important;text-decoration:none;
                          padding:15px;text-align:center;border-radius:6px;font-weight:bold;
                          font-size:15px;">
                    ✅ Konfirmasi Pembayaran
                </a>

            </div>

            <!-- FOOTER -->
            <div style="text-align:center;font-size:12px;color:#888;padding:15px;">
                Email ini dikirim otomatis, mohon tidak membalas.<br>
                © '.date('Y').' | Iuran Pemeliharaan Lingkungan - IPL
            </div>

        </div>

            ')
        ->send();

            if ($model->save(false)) {
                \Yii::$app->dbipl->createCommand()->insert('log_hist', [
                    'idRef'       => $model->iId,
                    'idCluster'   => $idcluster->idCluster,
                    'eType'       => 'INV',
                    'vKeterangan' => 'NEW ORDER '.$cluster->vNama,
                    'iCreatedid'  => Yii::$app->user->id,
                    'iUpdatedid'  => Yii::$app->user->id,
                    'tCreated'    => date('Y-m-d H:i:s'),
                    'tUpdated'    => date('Y-m-d H:i:s'),
                ])->execute();
                Yii::$app->session->setFlash('success', 'Pembayaran berhasil dibuat.');
                return $this->redirect(['admin/invoice']);
            }

                

                // Yii::$app->getSession()->setFlash('success', 
                // "
                
                // <div class='bg-green alert alert-info' role='alert'>
                //   Data berhasil disimpan
                // </div>

                // <script type='text/javascript'>
                //     $(window).on('load',function(){
                //         $('#modalUbah').modal('show');
                //     });
                // </script>"
                //   );
                // return $this->redirect(['admin/warga']);
        
        } else {
               if (Yii::$app->request->isAjax) {
                    return $this->render('create-inv',[
                       'model' =>$model, 'jmlrumah'=>$jmlrumah, 'cluster'=>$cluster
                   ]);
               } else {
                    return $this->render('create-inv', [
                     'model' => $model, 'jmlrumah'=>$jmlrumah, 'cluster'=>$cluster
                     ]);
              }
         }
         
     }

    public function actionViewInv($id)
    {
        $idcluster = Usermember::find()->where(['id'=>Yii::$app->user->id])->andWhere(['eDeleted'=>"Tidak"])->one();
        $cluster = Cluster::find()->select(['*'])->where(['eDeleted'=>'Tidak'])->where(['idCluster'=>$idcluster->idCluster])->one();

        $model = Pembayaran::find()
            ->where(['vKode' => $id])->andWhere(['idCluster'=>$idcluster->idCluster])->andWhere(['eDeleted'=>'Tidak'])
            ->one();

            // var_dump($model);die;

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

        return $this->render('view-inv', [
            'model' => $model, 'cluster'=> $cluster
        ]);
    }

    public function actionVerifInv($id)
    {
        

        $model = Pembayaran::find()
            ->where(['vKode' => $id])->andWhere(['eDeleted'=>'Tidak'])
            ->one();

        $idcluster = Usermember::find()->where(['id'=>Yii::$app->user->id])->andWhere(['eDeleted'=>"Tidak"])->one();
        $cluster = Cluster::find()->select(['*'])->where(['eDeleted'=>'Tidak'])->where(['idCluster'=>$model->idCluster])->one();

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

        $dateStart = date('Y-m-d H:i:s');

        if ($model->load(Yii::$app->request->post())) {
            // hitung finish
            $dateFinish = date(
                'Y-m-d H:i:s',
                strtotime("+{$model->jumlah_bulan} months", strtotime($dateStart))
            );

            // assign ke model
            $model->dateStart  = $dateStart;
            $model->dateFinish = $dateFinish;

            $linkInvoice = Yii::$app->urlManager->createAbsoluteUrl([
                'admin/invoice',
            ]);

            Yii::$app->mailer2
                ->compose()
                ->setFrom(['noreply@myipl.my.id' => 'IPL'])
                ->setTo($cluster->vEmail) 
                ->setSubject('LAYANAN AKTIF '.$model->vKode)
                ->setHtmlBody('
                    <div style="max-width:650px;margin:auto;font-family:Arial,sans-serif;background:#ffffff;border:1px solid #ddd;border-radius:6px;">


<!-- HEADER -->
<div style="background:#2c3e50;color:#fff;padding:20px;text-align:center;">
<img width="72" src="https://play-lh.googleusercontent.com/5hxSeQ2M30e52U4mxWci8I2Dhi6Chq9LnNP4o2x6FAPz_294iGZB2Hvd-5v08jK_6sW_=w240-h480-rw" />
    <h2 style="margin:0;">LAYANAN SUDAH AKTIF</h2>
</div>

<!-- CONTENT -->
<div style="padding:25px;font-size:14px;color:#333;">

    <p>Yth. <strong>'.$model->vNama .'</strong>,</p>

    <p>
        Terima kasih atas pembayaran yang telah kami terima 🙏<br>
        Dengan ini kami informasikan bahwa <strong>layanan Anda sudah aktif</strong> dan siap digunakan.
    </p>

    <!-- BOX INFO -->
    <div style="background:#f8f9fa;padding:15px;border-radius:5px;margin:15px 0;">
        <table width="100%" cellpadding="0" cellspacing="0">
            <tr>
                <td>Kode Invoice</td>
                <td>: <strong>'.$model->vKode .'</strong></td>
            </tr>
            <tr>
                <td>Paket</td>
                <td>: Langganan '.$model->jumlah_bulan .' Bulan</td>
            </tr>
            <tr>
                <td>Tanggal Aktif</td>
                <td>: '.$model->dateStart .'</td>
            </tr>
            <tr>
                <td>Tanggal Berakhir</td>
                <td>: '.$model->dateFinish .'</td>
            </tr>
        </table>
    </div>

    <p>
        Silakan login ke sistem untuk mulai menggunakan layanan Anda.
    </p>

    <!-- BUTTON -->
    <a href="'.$linkInvoice.'" 
       style="display:block;background:#27a2db;color:#ffffff !important;text-decoration:none;
              padding:15px;text-align:center;border-radius:6px;font-weight:bold;
              font-size:15px;">
        🚀 Login ke Dashboard
    </a>

</div>

<!-- FOOTER -->
<div style="text-align:center;font-size:12px;color:#888;padding:15px;">
    Email ini dikirim otomatis, mohon tidak membalas.<br>
    © '.date('Y').' | Iuran Pemeliharaan Lingkungan - IPL
</div>


</div>


                    ')
                ->send();

            if ($model->save(false)) {
                \Yii::$app->dbipl->createCommand()->insert('log_hist', [
                    'idRef'       => $model->iId,
                    'idCluster'   => $idcluster->idCluster,
                    'eType'       => 'INV',
                    'vKeterangan' => 'SETUJU ORDER '.$cluster->vNama,
                    'iCreatedid'  => Yii::$app->user->id,
                    'iUpdatedid'  => Yii::$app->user->id,
                    'tCreated'    => date('Y-m-d H:i:s'),
                    'tUpdated'    => date('Y-m-d H:i:s'),
                ])->execute();
                Yii::$app->session->setFlash('success', 'Pembayaran berhasil dibuat.');
                return $this->redirect(['admin/invoice-all']);
            }

                

                // Yii::$app->getSession()->setFlash('success', 
                // "
                
                // <div class='bg-green alert alert-info' role='alert'>
                //   Data berhasil disimpan
                // </div>

                // <script type='text/javascript'>
                //     $(window).on('load',function(){
                //         $('#modalUbah').modal('show');
                //     });
                // </script>"
                //   );
                // return $this->redirect(['admin/warga']);
        
        } else {
               return $this->render('view-inv', [
                'model' => $model, 'cluster'=> $cluster
            ]);
        }

        
    }

    public function actionInvoicePdf($kode)
    {
        $idcluster = Usermember::find()->where(['id'=>Yii::$app->user->id])->andWhere(['eDeleted'=>"Tidak"])->one();
        $cluster = Cluster::find()->select(['*'])->where(['eDeleted'=>'Tidak'])->where(['idCluster'=>$idcluster->idCluster])->one();
        $model = Pembayaran::find()
            ->where(['vKode' => $kode])->andWhere(['eDeleted'=>'Tidak'])
            ->one();

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

        // render view ke html
        $content = $this->renderPartial('invoice-pdf', [
            'model' => $model, 'cluster'=> $cluster
        ]);

        $filename = 'Invoice-' . $model->vKode . '.pdf';

        $pdf = new Pdf([
            'mode' => Pdf::MODE_UTF8,
            'format' => Pdf::FORMAT_A4,
            'orientation' => Pdf::ORIENT_PORTRAIT,
            'destination' => Pdf::DEST_BROWSER,

            'filename' => $filename,

            'content' => $content,

            'cssFile' => '@vendor/kartik-v/yii2-mpdf/src/assets/kv-mpdf-bootstrap.min.css',

            'options' => [
                'title' => $filename,
            ],

            'methods' => [
        'SetTitle' => $filename,

        'SetFooter' => [
            '',
            'Copyright © '.date('Y'),
            'Hal. {PAGENO}'
        ],
    ],

        ]);

        ob_clean();


        return $pdf->render();
    }


    public function actionKonfirmasiInv($kode)
    {
        $model = Pembayaran::find()
            ->where(['vKode' => $kode])
            ->one();

        if (!$model) {
            throw new NotFoundHttpException('Invoice tidak ditemukan.');
        }

        // jika sudah lunas, redirect
        if ($model->eStatus == 'Lunas') {
            Yii::$app->session->setFlash('info', 'Invoice sudah dibayar.');
            return $this->redirect(['view', 'kode' => $kode]);
        }

        if ($model->load(Yii::$app->request->post())) {
            
            $model->eStatus = 'VERIFIKASI'; // menunggu verifikasi
            $model->tUpdated = date('Y-m-d H:i:s');

            $linkInvoice = Yii::$app->urlManager->createAbsoluteUrl([
                'admin/invoice-all',
            ]);

            Yii::$app->mailer2
                ->compose()
                ->setFrom(['noreply@myipl.my.id' => 'IPL'])
                ->setTo('anak.sarerea@gmail.com')
                ->setSubject('[Konfirmasi Pembayaran] '.$model->vKode)
                ->setHtmlBody('
                    <div style="max-width:650px;margin:auto;font-family:Arial,sans-serif;background:#ffffff;border:1px solid #ddd;border-radius:6px;">


<!-- HEADER -->
<div style="background:#2c3e50;color:#fff;padding:20px;text-align:center;">
<img width="72" src="https://play-lh.googleusercontent.com/5hxSeQ2M30e52U4mxWci8I2Dhi6Chq9LnNP4o2x6FAPz_294iGZB2Hvd-5v08jK_6sW_=w240-h480-rw" />
    <h2 style="margin:0;">LAYANAN SUDAH AKTIF</h2>
</div>

<!-- CONTENT -->
<div style="padding:25px;font-size:14px;color:#333;">

    <p>Yth. <strong>'.$model->dateStart .'</strong>,</p>

    <p>
        Terima kasih atas pembayaran yang telah kami terima 🙏<br>
        Dengan ini kami informasikan bahwa <strong>layanan Anda sudah aktif</strong> dan siap digunakan.
    </p>

    <!-- BOX INFO -->
    <div style="background:#f8f9fa;padding:15px;border-radius:5px;margin:15px 0;">
        <table width="100%" cellpadding="0" cellspacing="0">
            <tr>
                <td>Kode Invoice</td>
                <td>: <strong>'.$model->vKode .'</strong></td>
            </tr>
            <tr>
                <td>Paket</td>
                <td>: Langganan '.$model->jumlah_bulan .' Bulan</td>
            </tr>
            <tr>
                <td>Tanggal Aktif</td>
                <td>: '.$model->dateStart .'</td>
            </tr>
            <tr>
                <td>Tanggal Berakhir</td>
                <td>: '.$model->dateFinish .'</td>
            </tr>
        </table>
    </div>

    <p>
        Silakan login ke sistem untuk mulai menggunakan layanan Anda.
    </p>

    <!-- BUTTON -->
    <a href="'.$linkInvoice.'" 
       style="display:block;background:#27a2db;color:#ffffff !important;text-decoration:none;
              padding:15px;text-align:center;border-radius:6px;font-weight:bold;
              font-size:15px;">
        🚀 Login ke Dashboard
    </a>

</div>

<!-- FOOTER -->
<div style="text-align:center;font-size:12px;color:#888;padding:15px;">
    Email ini dikirim otomatis, mohon tidak membalas.<br>
    © '.date('Y').' | Iuran Pemeliharaan Lingkungan - IPL
</div>


</div>


                    ')
                ->send(); 

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

                Yii::$app->session->setFlash('success', 'Konfirmasi pembayaran berhasil dikirim.');

                return $this->redirect([
                    'admin/invoice',
                    // 'kode' => $model->vKode
                ]);
            }
        }

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


    public function actionFaq()
    {
        $pelanggan = UserUsermember::find()->where(['id'=>Yii::$app->user->id])->one();
        $data = Artikel::find()
                      ->select([
                          '*',
                      ])
                      //->leftJoin('m_saldo', 'member.id = m_saldo.idMember')
                      ->where(['eDeleted'=>'Tidak'])    
                      ->andWhere(['eType'=>'WEB'])
                      // ->andWhere(['idCluster'=>$pelanggan->idCluster])                     
                      ->limit(16)             
                      ->orderBy(['iId' => SORT_ASC])
                      ->all(); 
        return $this->render('faq',['data'=>$data]);
    }

    public function actionDetailFaq($slug){
        $data = Artikel::find()
                ->where(['eDeleted' => 'Tidak', 'vJudul'=>$slug])
                ->one();
        return $this->render('detail-faq',['data'=>$data]);
    }

}
