<?php

namespace App\Models;

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

class Product extends Model
{
    use HasFactory;
    use SoftDeletes;

    protected $dates = ['deleted_at'];

    // Mass assignable fields
    protected $fillable = [
        'name',
        'description',
        'category_id',
        'subcategory_id',
        'brand_id',
        'reference',
        'type',
        'price',
        'compare_price',
        'stock',
        'sku',
        'details',
        'images',
        'is_top_seller',
        'is_special_offer',
        'is_featured',
        'is_active',
    ];

    // Cast fields to appropriate types
    protected $casts = [
        'details' => 'array', // JSON to Array
        'images' => 'array',  // JSON to Array
        'is_top_seller' => 'boolean',
        'is_special_offer' => 'boolean',
        'is_featured' => 'boolean',
        'is_active' => 'boolean',
    ];

    /**
     * Relationships
     */

    // A product belongs to a category
    public function category()
    {
        return $this->belongsTo(Category::class);
    }

    // A product belongs to a subcategory
    public function subcategory()
    {
        return $this->belongsTo(SubCategory::class);
    }

    // A product belongs to a brand
    public function brand()
    {
        return $this->belongsTo(Brand::class);
    }

    // A product has many variants
    public function variants()
    {
        return $this->hasMany(ProductVariant::class);
    }

    public function reviews()
    {
        return $this->hasMany(Review::class)
                ->with('user');

    }


    public function orders()
    {
        return $this->belongsToMany(Order::class, 'order_product')
            ->withPivot('quantity', 'price')
            ->withTimestamps();
    }
}
