<?php

namespace App\Models;

use App\Traits\Auditable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\SoftDeletes;

class BudgetItem extends Model
{
    use HasFactory, Auditable, SoftDeletes;

    protected $fillable = [
        'budget_id',
        'category_id',
        'amount',
        'description',
    ];

    protected function casts(): array
    {
        return [
            'amount' => 'decimal:2',
        ];
    }

    /**
     * Boot method to update budget totals.
     */
    protected static function booted(): void
    {
        static::created(function (BudgetItem $item) {
            $item->budget->recalculateTotals();
        });

        static::updated(function (BudgetItem $item) {
            $item->budget->recalculateTotals();
        });

        static::deleted(function (BudgetItem $item) {
            $item->budget->recalculateTotals();
        });
    }

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

    public function category(): BelongsTo
    {
        return $this->belongsTo(TransactionCategory::class, 'category_id');
    }
}
