<?php

namespace App\Controllers;

use App\Models\RolePermissionModel;
use App\Models\UserModel;
use Config\Lookups;

/**
 * Role Management — see CreateRolePermissionsTable's doc comment for the
 * exact scope: this edits per-role nav visibility (real, stored,
 * verifiable), not the underlying access-control boundary. Roles
 * themselves stay fixed at whatever's built into Config\Lookups::
 * $staffRoles/Routes.php's role: filter groups (manager/front_desk/fnb,
 * plus Phase 4's housekeeping/accounts) — turning those into fully
 * dynamic, staff-creatable roles would mean rewriting every
 * `role:manager,front_desk`-style route group in Routes.php to consult a
 * database instead of a hardcoded string list, a materially larger
 * change than a permissions matrix over a fixed role set. This
 * controller itself is already fully driven by $staffRoles/
 * $permissionModules, so adding a role only ever means editing
 * Config\Lookups + Routes.php, never this file. Manager-only (same as
 * Settings/Staff).
 */
class RoleManagementController extends BaseController
{
    public function index()
    {
        $lookups     = new Lookups();
        $permissions = new RolePermissionModel();
        $staffCounts = [];

        foreach (array_keys($lookups->staffRoles) as $role) {
            $staffCounts[$role] = (new UserModel())->where('role', $role)->where('is_active', 1)->countAllResults();
        }

        return view('role_management/index', [
            'pageTitle'    => 'Role Management',
            'pageSubtitle' => 'Control which nav sections each staff role sees.',
            'lookups'      => $lookups,
            'staffCounts'  => $staffCounts,
            'permissionsByRole' => array_combine(
                array_keys($lookups->staffRoles),
                array_map(static fn ($role) => $permissions->forRole($role), array_keys($lookups->staffRoles)),
            ),
        ]);
    }

    public function update(string $role)
    {
        $lookups = new Lookups();

        if (! array_key_exists($role, $lookups->staffRoles)) {
            return redirect()->to('role-management')->with('error', 'Unknown role.');
        }

        $moduleAllowed = [];

        foreach ($lookups->permissionModules as $key => $meta) {
            if (! in_array($role, $meta['roles'], true)) {
                continue; // not a module this role could ever see — nothing to store
            }

            $moduleAllowed[$key] = (bool) $this->request->getPost('module_' . $key);
        }

        (new RolePermissionModel())->saveForRole($role, $moduleAllowed);

        $this->logActivity('settings', 'Updated nav permissions for the ' . ($lookups->staffRoles[$role]['label'] ?? $role) . ' role.');

        return redirect()->to('role-management')->with('success', 'Permissions saved for ' . ($lookups->staffRoles[$role]['label'] ?? $role) . '.');
    }
}
