<?php
// app/Models/Product.php

namespace App\Models;

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

class Product extends Model
{
    use HasFactory;

    protected $table = 'product';
    protected $primaryKey = 'produk_id';

    protected $fillable = [
        'kategori_id',
        'nama_produk',
        'harga',
        'stok',
        'tanggal_kadaluarsa',
        'foto',
    ];

    // Relasi ke kategori (setiap produk punya 1 kategori)
    public function kategori()
    {
        return $this->belongsTo(Kategori::class, 'kategori_id', 'kategori_id');
    }
    
    public function detailPenjualan()
    {
        return $this->hasMany(DetailPenjualan::class, 'produk_id', 'produk_id');
    }
    
    // Tambahkan relasi ke reviews
    public function reviews()
    {
        return $this->hasMany(Review::class, 'produk_id', 'produk_id');
    }
    
    // Hitung rata-rata rating
    public function getAverageRatingAttribute()
    {
        return $this->reviews()->avg('rating') ?? 0;
    }
    
    // Hitung jumlah review
    public function getReviewsCountAttribute()
    {
        return $this->reviews()->count();
    }
    
    // Mendapatkan distribusi rating
    public function getRatingDistributionAttribute()
    {
        $distribution = [];
        for ($i = 5; $i >= 1; $i--) {
            $distribution[$i] = $this->reviews()->where('rating', $i)->count();
        }
        return $distribution;
    }

    public function images()
{
    return $this->hasMany(ProductImage::class, 'produk_id', 'produk_id');
}

public function getPrimaryFotoAttribute()
{
    $primary = $this->images()->where('is_primary', true)->first();
    if ($primary) return $primary->foto;
    
    $first = $this->images()->first();
    if ($first) return $first->foto;
    
    return $this->foto; // fallback ke field foto lama
}

public function getAllImagesAttribute()
{
    return $this->images->pluck('foto')->toArray();
}

/**
 * Check if the product is expired.
 */
public function getIsExpiredAttribute()
{
    if (!$this->tanggal_kadaluarsa) {
        return false;
    }

    return \Carbon\Carbon::parse($this->tanggal_kadaluarsa)->isPast();
}
}
