<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Product extends Model
{
    protected $guarded = [];

    protected $casts = [
        'buy_price' => 'float',
        'price' => 'float',
        'conversion_factor' => 'float',
        'conversion_3_qty' => 'float',
        'conversion_4_qty' => 'float',
        'is_active' => 'boolean',

        // Gunakan 'json' agar Filament lebih paksa dalam membaca strukturnya
        'price_matrix' => 'json',
        'variants_list' => 'json',
    ];

    protected static function booted()
    {
        static::creating(function ($product) {
            if (empty($product->sku)) {
                $product->sku = 'BRG' . date('ymd') . mt_rand(1000, 9999);
            }
        });
    }

    public function category(): BelongsTo
    {
        return $this->belongsTo(Category::class);
    }

    public function prices(): HasMany
    {
        return $this->hasMany(ProductPrice::class);
    }

    public function stocks(): HasMany
    {
        return $this->hasMany(ProductStock::class);
    }

    // --- RELASI PENTING UNTUK ALOKASI CABANG ---
    public function branches(): BelongsToMany
    {
        return $this->belongsToMany(Branch::class);
    }
    // -------------------------------------------

    public function stok_terbilang($qty)
    {
        $qty = (float) $qty;
        if ($qty <= 0.001 && $qty >= -0.001) return '0 ' . $this->unit;

        $hasil = [];
        $sisa = abs($qty);
        $prefix = $qty < 0 ? '- ' : '';

        $conv4 = (float) ($this->conversion_4_qty ?? 0);
        $conv3 = (float) ($this->conversion_3_qty ?? 0);
        $conv2 = (float) ($this->conversion_factor ?? 0);

        if ($conv4 > 1 && $sisa >= $conv4) {
            $jumlah = floor($sisa / $conv4);
            $hasil[] = number_format($jumlah, 0) . ' ' . ($this->unit_4_name ?? 'L4');
            $sisa = fmod($sisa, $conv4);
        }
        if ($conv3 > 1 && $sisa >= $conv3) {
            $jumlah = floor($sisa / $conv3);
            $hasil[] = number_format($jumlah, 0) . ' ' . ($this->unit_3_name ?? 'L3');
            $sisa = fmod($sisa, $conv3);
        }
        if ($conv2 > 1 && $sisa >= $conv2) {
            $jumlah = floor($sisa / $conv2);
            $hasil[] = number_format($jumlah, 0) . ' ' . ($this->buy_unit ?? 'L2');
            $sisa = fmod($sisa, $conv2);
        }
        if ($sisa > 0.001) { 
            $sisaStr = (floatval($sisa) == intval($sisa)) ? number_format($sisa, 0) : number_format($sisa, 2);
            $hasil[] = $sisaStr . ' ' . $this->unit;
        }
        return $prefix . (empty($hasil) ? '0 ' . $this->unit : implode(' ', $hasil));
    }
}