<?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',
        'description',
        'price',
        'discount_price',  // ADD THIS
        'stock_quantity',  // ADD THIS
        'quantity',
        'image',
        'status',
        'is_on_sale',     // ADD THIS
        'sku',            // ADD THIS (optional)
    ];

    protected $casts = [
        'price' => 'decimal:2',
        'discount_price' => 'decimal:2',
        'is_on_sale' => 'boolean',
        'stock_quantity' => 'integer',
    ];

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

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

    /**
     * Calculate discount percentage
     */
    public function getDiscountPercentageAttribute()
    {
        if ($this->is_on_sale && $this->price > 0) {
            return round((($this->price - $this->discount_price) / $this->price) * 100);
        }
        return 0;
    }
}
