<?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 BomItem extends Model
{
    use LogsActivity;

    protected $table = 'bom_items';

    protected $fillable = [
        'bom_id',
        'component_item_id',
        'qty_per',
        'scrap_pct',
    ];

    protected $casts = [
        'qty_per' => 'decimal:6',
        'scrap_pct' => 'decimal:2',
    ];

    // Relationships
    public function bom(): BelongsTo
    {
        return $this->belongsTo(BOM::class, 'bom_id');
    }

    public function component(): BelongsTo
    {
        return $this->belongsTo(Item::class, 'component_item_id');
    }

    // Scopes
    public function scopeForBom($query, $bomId)
    {
        return $query->where('bom_id', $bomId);
    }

    public function scopeForComponent($query, $componentId)
    {
        return $query->where('component_item_id', $componentId);
    }

    // Helper methods
    public function getEffectiveQtyAttribute()
    {
        $scrapFactor = 1 + ($this->scrap_pct / 100);
        return $this->qty_per * $scrapFactor;
    }

    public function getFormattedQtyPerAttribute()
    {
        return number_format($this->qty_per, 6);
    }

    public function getFormattedScrapPctAttribute()
    {
        return number_format($this->scrap_pct, 2) . '%';
    }

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