<?php

namespace App\Http\Controllers\Reports;

use App\Http\Controllers\Controller;
use App\Services\FinancialReportService;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;

class IncomeStatementController extends Controller
{
    public function index(Request $request, FinancialReportService $svc)
    {
        $to = $request->input('to_date', Carbon::now()->toDateString());
        $from = $request->input('from_date', Carbon::parse($to)->subMonth()->toDateString());

        $current = $svc->totalsByAccountCode($from, $to);

        $accounts = DB::table('main_accounts as ma')
            ->leftJoin('account_types as at', 'at.id', '=', 'ma.account_type')
            ->where('ma.financial_category', 'IS')
            ->select(['ma.id','ma.code','ma.account_name','at.name as type_name'])
            ->orderBy('ma.code')
            ->get();

        $sections = [
            'Revenue' => ['Revenue', 'Sales', 'Other Income'],
            'Cost of Goods Sold' => ['Cost', 'Cost of Sales', 'Cost of Goods Sold', 'Purchases'],
            'Operating Expenses' => ['Expense', 'Expenses'],
        ];

        $grouped = [
            'Revenue' => [],
            'Cost of Goods Sold' => [],
            'Operating Expenses' => [],
            'Other' => [],
        ];

        foreach ($accounts as $acc) {
            $typeName = (string) ($acc->type_name ?? '');
            $bucket = 'Other';
            foreach ($sections as $name => $keywords) {
                foreach ($keywords as $k) {
                    if (stripos($typeName, $k) !== false) {
                        $bucket = $name;
                        break 2;
                    }
                }
            }

            $tot = $current[(string) $acc->code] ?? ['dr' => 0.0, 'cr' => 0.0];
            $value = (float) $tot['cr'] - (float) $tot['dr'];

            $grouped[$bucket][] = [
                'code' => $acc->code,
                'name' => $acc->account_name,
                'value' => $value,
            ];
        }

        $sum = fn(array $rows) => array_sum(array_map(fn($r) => (float) $r['value'], $rows));

        $revenue = $sum($grouped['Revenue']);
        $cogs = $sum($grouped['Cost of Goods Sold']);
        $gross = $revenue - $cogs;
        $opex = $sum($grouped['Operating Expenses']);
        $net = $gross - $opex;

        return view('reports.income-statement', compact('from','to','grouped','revenue','cogs','gross','opex','net'));
    }
}

