<?php

namespace App\Models\Tenant;

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

class Product extends Model
{
    use HasFactory;
    
    protected $connection = 'tenant'; 
    protected $guarded = [];
    protected $fillable = [
        'name', 'description', 'category_id', 'brand_id', 'unit_id', 'sku', 'barcode', 'price', 'cost',
        'stock_quantity', 'min_stock_alert', 'has_variants', 'image', 'status', 'manufacture_date', 'expiry_date'
    ];
    protected $casts = [
        'has_variants' => 'boolean',
        'manufacture_date' => 'date',
        'expiry_date' => 'date',
    ];

    public function getImageUrlAttribute()
    {
        return $this->image 
            ? asset('storage/' . $this->image) 
            : asset('assets/images/placeholder-product.png'); // Ensure you have a placeholder
    }

    public function variants()
    {
        return $this->hasMany(ProductVariant::class);
    }
    
    public function category() { return $this->belongsTo(Category::class); }
    public function brand() { return $this->belongsTo(Brand::class); }
    public function unit() { return $this->belongsTo(Unit::class); } // Base Unit (Global)

    public function productUnits()
    {
        return $this->hasMany(ProductUnit::class);
    }

    /**
     * Check if the product has expired.
     *
     * @return bool
     */
    public function isExpired(): bool
    {
        return $this->expiry_date && $this->expiry_date->isPast();
    }

    /**
     * Check if the product is expiring within a given number of days.
     *
     * @param int $days
     * @return bool
     */
    public function expiresSoon(int $days = 7): bool
    {
        if (!$this->expiry_date) {
            return false;
        }

        $today = now()->startOfDay();
        $expiryDate = $this->expiry_date->startOfDay();

        return $expiryDate->isFuture() && $expiryDate->diffInDays($today) <= $days;
    }
}
