<?php

namespace App\Models;

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

class ItemRequestDetail extends Model
{
    use HasFactory;

    protected $table = 't_item_request_details';

    protected $fillable = [
        'item_request_id',
        'raw_material_id',
        'forecast_qty',
        'so_qty',
        'tsm_qty',
        'suggested_qty',
        'adjusted_qty',
        'final_qty',
        'alert_status',
        'notes',
        'created_at',
        'updated_at',
    ];

    public function itemRequest()
    {
        return $this->belongsTo(ItemRequest::class, 'item_request_id');
    }

    public function rawMaterial()
    {
        return $this->belongsTo(RawMaterial::class, 'raw_material_id');
    }

    // Auto calculate final_qty when saving
    protected static function boot()
    {
        parent::boot();

        static::saving(function ($model) {
            // final_qty = adjusted_qty if adjusted, otherwise suggested_qty
            $model->final_qty = $model->adjusted_qty > 0 ? $model->adjusted_qty : $model->suggested_qty;
            
            // Set alert status based on DOI or other business rules
            if ($model->so_qty > 0 && $model->forecast_qty > 0) {
                $doi = $model->so_qty / ($model->forecast_qty / 7); // Assuming 7-day forecast
                
                if ($doi < 1) {
                    $model->alert_status = 'Critical';
                } elseif ($doi < 2) {
                    $model->alert_status = 'Normal';
                } else {
                    $model->alert_status = 'Overstock';
                }
            }
        });
    }
}