<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Relations\BelongsTo;

class BudgetLine extends BaseModel
{
    public const MONTHS = ['jan', 'feb', 'mar', 'apr', 'may', 'jun', 'jul', 'aug', 'sep', 'oct', 'nov', 'dec'];

    protected $fillable = [
        'company_id',
        'budget_id',
        'account_id',
        'dim1_id',
        'dim2_id',
        'dim3_id',
        'customer_id',
        'period_amounts',
        'jan', 'feb', 'mar', 'apr', 'may', 'jun',
        'jul', 'aug', 'sep', 'oct', 'nov', 'dec',
        'total',
    ];

    protected $casts = [
        'period_amounts' => 'array',
        'jan' => 'decimal:2',
        'feb' => 'decimal:2',
        'mar' => 'decimal:2',
        'apr' => 'decimal:2',
        'may' => 'decimal:2',
        'jun' => 'decimal:2',
        'jul' => 'decimal:2',
        'aug' => 'decimal:2',
        'sep' => 'decimal:2',
        'oct' => 'decimal:2',
        'nov' => 'decimal:2',
        'dec' => 'decimal:2',
        'total' => 'decimal:2',
    ];

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

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

    public static function sumMonths(array $amounts): float
    {
        $total = 0.0;
        foreach ($amounts as $amount) {
            $total += (float) $amount;
        }

        return round($total, 2);
    }

    /** @return array<string, float> */
    public static function legacyMonthAmounts(BudgetLine $line, int $year): array
    {
        $amounts = [];

        foreach (self::MONTHS as $index => $month) {
            $value = (float) $line->{$month};
            if ($value <= 0) {
                continue;
            }

            $amounts[sprintf('%04d-%02d', $year, $index + 1)] = $value;
        }

        return $amounts;
    }
}
