<?php

function loadUserPermissions(mysqli $conn): array {
    if (isAdmin()) {
        return array_fill_keys(PERM_KEYS, true);
    }

    $uid  = currentUserId();
    $stmt = $conn->prepare("SELECT " . implode(',', PERM_KEYS) . " FROM user_permissions WHERE user_id = ? LIMIT 1");
    $stmt->bind_param("i", $uid);
    $stmt->execute();

    $tmpRow = array_fill_keys(PERM_KEYS, 0);
    $refs   = [];
    foreach (PERM_KEYS as $k) { $refs[] = &$tmpRow[$k]; }
    $stmt->bind_result(...$refs);
    $found = (bool)$stmt->fetch();
    $stmt->close();

    if (!$found) {
        return array_fill_keys(PERM_KEYS, false);
    }

    $perms = [];
    foreach (PERM_KEYS as $k) {
        $perms[$k] = (bool)$tmpRow[$k];
    }
    return $perms;
}

function hasPerm(string $key): bool {
    global $userPerms;
    if (isAdmin()) return true;
    return (bool)($userPerms[$key] ?? false);
}

function accessDenied(string $msg = 'Access denied. You do not have permission to view this page.'): void {
    echo '<div class="container-fluid px-4 py-4">
            <div class="alert" style="background:rgba(255,0,60,.15);border:1px solid rgba(255,0,60,.4);color:#ff003c;border-radius:10px;">
                <i class="fa fa-lock me-2"></i>' . htmlspecialchars($msg) . '
            </div>
          </div>';
}

const PERM_KEYS = [
    'can_view_groups', 'can_add_group',    'can_edit_group',    'can_delete_group',
    'can_view_rdp',    'can_add_rdp',      'can_edit_rdp',      'can_delete_rdp',
    'can_view_vm',     'can_add_vm',       'can_edit_vm',       'can_delete_vm',   'can_send_commands',
    'can_view_earnings','can_view_reports','can_view_analytics','can_view_ip',
    'can_view_dashboard','can_view_settings','can_change_password','can_view_tokens',
];

const PERM_LABELS = [
    'can_view_groups'    => ['group'  , 'View Groups'],
    'can_add_group'      => ['group'  , 'Add Groups'],
    'can_edit_group'     => ['group'  , 'Edit Groups'],
    'can_delete_group'   => ['group'  , 'Delete Groups'],
    'can_view_rdp'       => ['rdp'    , 'View RDPs'],
    'can_add_rdp'        => ['rdp'    , 'Add RDPs'],
    'can_edit_rdp'       => ['rdp'    , 'Edit RDPs'],
    'can_delete_rdp'     => ['rdp'    , 'Delete RDPs'],
    'can_view_vm'        => ['vm'     , 'View VMs'],
    'can_add_vm'         => ['vm'     , 'Add VMs'],
    'can_edit_vm'        => ['vm'     , 'Edit VMs'],
    'can_delete_vm'      => ['vm'     , 'Delete VMs'],
    'can_send_commands'  => ['vm'     , 'Send Commands'],
    'can_view_earnings'  => ['earnings', 'View Earnings'],
    'can_view_reports'   => ['earnings', 'View Reports'],
    'can_view_analytics' => ['earnings', 'View Analytics'],
    'can_view_ip'        => ['earnings', 'View IP Analysis'],
    'can_view_dashboard' => ['other'  , 'View Dashboard'],
    'can_view_settings'  => ['other'  , 'View Settings'],
    'can_change_password'=> ['other'  , 'Change Own Password'],
    'can_view_tokens'    => ['other'  , 'View Cold Tokens'],
];
