<?php

namespace App\Services\ImportExport\Handlers;

use App\Services\Finance\FinancialReportService;
use Illuminate\Support\Carbon;

class BalanceSheetHandler extends AbstractModuleHandler
{
    public function key(): string
    {
        return 'balance-sheet';
    }

    public function label(): string
    {
        return 'Balance Sheet';
    }

    public function permissionModule(): string
    {
        return 'finance';
    }

    public function exportData(array $filters): array
    {
        $asOf = Carbon::parse($filters['as_of'] ?? now());
        $report = app(FinancialReportService::class)->balanceSheet($asOf);

        $rows = [];
        $rows[] = ['ASSETS', '', ''];
        foreach ($report['assets'] as $row) {
            $rows[] = [$row['code'], $row['name'], number_format((float) $row['balance'], 2, '.', '')];
        }
        $rows[] = ['', 'Total Assets', number_format((float) $report['total_assets'], 2, '.', '')];
        $rows[] = ['', '', ''];
        $rows[] = ['LIABILITIES', '', ''];
        foreach ($report['liabilities'] as $row) {
            $rows[] = [$row['code'], $row['name'], number_format((float) $row['balance'], 2, '.', '')];
        }
        $rows[] = ['', 'Total Liabilities', number_format((float) $report['total_liabilities'], 2, '.', '')];
        $rows[] = ['', '', ''];
        $rows[] = ['EQUITY', '', ''];
        foreach ($report['equity'] as $row) {
            $rows[] = [$row['code'], $row['name'], number_format((float) $row['balance'], 2, '.', '')];
        }
        $rows[] = ['', 'Total Equity', number_format((float) $report['total_equity'], 2, '.', '')];

        return [
            'title' => 'Balance Sheet',
            'sheet_name' => 'Balance Sheet',
            'headings' => ['Code', 'Account', 'Balance'],
            'rows' => $rows,
            'filters' => ['as_of' => $asOf->toDateString()],
            'totals' => [
                'Total Assets' => number_format((float) $report['total_assets'], 2),
                'Total Liabilities' => number_format((float) $report['total_liabilities'], 2),
                'Total Equity' => number_format((float) $report['total_equity'], 2),
            ],
        ];
    }
}
