<?php

namespace App\Models;

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

class FatteningLotFeedIntake extends Model
{
    use HasFactory;

    protected $fillable = [
        'fattening_lot_id',
        'intake_date',
        'animals_count_snapshot',
        'total_cost',
        'notes',
        'user_id',
    ];

    protected $casts = [
        'intake_date' => 'date',
        'animals_count_snapshot' => 'integer',
        'total_cost' => 'decimal:2',
    ];

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

    public function items(): HasMany
    {
        return $this->hasMany(FatteningLotFeedIntakeItem::class);
    }

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

    public function costPerHead(): ?float
    {
        if ($this->animals_count_snapshot <= 0) {
            return null;
        }

        return round((float) $this->total_cost / $this->animals_count_snapshot, 2);
    }
}
