<?php
declare(strict_types=1);

namespace App\Modules\Accounting\Models;

use App\Core\Model;

class AccountBudget extends Model
{
    protected static string $table = 'account_budgets';
    protected static array $fillable = [
        'fiscal_year_id', 'account_id', 'period',
        'budgeted_amount', 'notes', 'created_by',
    ];
    protected static bool $timestamps = true;
    protected static bool $softDelete = false;

    public static function getForYear(int $fiscalYearId): array
    {
        return static::query()
            ->where('fiscal_year_id', '=', $fiscalYearId)
            ->orderBy('account_id', 'ASC')
            ->get();
    }

    public static function getForAccount(int $accountId, int $fiscalYearId): array
    {
        return static::query()
            ->where('account_id', '=', $accountId)
            ->where('fiscal_year_id', '=', $fiscalYearId)
            ->orderBy('period', 'ASC')
            ->get();
    }

    public static function upsert(int $fiscalYearId, int $accountId, string $period, float $amount, ?string $notes = null, ?int $createdBy = null): void
    {
        $existing = static::query()
            ->where('fiscal_year_id', '=', $fiscalYearId)
            ->where('account_id', '=', $accountId)
            ->where('period', '=', $period)
            ->first();

        if ($existing) {
            $instance = new static($existing);
            $instance->exists = true;
            $instance->update([
                'budgeted_amount' => $amount,
                'notes' => $notes,
            ]);
        } else {
            static::create([
                'fiscal_year_id'  => $fiscalYearId,
                'account_id'      => $accountId,
                'period'          => $period,
                'budgeted_amount' => $amount,
                'notes'           => $notes,
                'created_by'      => $createdBy,
            ]);
        }
    }
}
