<?php
/**
 * DashboardController — role-aware landing page.
 *
 * indexAction routes each user's group to the dashboard purpose-built for
 * them. Everyone can also bookmark a specific dashboard via a dedicated
 * action:
 *
 *   /Dashboard/exec        — Executive (financial-first)
 *   /Dashboard/finance     — Finance Manager · Accountant
 *   /Dashboard/fleet       — Fleet Manager
 *   /Dashboard/ops         — Ops Manager · Dispatcher
 *   /Dashboard/hr          — HR Officer
 *   /Dashboard/fuel        — Fuel Officer
 *   /Dashboard/procurement — Procurement
 *   /Dashboard/fleetLegacy — the old fleet KPI dashboard (fallback)
 */
class DashboardController extends Controller
{
    public function indexAction()
    {
        $role = strtolower(trim($_SESSION['user_group_name'] ?? ''));

        $map = [
            'executive'         => 'exec',
            'finance manager'   => 'finance',
            'accountant'        => 'finance',
            'fleet manager'     => 'fleet',
            'field supervisor'  => 'fleet',
            'ops manager'       => 'ops',
            'dispatcher'        => 'ops',
            'hr officer'        => 'hr',
            'fuel officer'      => 'fuel',
            'procurement'       => 'procurement',
        ];
        $flavour = $map[$role] ?? 'fleetLegacy';

        $method = $flavour . 'Action';
        $this->$method();
    }

    public function execAction()        { $this->renderExec(); }
    public function financeAction()     { $this->renderFinance(); }
    public function fleetAction()       { $this->renderFleet(); }
    public function opsAction()         { $this->renderOps(); }
    public function hrAction()          { $this->renderHr(); }
    public function fuelAction()        { $this->renderFuel(); }
    public function procurementAction() { $this->renderProcurement(); }

    /** Fallback: the legacy PacificDashboard KPI grid — used by any role
     *  that doesn't have a purpose-built dashboard yet. */
    public function fleetLegacyAction()
    {
        $m = new PacificDashboard();
        $this->view->setLayout($this->roleLayout());
        $this->view->render('Dashboard/index', [
            'page_title'      => 'Dashboard',
            'full_name'       => $_SESSION['full_name']       ?? '',
            'role_name'       => $_SESSION['user_group_name'] ?? '',
            'kpis'            => $m->kpis(),
            'recent_trips'    => $m->recentTrips(6),
            'pending_reqs'    => $m->pendingRequests(6),
            'compliance'      => $m->complianceAlerts(8),
        ]);
    }

    /* ══════════════════════════════════════════════════════════════════
       Render helpers — one per dashboard flavour.
       ══════════════════════════════════════════════════════════════════ */

    private function renderExec(): void
    {
        $summary = (new PacificExecDashboard())->financialSummary();
        $exec    = new PacificExecDashboard();
        $q       = new DashboardQueries();

        $this->view->setLayout($this->roleLayout());
        $this->view->render('Dashboard/pacific_exec', $this->baseData('Executive Dashboard') + [
            'summary'         => $summary,
            'overdue_ar'      => $exec->topOverdueAr(5),
            'due_soon_ap'     => $exec->topDueSoonAp(5),
            'trip_pipeline'   => $exec->tripPipeline(),
            'compliance'      => $exec->complianceCounts(),
            'recent_journals' => $exec->recentJournals(8),
            'kpi_tiles'       => $q->kpiTiles('exec'),
            'feed_trips'      => $q->recentTrips(6),
            'feed_compliance' => $q->complianceUpcoming(6),
            'charts' => [
                'revenue'    => $q->revenueTrend12(),
                'cover'      => ['series' => [$q->cashCoverRatio()['value']], 'label' => 'Cash cover'],
                'ar_aging'   => $q->arAgingDonut(),
                'rev_vs_exp' => $q->revenueVsExpenses6(),
            ],
        ]);
    }

    private function renderFinance(): void
    {
        $q = new DashboardQueries();
        $this->view->setLayout($this->roleLayout());
        $this->view->render('Dashboard/finance_manager', $this->baseData('Finance Dashboard') + [
            'kpi_tiles'       => $q->kpiTiles('finance'),
            'feed_bills'      => $q->recentSupplierBills(6),
            'feed_compliance' => $q->complianceUpcoming(6),
            'charts' => [
                'funnel' => $q->billLifecycleFunnel(),
                'cash'   => $q->dailyCash60(),
                'flows'  => $q->receiptsVsPayments6(),
                'mix'    => $q->expenseMixDonut(),
            ],
        ]);
    }

    private function renderFleet(): void
    {
        $q = new DashboardQueries();
        $this->view->setLayout($this->roleLayout());
        $this->view->render('Dashboard/fleet_manager', $this->baseData('Fleet Dashboard') + [
            'kpi_tiles'       => $q->kpiTiles('fleet'),
            'feed_trips'      => $q->recentTrips(6),
            'feed_compliance' => $q->complianceUpcoming(6),
            'charts' => [
                'util' => ['series' => [$q->fleetUtilisation()['value']], 'label' => 'On-trip %'],
                'km'   => $q->truckKm30(),
                'docs' => $q->docExpiryComposition(),
                'heat' => $q->tripDepartureHeatmap(),
            ],
        ]);
    }

    private function renderOps(): void
    {
        $q = new DashboardQueries();
        $this->view->setLayout($this->roleLayout());
        $this->view->render('Dashboard/ops_manager', $this->baseData('Ops Dashboard') + [
            'kpi_tiles'     => $q->kpiTiles('ops'),
            'feed_trips'    => $q->recentTrips(6),
            'feed_requests' => $q->requestsNeedingAttention(6),
            'charts' => [
                'funnel' => $q->tripPipelineFunnel(),
                'ontime' => ['series' => [$q->onTimeRate30()['value']], 'label' => 'On-time %'],
                'cust'   => $q->topCustomersOpenTrips(),
                'gantt'  => $q->todayTripGantt(),
            ],
        ]);
    }

    private function renderHr(): void
    {
        $q = new DashboardQueries();
        $this->view->setLayout($this->roleLayout());
        $this->view->render('Dashboard/hr_officer', $this->baseData('HR Dashboard') + [
            'kpi_tiles'         => $q->kpiTiles('hr'),
            'feed_assignments'  => $q->recentAssignmentsHr(6),
            'feed_compliance'   => $q->complianceUpcoming(6),
            'charts' => [
                'net'   => $q->netPayrollMonthly(),
                'stat'  => $q->statutoryDonut(),
                'heads' => $q->headcountTrend6(),
                'sev'   => $q->docExpirySeverityBar(),
            ],
        ]);
    }

    private function renderFuel(): void
    {
        $q = new DashboardQueries();
        $this->view->setLayout($this->roleLayout());
        $this->view->render('Dashboard/fuel_officer', $this->baseData('Fuel Dashboard') + [
            'kpi_tiles' => $q->kpiTiles('fuel'),
            'feed_fuel' => $q->recentFuelEntries(6),
            'charts' => [
                'spend' => $q->weeklyFuelSpend(),
                'pm'    => $q->fuelPaymentMethodDonut(),
                'l'     => $q->topLitres30(),
            ],
        ]);
    }

    private function renderProcurement(): void
    {
        $q = new DashboardQueries();
        $this->view->setLayout($this->roleLayout());
        $this->view->render('Dashboard/procurement', $this->baseData('Procurement Dashboard') + [
            'kpi_tiles'  => $q->kpiTiles('procurement'),
            'feed_bills' => $q->recentSupplierBills(6),
            'charts' => [
                'top'   => $q->topSuppliersSpendYtd(),
                'aging' => $q->apAgingDonut(),
                'vol'   => $q->billVsPaymentVolume6(),
                'dtp'   => $q->avgDaysToPayTrend(),
            ],
        ]);
    }

    private function baseData(string $title): array
    {
        return [
            'page_title' => $title,
            'full_name'  => $_SESSION['full_name']       ?? '',
            'role_name'  => $_SESSION['user_group_name'] ?? '',
        ];
    }
}
