<?php

declare(strict_types=1);

namespace App\Modules\Reporting\Presentation\Controllers;

use App\Core\Auth;
use App\Core\Response;
use App\Modules\Reporting\Application\Support\ReportCatalog;

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

        $cards = ReportCatalog::all();

        // Performance: the hub may contain dozens of reports sharing the same
        // permission. Resolve every unique permission once instead of calling
        // can() for every card. This keeps /reports lightweight even with RBAC.
        $permissionCache = [];
        $visible = [];
        foreach ($cards as $card) {
            $permission = trim((string)($card['permission'] ?? ''));
            if ($permission === '') {
                $visible[] = $card;
                continue;
            }

            if (!array_key_exists($permission, $permissionCache)) {
                $permissionCache[$permission] = can($permission);
            }

            if ($permissionCache[$permission]) {
                $visible[] = $card;
            }
        }

        Response::view('pages/reports/hub', [
            'page_title' => 'مركز التقارير',
            'cards' => $visible,
            'breadcrumbs' => [
                ['label'=>'لوحة التحكم','url'=>'/admin/dashboard'],
                ['label'=>'مركز التقارير'],
            ],
        ]);
    }
}
