<?php

namespace Kylin\Catering\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Kylin\Catering\Enums\ExpiryAlertLevel;

/**
 * 库存
 */
class Stock extends Model
{
    protected $table = 'catering_stocks';
    protected $fillable = [
        'ingredient_name',
        'category',
        'unit',
        'current_stock',
        'min_stock',
        'unit_price',
        'supplier_id',
        'expiry_date',
        'batch_number',
    ];

    protected $casts = [
        'current_stock' => 'decimal:2',
        'min_stock' => 'decimal:2',
        'unit_price' => 'decimal:2',
        'supplier_id' => 'integer',
        'expiry_date' => 'date',
    ];

    public function supplier(): BelongsTo
    {
        return $this->belongsTo(Supplier::class);
    }

    public function logs(): HasMany
    {
        return $this->hasMany(StockLog::class);
    }

    public function isLowStock(): bool
    {
        return $this->current_stock <= $this->min_stock;
    }

    public function getExpiryAlertLevel(): ?ExpiryAlertLevel
    {
        if (!$this->expiry_date) {
            return null;
        }

        $days = now()->diffInDays($this->expiry_date, false);

        if ($days < 0) {
            return ExpiryAlertLevel::Urgent;
        }
        if ($days <= 3) {
            return ExpiryAlertLevel::Urgent;
        }
        if ($days <= 7) {
            return ExpiryAlertLevel::Warning;
        }
        if ($days <= 15) {
            return ExpiryAlertLevel::Notice;
        }

        return null;
    }
}
