<?php

namespace App\Models\Warehouse;

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

class OutgoingItem extends Model
{
    use HasFactory;

    protected $fillable = [
        'outgoing_transaction_id',
        'item_id',
        'division_id',
        'quantity_requested',
        'quantity_released',
        'quantity_balance',
        'quantity_transferred',
        'transfer_status',
        'unit_price',
        'total_price'
    ];

    protected $casts = [
        'quantity_requested' => 'decimal:2',
        'quantity_released' => 'decimal:2',
        'quantity_balance' => 'decimal:2',
        'quantity_transferred' => 'decimal:2',
        'transfer_status' => 'string',
        'unit_price' => 'decimal:2',
        'total_price' => 'decimal:2',
        'created_at' => 'datetime',
        'updated_at' => 'datetime'
    ];

    protected $appends = [
        'foc_available'
    ];

    /**
     * Boot the model
     */
    protected static function boot()
    {
        parent::boot();

        static::saving(function ($item) {
            // Auto-calculate balance
            $item->quantity_balance = $item->quantity_requested - $item->quantity_released;

            // Auto-calculate total price
            $item->total_price = $item->quantity_released * $item->unit_price;
        });
    }

    /**
     * Get the transaction that owns the item
     */
    public function transaction(): BelongsTo
    {
        return $this->belongsTo(OutgoingTransaction::class, 'outgoing_transaction_id');
    }

    /**
     * Get the item details
     */
    public function item(): BelongsTo
    {
        return $this->belongsTo(Item::class);
    }

    /**
     * Get the division details (ProjectDivision)
     */
    public function division(): BelongsTo
    {
        return $this->belongsTo(ProjectDivision::class, 'division_id');
    }

    /**
     * Get the fulfillments for this item
     */
    public function fulfillments()
    {
        return $this->hasMany(OutgoingFulfillment::class, 'item_id', 'item_id')
                    ->where('outgoing_transaction_id', $this->outgoing_transaction_id);
    }

    /**
     * Check if item is fully fulfilled
     */
    public function getIsFullyFulfilledAttribute()
    {
        return $this->quantity_balance <= 0;
    }

    /**
     * Check if item is partially fulfilled
     */
    public function getIsPartiallyFulfilledAttribute()
    {
        return $this->quantity_released > 0 && $this->quantity_balance > 0;
    }

    /**
     * Get fulfillment percentage
     */
    public function getFulfillmentPercentageAttribute()
    {
        if ($this->quantity_requested <= 0) {
            return 0;
        }

        return round(($this->quantity_released / $this->quantity_requested) * 100, 2);
    }

    /**
     * Get FOC available quantity for this item
     */
    public function getFocAvailableAttribute()
    {
        // If the attribute was manually set (in controller), return that value
        if (isset($this->attributes['foc_available'])) {
            return $this->attributes['foc_available'];
        }

        // Otherwise, fetch from FOC inventory
        return \App\Models\FocInventory::getTotalAvailableForItem($this->item_id);
    }

    /**
     * Release quantity from inventory
     */
    public function releaseQuantity($quantity)
    {
        $this->quantity_released += $quantity;
        $this->save();
    }
}