<?php

namespace App\Models;

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

class Product extends Model
{
    use HasFactory;

    protected $fillable = [
        'name',
        'slug',
        'category_id',
        'description',
        'price',
        'stock',
        'image',
    ];

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

    // Gunakan Slug sebagai pencarian otomatis di URL (opsional)
    public function getRouteKeyName()
    {
        return 'id'; // Gunakan 'slug' jika ingin URL menggunakan nama produk
    }

    public function stockLogs()
    {
        return $this->hasMany(StockLog::class);
    }

    // Tambahkan 2 method ini di dalam class Product

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

public function averageRating(): float
{
    return round($this->reviews()->avg('rating') ?? 0, 1);
}
}