<?php
declare(strict_types=1);

namespace App\Modules\Accounting\Models;

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

class AccountBalance extends Model
{
    protected static string $table = 'account_balances';
    protected static array $fillable = [
        'account_id', 'fiscal_year_id', 'period',
        'opening_debit', 'opening_credit', 'period_debit', 'period_credit',
        'closing_debit', 'closing_credit', 'cost_center_id', 'branch_id',
        'is_closed',
    ];
    protected static bool $timestamps = true;
    protected static bool $softDelete = false;
    protected static bool $autoTrackAuthor = false;
    protected static bool $dispatchEvents = false;

    public static function getForPeriod(int $fiscalYearId, string $period, ?int $costCenterId = null, ?int $branchId = null): array
    {
        $db = App::getInstance()->db();
        $where = 'ab.fiscal_year_id = ? AND ab.period = ?';
        $params = [$fiscalYearId, $period];

        if ($costCenterId !== null) {
            $where .= ' AND ab.cost_center_id = ?';
            $params[] = $costCenterId;
        }
        if ($branchId !== null) {
            $where .= ' AND ab.branch_id = ?';
            $params[] = $branchId;
        }

        return $db->select(
            "SELECT ab.*, coa.account_code, coa.name_ar, coa.name_en,
                    coa.account_type, coa.account_nature, coa.level, coa.is_header
             FROM account_balances ab
             JOIN chart_of_accounts coa ON coa.id = ab.account_id
             WHERE {$where}
             ORDER BY coa.account_code ASC",
            $params
        );
    }

    public static function upsert(array $data): void
    {
        $db = App::getInstance()->db();
        $db->execute(
            "INSERT INTO account_balances
                (account_id, fiscal_year_id, period, opening_debit, opening_credit,
                 period_debit, period_credit, closing_debit, closing_credit,
                 cost_center_id, branch_id, created_at, updated_at)
             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NOW(), NOW())
             ON DUPLICATE KEY UPDATE
                period_debit   = VALUES(period_debit),
                period_credit  = VALUES(period_credit),
                closing_debit  = VALUES(closing_debit),
                closing_credit = VALUES(closing_credit),
                updated_at     = NOW()",
            [
                $data['account_id'], $data['fiscal_year_id'], $data['period'],
                $data['opening_debit'] ?? '0.00', $data['opening_credit'] ?? '0.00',
                $data['period_debit'] ?? '0.00', $data['period_credit'] ?? '0.00',
                $data['closing_debit'] ?? '0.00', $data['closing_credit'] ?? '0.00',
                $data['cost_center_id'] ?? null, $data['branch_id'] ?? null,
            ]
        );
    }
}
