<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Request;
use App\Models\PortalData;
use App\Services\PortalAccess;

final class HomeController extends BaseController
{
    public function index(Request $request): void
    {
        $this->requirePage('home');
        $pages = [];
        foreach (PortalAccess::PAGES as $key => $label) {
            if ($key === 'home') {
                continue;
            }
            if (can_see($key)) {
                $pages[] = $key;
            }
        }
        $invoices = can_see('invoices') ? PortalData::invoices() : [];
        $unpaid = 0;
        foreach ($invoices as $inv) {
            if (in_array((string) ($inv['status'] ?? ''), ['unpaid', 'partial'], true)) {
                $unpaid++;
            }
        }
        $orders = can_see('orders') ? PortalData::orders() : [];
        $signs = can_see('sign') ? PortalData::pendingSigns() : [];
        view('home/index', [
            'title' => 'Home',
            'invoices' => array_slice($invoices, 0, 4),
            'invoiceCount' => count($invoices),
            'unpaidCount' => $unpaid,
            'signs' => $signs,
            'orders' => array_slice($orders, 0, 4),
            'orderCount' => count($orders),
            'pages' => $pages,
        ]);
    }
}
