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

    protected $fillable = [
        'factory_invoice_id',
        'item_account_id',
        'warehouse_id',
        'ordered_quantity',
        'ordered_unit_price',
        'ordered_total',
        'picked_quantity',
        'delivered_quantity',
        'delivered_unit_price',
        'delivered_total',
        'length'
    ];

    protected $casts = [
        'ordered_quantity' => 'decimal:2',
        'ordered_unit_price' => 'decimal:2',
        'ordered_total' => 'decimal:2',
        'picked_quantity' => 'decimal:2',
        'delivered_quantity' => 'decimal:2',
        'delivered_unit_price' => 'decimal:2',
        'delivered_total' => 'decimal:2'
    ];

    // Relationships
    public function invoice(): BelongsTo
    {
        return $this->belongsTo(FactoryInvoice::class, 'factory_invoice_id');
    }

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

    public function warehouse(): BelongsTo
    {
        return $this->belongsTo(Warehouse::class, 'warehouse_id');
    }

    // Helper methods
    public function getEffectiveQuantityAttribute()
    {
        return $this->delivered_quantity ?? $this->ordered_quantity;
    }

    public function getEffectiveUnitPriceAttribute()
    {
        return $this->delivered_unit_price ?? $this->ordered_unit_price;
    }

    public function getEffectiveTotalAttribute()
    {
        return $this->delivered_total ?? $this->ordered_total;
    }

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