<?php
declare(strict_types=1);

namespace App\Modules\Accounting\Models;

use App\Core\Model;

class CostCenterBudget extends Model
{
    protected static string $table = 'cost_center_budgets';
    protected static array $fillable = [
        'fiscal_year_id', 'cost_center_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('cost_center_id', 'ASC')
            ->get();
    }

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

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

        if ($accountId !== null) {
            $qb->where('account_id', '=', $accountId);
        } else {
            $qb->whereNull('account_id');
        }

        $existing = $qb->first();

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