<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable = [
        'category_id',
        'title',
        'slug',
        'thumbnail_id',
        'price',
        'discount_price',
        'short_description',
        'long_description',
        'how_to_use',
        'stock_quantity',
        'sold_count',
        'status'
    ];

    protected $appends = ['average_rating', 'reviews_count'];

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

    public function getReviewsCountAttribute()
    {
        return $this->reviews()->count();
    }

    protected static function boot()
    {
        parent::boot();
        static::creating(function ($product) {
            if (empty($product->slug)) {
                $product->slug = \Illuminate\Support\Str::slug($product->title);
            }
        });
    }

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

    public function thumbnail()
    {
        return $this->belongsTo(Image::class, 'thumbnail_id');
    }

    public function images()
    {
        return $this->belongsToMany(Image::class, 'product_images');
    }

    public function tags()
    {
        return $this->belongsToMany(Tag::class, 'product_tags');
    }

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