<?php

namespace App\Services\ImportExport\Handlers;

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

class CashflowHandler extends AbstractModuleHandler
{
    public function key(): string
    {
        return 'cashflow';
    }

    public function label(): string
    {
        return 'Cash Flow Statement';
    }

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

    public function exportData(array $filters): array
    {
        $from = Carbon::parse($filters['from'] ?? now()->startOfYear());
        $to = Carbon::parse($filters['to'] ?? now());
        $report = app(FinancialReportService::class)->cashflow($from, $to);

        $rows = [
            ['Opening Cash', number_format((float) $report['opening_cash'], 2, '.', '')],
            ['Total Inflows', number_format((float) $report['total_inflows'], 2, '.', '')],
        ];

        foreach ($report['inflows'] as $row) {
            $rows[] = ["  {$row['code']} — {$row['name']}", number_format((float) $row['amount'], 2, '.', '')];
        }

        $rows[] = ['Total Outflows', number_format((float) $report['total_outflows'], 2, '.', '')];

        foreach ($report['outflows'] as $row) {
            $rows[] = ["  {$row['code']} — {$row['name']}", number_format((float) $row['amount'], 2, '.', '')];
        }

        $rows[] = ['Net Cash Change', number_format((float) $report['net_change'], 2, '.', '')];
        $rows[] = ['Closing Cash', number_format((float) $report['closing_cash'], 2, '.', '')];

        return [
            'title' => 'Cash Flow Statement',
            'sheet_name' => 'Cash Flow',
            'headings' => ['Description', 'Amount'],
            'rows' => $rows,
            'filters' => ['from' => $from->toDateString(), 'to' => $to->toDateString()],
            'totals' => ['Net Change' => number_format((float) $report['net_change'], 2)],
        ];
    }
}
