<?php
declare(strict_types=1);

namespace App\Controllers;

use App\Core\Auth;
use App\Core\Request;
use App\Models\Role;
use App\Models\User;

final class RoleController extends BaseController
{
    public function index(Request $request): void
    {
        $this->requireModule('roles');
        $roles = Role::all();
        $people = User::listForTenant((int) Auth::instance()->tenantId(), false);
        $roleCounts = [];
        $roleActive = [];
        foreach ($roles as $r) {
            $code = (string) $r['code'];
            $roleCounts[$code] = 0;
            $roleActive[$code] = 0;
        }
        $twoPlus = 0;
        $assigned = 0;
        foreach ($people as $p) {
            $codes = array_values(array_filter(array_map('trim', explode(',', (string) ($p['role_codes'] ?? '')))));
            if ($codes === []) {
                continue;
            }
            $assigned++;
            if (count($codes) > 1) {
                $twoPlus++;
            }
            $on = (($p['login_status'] ?? $p['status'] ?? '') === 'active');
            foreach ($codes as $code) {
                if (!isset($roleCounts[$code])) {
                    continue;
                }
                $roleCounts[$code]++;
                if ($on) {
                    $roleActive[$code]++;
                }
            }
        }
        view('roles/index', [
            'title' => 'Roles',
            'roles' => $roles,
            'roleCounts' => $roleCounts,
            'roleActive' => $roleActive,
            'people' => count($people),
            'assigned' => $assigned,
            'twoPlus' => $twoPlus,
            'notifications' => $this->notifications(),
        ]);
    }
}
