<?php
namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\SoftDeletes;

class Product extends Model
{
    use HasFactory, SoftDeletes;

    protected $fillable = [
        'vendor_id', 'category_id', 'name', 'slug', 'short_description', 'description',
        'price', 'sale_price', 'cost_price', 'sku', 'stock_quantity', 'low_stock_threshold',
        'track_inventory', 'stock_status', 'thumbnail', 'images', 'weight', 'dimensions',
        'is_digital', 'digital_file', 'status', 'is_featured', 'attributes', 'tags',
        'average_rating', 'review_count', 'sales_count', 'view_count',
        'meta_title', 'meta_description',
    ];

    protected $casts = [
        'price' => 'decimal:2',
        'sale_price' => 'decimal:2',
        'cost_price' => 'decimal:2',
        'images' => 'array',
        'dimensions' => 'array',
        'attributes' => 'array',
        'tags' => 'array',
        'is_digital' => 'boolean',
        'is_featured' => 'boolean',
        'track_inventory' => 'boolean',
        'average_rating' => 'decimal:2',
    ];

    public function vendor(): BelongsTo { return $this->belongsTo(Vendor::class); }
    public function category(): BelongsTo { return $this->belongsTo(Category::class); }
    public function reviews(): HasMany { return $this->hasMany(Review::class); }
    public function orderItems(): HasMany { return $this->hasMany(OrderItem::class); }
    public function wishlists(): HasMany { return $this->hasMany(Wishlist::class); }

    public function getEffectivePriceAttribute(): float
    {
        return $this->sale_price ?? $this->price;
    }

    public function isInStock(): bool
    {
        if (!$this->track_inventory) return true;
        return $this->stock_quantity > 0;
    }

    public function updateRating(): void
    {
        $avg = $this->reviews()->where('status', 'approved')->avg('rating') ?? 0;
        $count = $this->reviews()->where('status', 'approved')->count();
        $this->update(['average_rating' => $avg, 'review_count' => $count]);
    }
}
