<?php
declare(strict_types=1);

namespace App\Modules\Accounting\Models;

use App\Core\Model;
use App\Core\App;

class HistoricalBalance extends Model
{
    protected static string $table = 'historical_balances';
    protected static array $fillable = [
        'account_id', 'fiscal_year_id', 'period',
        'debit_total', 'credit_total', 'closing_balance',
    ];
    protected static bool $timestamps = false;
    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 snapshotYear(int $fiscalYearId): int
    {
        $db = App::getInstance()->db();

        $balances = $db->select("
            SELECT
                jel.account_id,
                SUM(jel.debit_amount) AS debit_total,
                SUM(jel.credit_amount) AS credit_total,
                SUM(jel.debit_amount) - SUM(jel.credit_amount) AS closing_balance
            FROM journal_entry_lines jel
            JOIN journal_entries je ON je.id = jel.journal_entry_id
            WHERE je.fiscal_year_id = ? AND je.status = 'posted'
            GROUP BY jel.account_id
        ", [$fiscalYearId]);

        $now = date('Y-m-d H:i:s');
        $fy = $db->selectOne("SELECT start_date FROM fiscal_years WHERE id = ?", [$fiscalYearId]);
        $year = $fy ? substr($fy['start_date'], 0, 4) : date('Y');
        $count = 0;

        foreach ($balances as $bal) {
            $existing = $db->selectOne(
                "SELECT id FROM historical_balances WHERE account_id = ? AND fiscal_year_id = ? AND period = ?",
                [(int)$bal['account_id'], $fiscalYearId, $year]
            );

            if ($existing) {
                $db->update('historical_balances', [
                    'debit_total'     => (float)$bal['debit_total'],
                    'credit_total'    => (float)$bal['credit_total'],
                    'closing_balance' => (float)$bal['closing_balance'],
                ], 'id = ?', [(int)$existing['id']]);
            } else {
                $db->insert('historical_balances', [
                    'account_id'      => (int)$bal['account_id'],
                    'fiscal_year_id'  => $fiscalYearId,
                    'period'          => $year,
                    'debit_total'     => (float)$bal['debit_total'],
                    'credit_total'    => (float)$bal['credit_total'],
                    'closing_balance' => (float)$bal['closing_balance'],
                    'created_at'      => $now,
                ]);
            }
            $count++;
        }

        return $count;
    }
}
