<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $table = 'products';

    protected $fillable = [
        'kategori', 'kode', 'nama', 'harga',
        'harga_p1', 'harga_p2', 'harga_p3',
        'min_p1', 'min_p2', 'min_p3',
        'tipe_harga', 'konversi_toples',
        'urutan', 'aktif'
    ];

    /**
     * Hitung harga berdasarkan qty efektif (sudah dikonversi ke toples)
     * qty_efektif = total toples reguler + (toples mini / 2)
     */
    public function hitungHarga(int $qtyEfektif): int
    {
        if ($this->tipe_harga === 'other') return $this->harga;

        // Cek dari paket tertinggi dulu
        if ($this->min_p3 > 0 && $qtyEfektif >= $this->min_p3) return $this->harga_p3;
        if ($this->min_p2 > 0 && $qtyEfektif >= $this->min_p2) return $this->harga_p2;
        if ($this->min_p1 > 0 && $qtyEfektif >= $this->min_p1) return $this->harga_p1;

        return $this->harga;
    }

    // Label kategori yang bagus untuk ditampilkan
    public static function labelKategori(): array
    {
        return [
            'TOPLES_REGULER' => '🏺 Toples Reguler',
            'POUCH'          => '👜 Pouch',
            'TOPLES_MINI'    => '🫙 Toples Mini',
            'KASSABA'        => '🧺 Kassaba',
            'DAILY'          => '📦 Daily',
            'BAG'            => '👝 Bag',
            'COFFEE'         => '☕ Coffee',
            'COOKIES'        => '🍪 Cookies',
            'IMLEK'          => '🧧 Imlek',
            'STARTERPACK'    => '🎁 Starterpack Plus',
            'ONLY_BOX'       => '📫 Only Box Imlek',
            'KUE_KERANJANG'  => '🧺 Kue Keranjang',
            'FU_QI'          => '🎀 Fu Qi Collection',
            'LEBARAN'        => '🌙 Lebaran',
            'BUNDLING'       => '📦 Bundling PKC',
            'ONLY_LEBARAN'   => '🌙 Only Lebaran',
            'WAN_SHI'        => '✨ Wan Shi',
        ];
    }

    public static function groupedByKategori()
    {
        return self::where('aktif', true)
            ->orderBy('kategori')
            ->orderBy('urutan')
            ->get()
            ->groupBy('kategori');
    }
}
