<?php

use ChurchCRM\dto\SystemURLs;
use ChurchCRM\Service\FinancialService;
use ChurchCRM\Service\ExpenseService;
use ChurchCRM\view\PageHeader;
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Views\PhpRenderer;

// Financial Analysis - Deposits vs Expenses Remaining Balance
$app->get('/analysis', function (Request $request, Response $response) {
    $financialService = new FinancialService();
    $expenseService = new ExpenseService();
    
    // Get fiscal year dates
    $dashboardData = $financialService->getDashboardData();
    $fiscalYear = $dashboardData['fiscalYear'];
    $fyStartDate = $fiscalYear['startDate'];
    $fyEndDate = $fiscalYear['endDate'];
    $fyLabel = $fiscalYear['label'];
    
    // Get financial data
    $ytdPaymentTotal = $dashboardData['ytdPaymentTotal'] ?? 0;
    $ytdPledgeTotal = $dashboardData['ytdPledgeTotal'] ?? 0;
    $totalDeposits = $ytdPaymentTotal + $ytdPledgeTotal;
    
    // Get expense data
    $expenseSummary = $expenseService->getDashboardSummary($fyStartDate, $fyEndDate);
    $totalExpenses = $expenseSummary['total_expenses'] ?? 0;
    
    // Calculate remaining balance
    $remainingBalance = $totalDeposits - $totalExpenses;
    $balancePercentage = $totalDeposits > 0 ? ($remainingBalance / $totalDeposits) * 100 : 0;
    $expensePercentage = $totalDeposits > 0 ? ($totalExpenses / $totalDeposits) * 100 : 0;
    
    // Determine status color
    if ($remainingBalance < 0) {
        $statusColor = 'danger';
        $statusIcon = 'fa-triangle-exclamation';
        $statusText = gettext('Deficit');
    } elseif ($remainingBalance < ($totalDeposits * 0.1)) {
        $statusColor = 'warning';
        $statusIcon = 'fa-circle-exclamation';
        $statusText = gettext('Low Balance');
    } else {
        $statusColor = 'success';
        $statusIcon = 'fa-check-circle';
        $statusText = gettext('Healthy');
    }
    
    $pageArgs = [
        'sRootPath'  => SystemURLs::getRootPath(),
        'sPageTitle' => gettext('Financial Analysis'),
        'sPageSubtitle' => gettext('Deposits vs Expenses Remaining Balance'),
        'aBreadcrumbs' => PageHeader::breadcrumbs([
            [gettext('Finance'), '/finance/'],
            [gettext('Financial Analysis')],
        ]),
        'ytdPaymentTotal' => $ytdPaymentTotal,
        'ytdPledgeTotal' => $ytdPledgeTotal,
        'totalDeposits' => $totalDeposits,
        'totalExpenses' => $totalExpenses,
        'remainingBalance' => $remainingBalance,
        'balancePercentage' => $balancePercentage,
        'expensePercentage' => $expensePercentage,
        'statusColor' => $statusColor,
        'statusIcon' => $statusIcon,
        'statusText' => $statusText,
        'expenseSummary' => $expenseSummary,
        'fyLabel' => $fyLabel,
    ];
    
    $renderer = new PhpRenderer(__DIR__ . '/../views/');
    return $renderer->render($response, 'financial-analysis.php', $pageArgs);
});
