<?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, SoftDeletes;

    protected $fillable = [
        'name',
        'slug',
        'sku',
        'description',
        'short_description',
        'weight',
        'size',
        'color',
        'price',
        'sale_price',
        'sale_price_start_date',
        'sale_price_end_date',
        'stock_quantity',
        'low_stock_threshold',
        'stock_status',
        'category_id',
        'subcategory_id',
        'brand_id',
        'is_featured',
        'is_active',
        'tags',
        'discount_percentage',
    ];

    protected $casts = [
        'price' => 'decimal:2',
        'sale_price' => 'decimal:2',
        'is_featured' => 'boolean',
        'is_active' => 'boolean',
        'tags' => 'array'  // Add this line
    ];

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

    public function brand()
    {
        return $this->belongsTo(Brand::class);
    }


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

    public function scopeActive($query)
    {
        return $query->where('is_active', true);
    }

    public function getDiscountPercentageAttribute()
    {
        if ($this->sale_price && $this->price > $this->sale_price) {
            return round((($this->price - $this->sale_price) / $this->price) * 100);
        }
        return 0;
    }

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


    public function specifications()
    {
        return $this->hasMany(ProductSpecification::class);
    }

    public function subcategories()
{
    return $this->belongsTo(Subcategory::class, 'subcategory_id');
}

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

public function getRouteKeyName()
{
    return 'slug';
}
}