<?php

namespace App\Models\Tenant;

use App\Models\Concerns\BelongsToTenant;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class PurchaseItem extends Model
{
    use BelongsToTenant;

    protected $fillable = [
        'company_id', 'purchase_id', 'part_id',
        'name', 'article', 'qty', 'qty_received', 'unit', 'buy_price', 'total', 'received',
    ];

    protected $casts = [
        'qty' => 'decimal:2',
        'qty_received' => 'decimal:2',
        'buy_price' => 'decimal:2',
        'total' => 'decimal:2',
        'received' => 'boolean',
    ];

    public function isFullyReceived(): bool
    {
        return (float) $this->qty_received + 0.001 >= (float) $this->qty;
    }

    public function outstanding(): float
    {
        return max(0.0, (float) $this->qty - (float) $this->qty_received);
    }

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

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

    protected static function booted(): void
    {
        static::saving(function (self $row) {
            $row->total = round((float) $row->qty * (float) $row->buy_price, 2);
        });
        static::saved(fn (self $row) => $row->purchase?->recalcTotal());
        static::deleted(fn (self $row) => $row->purchase?->recalcTotal());
    }
}
