<?php
declare(strict_types=1);

const UAE_VAT_RATE = 0.05;
const UAE_CT_THRESHOLD = 375000.00;
const UAE_CT_RATE = 0.09;

if (!function_exists('financial_has_table')) {
    function financial_has_table(PDO $pdo, string $table): bool
    {
        try {
            $st = $pdo->prepare('SHOW TABLES LIKE ?');
            $st->execute([$table]);
            return (bool)$st->fetchColumn();
        } catch (Throwable $e) {
            return false;
        }
    }
}

if (!function_exists('financial_tax_from_gross')) {
    function financial_tax_from_gross(float $grossAmount): array
    {
        $grossAmount = max(0.0, $grossAmount);
        $vatAmount = round($grossAmount - ($grossAmount / (1 + UAE_VAT_RATE)), 2);
        $netAmount = round($grossAmount - $vatAmount, 2);

        return [$vatAmount, $netAmount];
    }
}

if (!function_exists('financial_recalculate_tax_summary')) {
    function financial_recalculate_tax_summary(PDO $pdo, int $branchId, int $taxYear): void
    {
        if (!financial_has_table($pdo, 'financial_tax_summary')) {
            return;
        }

        $incomeCols = function_exists('financial_table_columns') ? financial_table_columns($pdo, 'financial_income') : [];
        $expenseCols = function_exists('financial_table_columns') ? financial_table_columns($pdo, 'financial_expenses') : [];

        $incomeNetExpr = in_array('net_amount', $incomeCols, true) ? 'COALESCE(net_amount, amount)' : 'amount';
        $incomeVatExpr = in_array('vat_amount', $incomeCols, true) ? 'COALESCE(vat_amount, 0)' : '0';
        $expenseNetExpr = in_array('net_amount', $expenseCols, true) ? 'COALESCE(net_amount, amount)' : 'amount';
        $expenseVatExpr = in_array('vat_amount', $expenseCols, true) ? 'COALESCE(vat_amount, 0)' : '0';

        $stIncome = $pdo->prepare("\n            SELECT\n                COALESCE(SUM({$incomeNetExpr}), 0) AS total_income,\n                COALESCE(SUM({$incomeVatExpr}), 0) AS output_vat\n            FROM financial_income\n            WHERE branch_id = ? AND YEAR(income_date) = ?\n        ");
        $stIncome->execute([$branchId, $taxYear]);
        $income = $stIncome->fetch(PDO::FETCH_ASSOC) ?: [];

        $stExpense = $pdo->prepare("\n            SELECT\n                COALESCE(SUM({$expenseNetExpr}), 0) AS total_expenses,\n                COALESCE(SUM({$expenseVatExpr}), 0) AS input_vat\n            FROM financial_expenses\n            WHERE branch_id = ? AND YEAR(expense_date) = ?\n        ");
        $stExpense->execute([$branchId, $taxYear]);
        $expense = $stExpense->fetch(PDO::FETCH_ASSOC) ?: [];

        $totalIncome = (float)($income['total_income'] ?? 0);
        $totalExpenses = (float)($expense['total_expenses'] ?? 0);
        $outputVat = (float)($income['output_vat'] ?? 0);
        $inputVat = (float)($expense['input_vat'] ?? 0);
        $netProfit = round($totalIncome - $totalExpenses, 2);
        $vatPayable = round($outputVat - $inputVat, 2);
        $corporateTax = round(max(0, $netProfit - UAE_CT_THRESHOLD) * UAE_CT_RATE, 2);

        $st = $pdo->prepare("\n            INSERT INTO financial_tax_summary\n            (branch_id, tax_year, total_income, total_expenses, net_profit, output_vat, input_vat, vat_payable, corporate_tax)\n            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)\n            ON DUPLICATE KEY UPDATE\n                total_income = VALUES(total_income),\n                total_expenses = VALUES(total_expenses),\n                net_profit = VALUES(net_profit),\n                output_vat = VALUES(output_vat),\n                input_vat = VALUES(input_vat),\n                vat_payable = VALUES(vat_payable),\n                corporate_tax = VALUES(corporate_tax)\n        ");

        $st->execute([
            $branchId,
            $taxYear,
            $totalIncome,
            $totalExpenses,
            $netProfit,
            $outputVat,
            $inputVat,
            $vatPayable,
            $corporateTax,
        ]);
    }
}
