<?php

namespace nota\models;
use Yii;

class Nota extends \yii\db\ActiveRecord
{
    public static function getDb() {
        return Yii::$app->get('dbnota'); 
    }
    
    public $voucher_amount;
    public $voucher_type;
    public $ppnUse;
    public $voucher_code;


    public $formItems = [];


    public static function tableName()
    {
        return 'nota';
    }

    public function rules()
    {
        return [
            [['tanggal', 'payment_method_id'], 'required'],
            [['tanggal'], 'safe'],
            [['total','grand_total'], 'number'],
            [['pelanggan', 'nomor'], 'string', 'max' => 150],
            [['ppn'], 'number'],
            [['uang_diterima', 'kembalian'], 'number'],

            // Tambahkan ini
            [['voucher_type', 'voucher_id', 'voucher_code', 'ppnUse'], 'safe'],

        ];
    }

    public function attributeLabels()
    {
        return [
            'payment_method_id' => 'Metode Pembayaran',
        ];
    }

    public function getItems()
    {
        return $this->hasMany(NotaItem::class, ['nota_id' => 'id']);
    }

    public function getPaymentMethod()
    {
        return $this->hasOne(PaymentMethod::class, ['id' => 'payment_method_id']);
    }

    // models/Nota.php
    
    public static function generateNomorDEbug()
{
    try {

        echo "<pre>";
        echo "MASUK FUNCTION\n";

        $userId = Yii::$app->user->identity->id ?? null;
        var_dump($userId);

        $user = Usermember::findOne($userId);
        var_dump($user);

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

        var_dump($cluster->format_id);
        var_dump($cluster->format);

        die("STOP DEBUG");

    } catch (\Throwable $e) {
        die($e->getMessage());
    }
}

    public static function generateNomor()
    {
        $userId = Yii::$app->user->identity->id ?? null;

        if (!$userId) {
            throw new \Exception('User belum login');
        }

        $user = Usermember::findOne($userId);

        if (!$user) {
            throw new \Exception('Usermember tidak ditemukan');
        }

        if (!$user->idCluster) {
            throw new \Exception('User tidak punya idCluster');
        }

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

        if (!$cluster) {
            throw new \Exception('Cluster tidak ditemukan. idCluster: ' . $user->idCluster);
        }

        if (!$cluster->format_id) {
            throw new \Exception('Format Nomor Nota belum di set di Pengaturan Transaksi');
        }

        if (!$cluster->format) {
            throw new \Exception('Relasi format tidak terbaca');
        }

        // Increment aman
        $affected = Cluster::updateAllCounters(
            ['nomor_terakhir' => 1],
            ['idCluster' => $cluster->idCluster]
        );

        if (!$affected) {
            throw new \Exception('updateAllCounters gagal');
        }

        $cluster->refresh();

        $nomorBaru = $cluster->nomor_terakhir;

        $replace = [
            '{PREFIX}' => $cluster->prefix,
            '{YEAR}'   => date('Y'),
            '{MONTH}'  => date('m'),
            '{DAY}'    => date('d'),
            '{NUMBER}' => str_pad(
                $nomorBaru,
                $cluster->panjang_nomor,
                '0',
                STR_PAD_LEFT
            ),
        ];

        return strtr($cluster->format->template, $replace);
    }



    public static function generateNomor2()
    {
        $user = Usermember::find()->where(['id'=>Yii::$app->user->identity->id])->one();
        $setting = Cluster::find()->select(['*'])->where(['eDeleted'=>'Tidak'])->where(['idCluster'=>$user->idCluster])->one();


        $bulan = date('m');
        $tahun = date('Y');

        // Reset bulanan
        if ($setting->reset_tipe == 'bulanan') {

            $awalBulan  = date('Y-m-01');
            $akhirBulan = date('Y-m-t');

            $cek = self::find()
                ->where(['between', 'tanggal', $awalBulan, $akhirBulan])
                ->count();

            if ($cek == 0) {
                $setting->nomor_terakhir = 0;
            }
        }

        $nomorBaru = $setting->nomor_terakhir + 1;
        $setting->nomor_terakhir = $nomorBaru;
        $setting->save(false);

        $nomorFormat = str_pad($nomorBaru, $setting->panjang_nomor, '0', STR_PAD_LEFT);

        return $setting->prefix .'/'.$setting->iId. '/' . $tahun . '/' . $bulan . '/' . $nomorFormat;
    }


}
