<?php

namespace App\Models\Warehouse;

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

class ProjectInventory extends Model
{
    use HasFactory;

    protected $table = 'project_inventory';

    protected $fillable = [
        'project_id',
        'item_id',
        'quantity_available',
        'allocated_quantity',
        'unit_price',
        'total_value'
    ];

    protected $casts = [
        'quantity_available' => 'decimal:2',
        'allocated_quantity' => 'decimal:2',
        'unit_price' => 'decimal:2',
        'total_value' => 'decimal:2'
    ];

    protected static function boot()
    {
        parent::boot();

        static::saving(function ($inventory) {
            // Auto-calculate total value
            $inventory->total_value = $inventory->quantity_available * $inventory->unit_price;
        });
    }

    /**
     * Relationships
     */
    public function project(): BelongsTo
    {
        return $this->belongsTo(Project::class);
    }

    public function item(): BelongsTo
    {
        return $this->belongsTo(Item::class);
    }

    /**
     * Calculated attributes
     */
    public function getAvailableForTransferAttribute()
    {
        return $this->quantity_available - $this->allocated_quantity;
    }

    /**
     * Quantity Management
     * @param float $quantity The quantity to add or subtract
     * @param string $operation 'add' or 'subtract'
     * @param float|null $unitPrice Unit price for the new quantity (used for weighted average when adding)
     */
    public function updateQuantity($quantity, $operation = 'add', $unitPrice = null)
    {
        if ($operation === 'add') {
            // Calculate weighted average price when adding new quantity
            if ($unitPrice !== null && $quantity > 0) {
                $oldQty = $this->quantity_available;
                $oldValue = $oldQty * $this->unit_price;
                $newValue = $quantity * $unitPrice;
                $newTotalQty = $oldQty + $quantity;

                // Calculate weighted average unit price
                $this->unit_price = $newTotalQty > 0 ? (($oldValue + $newValue) / $newTotalQty) : $unitPrice;
            }
            $this->quantity_available += $quantity;
        } else {
            $this->quantity_available = max(0, $this->quantity_available - $quantity);
        }

        $this->save();
    }

    public function allocateQuantity($quantity)
    {
        $this->allocated_quantity += $quantity;
        $this->save();
    }

    public function deallocateQuantity($quantity)
    {
        $this->allocated_quantity = max(0, $this->allocated_quantity - $quantity);
        $this->save();
    }
}