<?php

declare(strict_types=1);

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Request;
use App\Core\View;
use App\Repositories\RevenueRepository;
use App\Services\ChartDataService;

final class RevenueController
{
    public function index(): void
    {
        Auth::requireLogin();

        $currentYear = (int) date('Y');
        $year = \safe_int(Request::get('year'), $currentYear);
        $compareYear = \safe_int(Request::get('compare_year'), $year - 1);
        $hospitalCode = strtolower((string) Request::get('hospital', Auth::hospital()));

        if (!array_key_exists($hospitalCode, \config('hospitals', []))) {
            $hospitalCode = Auth::hospital();
        }

        $hospital = \config('hospitals.' . $hospitalCode);
        $repo = new RevenueRepository($hospitalCode);
        $chartService = new ChartDataService();

        $totalRows = $repo->monthlyRevenue($year, $compareYear, 'total');
        $cashRows = $repo->monthlyRevenue($year, $compareYear, 'cash');
        $insuranceRows = $repo->monthlyRevenue($year, $compareYear, 'insurance');
        $mohRows = $repo->monthlyRevenue($year, $compareYear, 'moh', (string) $hospital['moh_customer_code']);
        $profitLossRows = $repo->monthlyProfitLoss($year, $compareYear, (int) $hospital['profit_loss_company_id']);

        $charts = [
            'total' => [
                'title' => 'Monthly Total Revenue',
                'rows' => $totalRows,
                'payload' => $chartService->comparePayload($totalRows, 'Monthly Total Revenue', $year, $compareYear),
            ],
            'cash' => [
                'title' => 'Monthly Total Cash Revenue',
                'rows' => $cashRows,
                'payload' => $chartService->comparePayload($cashRows, 'Monthly Total Cash Revenue', $year, $compareYear),
            ],
            'insurance' => [
                'title' => 'Monthly Total Insurance Revenue',
                'rows' => $insuranceRows,
                'payload' => $chartService->comparePayload($insuranceRows, 'Monthly Total Insurance Revenue', $year, $compareYear),
            ],
            'moh' => [
                'title' => 'Monthly Total MOH Revenue',
                'rows' => $mohRows,
                'payload' => $chartService->comparePayload($mohRows, 'Monthly Total MOH Revenue', $year, $compareYear),
            ],
            'profit_loss' => [
                'title' => 'Monthly Total Profit / Loss',
                'rows' => $profitLossRows,
                'payload' => $chartService->comparePayload($profitLossRows, 'Monthly Total Profit / Loss', $year, $compareYear),
            ],
        ];

        $cards = [];
        foreach ($charts as $key => $chart) {
            $currentTotal = $chartService->total($chart['rows'], 'current_value');
            $compareTotal = $chartService->total($chart['rows'], 'compare_value');
            $cards[$key] = [
                'title' => $chart['title'],
                'current_total' => $currentTotal,
                'compare_total' => $compareTotal,
                'percent' => $chartService->percentChange($currentTotal, $compareTotal),
            ];
        }

        View::render('revenue/index', [
            'title' => 'Revenue Dashboard',
            'activePage' => 'revenue',
            'year' => $year,
            'compareYear' => $compareYear,
            'hospitalCode' => $hospitalCode,
            'hospital' => $hospital,
            'hospitals' => \config('hospitals'),
            'charts' => $charts,
            'cards' => $cards,
        ]);
    }
}
