<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    use HasFactory;

    protected $table = 'tbl_product';
    protected $primaryKey = 'product_id';

    protected $fillable = [
        'category_id',
        'product_name',
        'description',
        'price',
        'stock',
        'weight', // dalam gram — hanya untuk keperluan internal/admin
        'image',
    ];

    protected $casts = [
        'image' => 'array',
    ];

    // ── Relationships ──────────────────────────────────────────────────────────

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

    public function stockHistories()
    {
        return $this->hasMany(StockHistory::class, 'product_id', 'product_id');
    }

    public function reviews()
    {
        return $this->hasMany(Review::class, 'product_id', 'product_id');
    }

    // ── Accessor: format berat (hanya dipakai di admin) ───────────────────────

    public function getWeightFormattedAttribute(): string
    {
        if (!$this->weight) return '-';
        return $this->weight >= 1000
            ? round($this->weight / 1000, 2) . ' kg'
            : $this->weight . ' gram';
    }
}