<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable = [
        'category_id',
        'name',
        'slug',
        'description',
        'base_price',
        'weight',
        'length',
        'width',
        'height',
        'material',
        'status'
    ];

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

    // relasi ke gambar
    public function images()
    {
        // Ini artinya: Ambil ProductImage melalui ProductVariant
        return $this->hasManyThrough(ProductImage::class, ProductVariant::class);
    }

    public function variants()
    {
        return $this->hasMany(ProductVariant::class);
    }

    public function reviews() 
    {
        // Kita tambahkan with('user') agar tidak berat saat loading nama user
        return $this->hasMany(Review::class)->latest();
    }

    // Tambahan: Helper untuk menghitung rating di Blade lebih mudah
    public function getAverageRatingAttribute() 
    {
        return round($this->reviews()->avg('rating') ?? 0, 1);
    }

    public function wishlists() 
    {
        return $this->hasMany(Wishlist::class);
    }

    public function averageRating() 
    {
        return $this->reviews()->avg('rating');
    }

public function getImageUrlAttribute()
{
    // Cek apakah ada varian dan gambar varian
    $variant = $this->variants->first();
    if ($variant && $variant->images->count() > 0) {
        $path = $variant->images->first()->image_path;
    } else {
        // Jika tidak ada varian, ambil gambar produk langsung
        $productImage = $this->images->first();
        $path = $productImage ? $productImage->image_path : null;
    }

    if ($path) {
        // Bersihkan prefix 'public/' jika ada
        $cleanPath = str_replace('public/', '', $path);
        return asset('storage/' . $cleanPath);
    }

    return 'https://placehold.co/400x400?text=No+Photo';
}
}