<?php

namespace App\Models;

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

class SupplierInvoiceItem extends Model
{
    use HasFactory;

    protected $fillable = [
        'supplier_invoice_id',
        'item_type',
        'ingredient_id',
        'product_id',
        'description',
        'quantity',
        'bonus_quantity',
        'unit',
        'unit_price',
        'total_price',
        'batch_number',
        'expiry_date',
        'notes',
    ];

    protected $casts = [
        'quantity'        => 'decimal:3',
        'bonus_quantity'  => 'decimal:3',
        'unit_price'      => 'decimal:4',
        'total_price'     => 'decimal:2',
        'expiry_date'     => 'date',
    ];

    public const TYPE_INGREDIENT = 'ingredient';
    public const TYPE_PRODUCT    = 'product';
    public const TYPE_OTHER      = 'other';

    public function invoice(): BelongsTo
    {
        return $this->belongsTo(SupplierInvoice::class, 'supplier_invoice_id');
    }

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

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

    public function getTotalQuantityAttribute(): float
    {
        return (float) $this->quantity + (float) $this->bonus_quantity;
    }
}
