<?php
class UserGroups extends Model
{
    /** Load all group perms for the current user into $_SESSION['perms'] on first hit. */
    public static function loadPermsIntoSession(int $user_group_id, int $user_id = 0): void
    {
        $db = new DB();
        $rows = $db->mySelect(
            "SELECT controller_allowed, action_allowed
               FROM user_groups_perms
              WHERE user_group_id = :gid",
            [':gid' => $user_group_id]
        ) ?: [];

        $perms = [];
        foreach ($rows as $r) {
            $perms[strtolower($r['controller_allowed'])][strtolower($r['action_allowed'])] = 1;
        }

        if ($user_id > 0) {
            $sp = $db->mySelect(
                "SELECT controller_allowed, action_allowed
                   FROM special_user_perms WHERE user_id = :uid",
                [':uid' => $user_id]
            ) ?: [];
            foreach ($sp as $r) {
                $perms[strtolower($r['controller_allowed'])][strtolower($r['action_allowed'])] = 1;
            }
        }

        $_SESSION['perms']           = $perms;
        $_SESSION['_perms_loaded']   = 1;
    }

    public static function sessionCanAccess(string $controller, string $action): bool
    {
        if (empty($_SESSION['_perms_loaded'])) {
            self::loadPermsIntoSession(
                (int)($_SESSION['user_group_id'] ?? 0),
                (int)($_SESSION['user_id'] ?? 0)
            );
        }
        $c = strtolower($controller);
        $a = strtolower($action);
        return !empty($_SESSION['perms'][$c][$a]);
    }

    /** For templates: hide/show sidebar entries based on perms. */
    public static function can(string $controller, string $action = 'index'): bool
    {
        return self::sessionCanAccess($controller, $action);
    }
}
