<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;

class Product extends Model
{
    protected $fillable = [
        'slug','name','category','weight','price','old_price',
        'description','features','image','in_stock','stock_qty','sort_order'
    ];

    protected $casts = [
        'features'  => 'array',
        'in_stock'  => 'boolean',
        'price'     => 'decimal:2',
        'old_price' => 'decimal:2',
    ];

    public function getDiscountPercentAttribute(): int {
        if (!$this->old_price || $this->old_price <= $this->price) return 0;
        return (int) round((($this->old_price - $this->price) / $this->old_price) * 100);
    }

    public function getImageUrlAttribute(): string {
        return $this->image ? asset('images/' . $this->image) : asset('images/Pack.png');
    }

    public function cartItems() { return $this->hasMany(CartItem::class); }
    public function orderItems() { return $this->hasMany(OrderItem::class); }
    public function images() { return $this->hasMany(ProductImage::class)->orderBy('sort_order'); }
    public function primaryImage(): ?ProductImage { return $this->images->firstWhere('is_primary', true) ?? $this->images->first(); }
}
