<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Spatie\Activitylog\Traits\LogsActivity;
use Spatie\Activitylog\LogOptions;

class ManufacturingBOMHistoryIngredient extends Model
{
    use LogsActivity;

    protected $table = 'manufacturing_bom_history_ingredients';

    protected $fillable = [
        'manufacturing_bom_history_id',
        'ingredient_account_id',
        'ingredient_name',
        'ingredient_sku',
        'quantity_required',
        'unit',
        'wastage_type',
        'wastage_value',
        'current_wap',
        'required_qty',
    ];

    protected $casts = [
        'manufacturing_bom_history_id' => 'integer',
        'ingredient_account_id' => 'integer',
        'quantity_required' => 'decimal:4',
        'wastage_value' => 'decimal:4',
        'current_wap' => 'decimal:4',
        'required_qty' => 'decimal:4',
    ];

    // Relationships
    public function manufacturingBomHistory(): BelongsTo
    {
        return $this->belongsTo(ManufacturingBOMHistory::class, 'manufacturing_bom_history_id');
    }

    public function ingredient(): BelongsTo
    {
        return $this->belongsTo(Account::class, 'ingredient_account_id');
    }

    // Helper methods
    public function getFormattedQuantityRequiredAttribute()
    {
        return number_format($this->quantity_required, 4);
    }

    public function getFormattedRequiredQtyAttribute()
    {
        return number_format($this->required_qty, 4);
    }

    public function getFormattedWapAttribute()
    {
        return number_format($this->current_wap, 4);
    }

    public function getFormattedWastageAttribute()
    {
        if ($this->wastage_type === 'percentage') {
            return number_format($this->wastage_value, 2) . '%';
        } else {
            return number_format($this->wastage_value, 4);
        }
    }

    public function getEffectiveQuantityAttribute()
    {
        if ($this->wastage_type === 'percentage') {
            $wastageFactor = 1 + ($this->wastage_value / 100);
            return $this->quantity_required * $wastageFactor;
        } else {
            return $this->quantity_required + $this->wastage_value;
        }
    }

    public function getActivitylogOptions(): LogOptions
    {
        return LogOptions::defaults()
            ->useLogName('manufacturing_bom_history_ingredient')
            ->logFillable()
            ->logOnlyDirty()
            ->dontSubmitEmptyLogs();
    }
}
