<?php

namespace App\Models;

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

class Product extends Model
{
    use HasFactory;

    protected $fillable = [
        'category_id',
        'name',
        'slug',
        'tag',
        'price',
        'compare_at',
        'rating',
        'reviews_count',
        'badge',
        'image',
        'image_alt',
        'gallery',
        'sizes',
        'description',
        'meta_title',
        'meta_description',
        'meta_keywords',
        'og_title',
        'og_description',
        'stock',
        'is_featured',
        'is_active',
    ];

    protected $casts = [
        'sizes' => 'array',
        'gallery' => 'array',
        'price' => 'float',
        'compare_at' => 'float',
        'rating' => 'float',
        'is_featured' => 'boolean',
        'is_active' => 'boolean',
    ];

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

    public function variants()
    {
        return $this->hasMany(ProductVariant::class)->orderBy('is_default', 'desc')->orderBy('price', 'asc');
    }

    public function defaultVariant()
    {
        return $this->hasOne(ProductVariant::class)->where('is_default', true)->withDefault(function () {
            return $this->variants->first();
        });
    }

    public function orderItems()
    {
        return $this->hasMany(OrderItem::class);
    }
}
