<?php

namespace App\Controllers;

use App\Models\ExpenseModel;
use App\Models\FolioLineItemModel;
use Config\Lookups;

/**
 * Profit & Loss — nets real revenue against real operating expenses.
 * Revenue reuses FolioLineItemModel::totalBetween()/byCategoryBetween(),
 * the exact same "charges posted" figure ReportController::buildReport()
 * already shows as the Revenue KPI, so this never disagrees with the
 * main Reports page. Expense side only counts status='approved' rows
 * (see ExpenseModel::totalApprovedBetween()) — pending/denied expenses
 * aren't real costs yet.
 *
 * Own controller/route/view rather than folded into buildReport(),
 * matching how Staff Performance is also its own controller linked from
 * the Reports area rather than code merged into the one KPI-dashboard
 * method.
 */
class ProfitLossController extends BaseController
{
    public function index()
    {
        $dateFrom = $this->request->getGet('date_from') ?: date('Y-m-d', strtotime('-6 days'));
        $dateTo   = $this->request->getGet('date_to') ?: date('Y-m-d');

        $lineItems = new FolioLineItemModel();
        $expenses  = new ExpenseModel();

        $revenue      = $lineItems->totalBetween($dateFrom, $dateTo);
        $expenseTotal = $expenses->totalApprovedBetween($dateFrom, $dateTo);
        $net          = money_subtract($revenue, $expenseTotal);

        return view('reports/profit_loss', [
            'pageTitle'          => 'Profit & Loss',
            'dateFrom'           => $dateFrom,
            'dateTo'             => $dateTo,
            'revenue'            => $revenue,
            'expenseTotal'       => $expenseTotal,
            'net'                => $net,
            'revenueByCategory'  => $lineItems->byCategoryBetween($dateFrom, $dateTo),
            'expensesByCategory' => $expenses->byCategoryApprovedBetween($dateFrom, $dateTo),
            'lookups'            => new Lookups(),
        ]);
    }
}
