<?php
if (!isSuperAdmin()) {
    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>Access denied. Super Admin only.</div></div>';
    return;
}

$allGroups = [];
$gRes = $conn->query("SELECT id, name FROM `groups` ORDER BY name");
while ($row = $gRes->fetch_assoc()) $allGroups[] = $row;

$allUsers = [];
$uRes = $conn->query("SELECT id, username, role, email, is_active, last_login, created_at FROM users ORDER BY FIELD(role,'super_admin','admin','user'), username ASC");
while ($row = $uRes->fetch_assoc()) $allUsers[] = $row;

foreach ($allUsers as &$u) {
    $uid = (int)$u['id'];
    if ($u['role'] === 'super_admin') {
        $gRes2 = $conn->query("SELECT COUNT(*) as c FROM `groups`");
        $u['group_count'] = (int)$gRes2->fetch_assoc()['c'];
        $gRes3 = $conn->query("SELECT id FROM `groups`");
    } elseif ($u['role'] === 'admin') {
        $tRes = $conn->query("SELECT tenant_id FROM users WHERE id=$uid LIMIT 1");
        $tRow = $tRes ? $tRes->fetch_assoc() : null;
        if ($tRow && $tRow['tenant_id'] !== null) {
            $tid = (int)$tRow['tenant_id'];
            $gRes2 = $conn->query("SELECT COUNT(*) as c FROM `groups` WHERE tenant_id=$tid");
            $u['group_count'] = (int)$gRes2->fetch_assoc()['c'];
            $gRes3 = $conn->query("SELECT id FROM `groups` WHERE tenant_id=$tid");
        } else {
            $u['group_count'] = 0;
            $gRes3 = false;
        }
    } else {
        $gRes2 = $conn->query("SELECT COUNT(*) as c FROM user_groups WHERE user_id=$uid");
        $u['group_count'] = (int)$gRes2->fetch_assoc()['c'];
        $gRes3 = $conn->query("SELECT group_id AS id FROM user_groups WHERE user_id=$uid");
    }
    $gids = [0];
    if ($gRes3) while ($r = $gRes3->fetch_assoc()) $gids[] = (int)$r['id'];
    $gidStr = implode(',', $gids);
    $vmRes = $conn->query("SELECT COUNT(*) as c FROM vms v JOIN rdps r ON r.id=v.rdp_id WHERE r.group_id IN ($gidStr)");
    $u['vm_count'] = $vmRes ? (int)$vmRes->fetch_assoc()['c'] : 0;
    $earnRes = $conn->query("SELECT COALESCE(SUM(balance),0) as total FROM vms v JOIN rdps r ON r.id=v.rdp_id WHERE r.group_id IN ($gidStr)");
    $u['total_balance'] = $earnRes ? (float)$earnRes->fetch_assoc()['total'] : 0;
}
unset($u);

$cntSuperAdmin = count(array_filter($allUsers, function($u){ return $u['role'] === 'super_admin'; }));
$cntAdmin      = count(array_filter($allUsers, function($u){ return $u['role'] === 'admin'; }));
$cntUser       = count(array_filter($allUsers, function($u){ return $u['role'] === 'user'; }));
$cntActive     = count(array_filter($allUsers, function($u){ return (bool)$u['is_active']; }));
?>

<div class="container-fluid px-4 py-3">

<div class="d-flex align-items-center justify-content-between mb-4">
    <div>
        <h4 class="mb-0 fw-bold" style="color:#ff7700"><i class="fa fa-users-cog me-2"></i>User Management</h4>
        <small class="text-muted">Full control — click a user to view their account</small>
    </div>
    <button class="btn btn-sm" style="background:linear-gradient(135deg,#ff7700,#ff3300);color:#fff;border:none;padding:8px 18px;border-radius:8px;" onclick="openAddUser()">
        <i class="fa fa-plus me-2"></i>Add User
    </button>
</div>

<div class="row mb-4 g-3">
    <div class="col-6 col-md-3">
        <div class="text-center py-3" style="background:#0b0c10;border:1px solid rgba(255,119,0,.3);border-radius:12px;">
            <div style="font-size:26px;font-weight:700;color:#ff7700"><?= $cntSuperAdmin ?></div>
            <div class="text-muted small">Super Admins</div>
        </div>
    </div>
    <div class="col-6 col-md-3">
        <div class="text-center py-3" style="background:#0b0c10;border:1px solid rgba(155,77,255,.3);border-radius:12px;">
            <div style="font-size:26px;font-weight:700;color:#9b4dff"><?= $cntAdmin ?></div>
            <div class="text-muted small">Admins</div>
        </div>
    </div>
    <div class="col-6 col-md-3">
        <div class="text-center py-3" style="background:#0b0c10;border:1px solid rgba(0,229,255,.3);border-radius:12px;">
            <div style="font-size:26px;font-weight:700;color:#00e5ff"><?= $cntUser ?></div>
            <div class="text-muted small">Users</div>
        </div>
    </div>
    <div class="col-6 col-md-3">
        <div class="text-center py-3" style="background:#0b0c10;border:1px solid rgba(0,255,102,.3);border-radius:12px;">
            <div style="font-size:26px;font-weight:700;color:#00ff66"><?= $cntActive ?></div>
            <div class="text-muted small">Active</div>
        </div>
    </div>
</div>

<div class="table-responsive" style="background:#0b0c10;border:1px solid rgba(255,255,255,.08);border-radius:12px;overflow:hidden;">
    <table class="table table-dark table-hover mb-0" style="font-size:14px;">
        <thead style="background:rgba(255,119,0,.1);border-bottom:1px solid rgba(255,119,0,.25);">
            <tr>
                <th class="py-3 ps-4">User</th>
                <th>Role</th>
                <th>Groups</th>
                <th>VMs</th>
                <th>Balance</th>
                <th>Status</th>
                <th>Last Login</th>
                <th class="pe-3">Actions</th>
            </tr>
        </thead>
        <tbody>
        <?php foreach ($allUsers as $u):
            $isSA = $u['role'] === 'super_admin';
            $isAd = $u['role'] === 'admin';
            if ($isSA)      { $rc = '#ff7700'; $rb = 'rgba(255,119,0,.15)'; $rl = 'SUPER ADMIN'; }
            elseif ($isAd)  { $rc = '#9b4dff'; $rb = 'rgba(155,77,255,.15)'; $rl = 'ADMIN'; }
            else            { $rc = '#00e5ff'; $rb = 'rgba(0,229,255,.1)';  $rl = 'USER'; }
        ?>
        <tr style="border-bottom:1px solid rgba(255,255,255,.05);" id="user-row-<?= $u['id'] ?>">
            <td class="ps-4 py-3">
                <div class="d-flex align-items-center gap-2">
                    <div style="width:36px;height:36px;border-radius:50%;background:linear-gradient(135deg,<?= $rc ?>,<?= $isSA?'#ff3300':($isAd?'#6a00ff':'#0099bb') ?>);display:flex;align-items:center;justify-content:center;font-weight:700;font-size:14px;flex-shrink:0;">
                        <?= strtoupper(substr($u['username'],0,1)) ?>
                    </div>
                    <div>
                        <div class="fw-semibold"><?= htmlspecialchars($u['username']) ?></div>
                        <div class="text-muted" style="font-size:11px;"><?= htmlspecialchars($u['email'] ?: 'No email') ?></div>
                    </div>
                </div>
            </td>
            <td class="py-3">
                <span style="font-size:11px;padding:3px 10px;border-radius:20px;font-weight:700;background:<?= $rb ?>;color:<?= $rc ?>;border:1px solid <?= $rc ?>55;">
                    <?= $rl ?>
                </span>
            </td>
            <td class="py-3" style="color:#ccc;"><?= $u['group_count'] ?></td>
            <td class="py-3" style="color:#00ff66;font-weight:600;"><?= $u['vm_count'] ?></td>
            <td class="py-3" style="color:#ffb300;font-weight:600;">$<?= number_format($u['total_balance'],2) ?></td>
            <td class="py-3">
                <span style="<?= $u['is_active'] ? 'color:#00ff66' : 'color:#ff003c' ?>">
                    <i class="fa fa-circle" style="font-size:8px;margin-right:4px;"></i>
                    <?= $u['is_active'] ? 'Active' : 'Inactive' ?>
                </span>
            </td>
            <td class="py-3 text-muted" style="font-size:12px;">
                <?= $u['last_login'] ? date('d/m/y H:i', strtotime($u['last_login'])) : 'Never' ?>
            </td>
            <td class="pe-3 py-3">
                <div class="d-flex gap-1 flex-wrap">
                    <?php if (!$isSA): ?>
                    <a href="index.php?view_as=<?= $u['id'] ?>&page=dashboard" class="btn btn-sm" style="background:rgba(255,119,0,.15);color:#ff7700;border:1px solid rgba(255,119,0,.4);border-radius:6px;padding:4px 8px;" title="View as this user">
                        <i class="fa fa-eye"></i>
                    </a>
                    <?php endif; ?>
                    <?php if ($u['role'] === 'user'): ?>
                    <button class="btn btn-sm" style="background:rgba(155,77,255,.15);color:#9b4dff;border:1px solid rgba(155,77,255,.4);border-radius:6px;padding:4px 8px;" title="Permissions" onclick="openPermissions(<?= $u['id'] ?>,'<?= htmlspecialchars(addslashes($u['username'])) ?>')">
                        <i class="fa fa-shield-halved"></i>
                    </button>
                    <?php endif; ?>
                    <button class="btn btn-sm" style="background:rgba(255,179,0,.1);color:#ffb300;border:1px solid rgba(255,179,0,.3);border-radius:6px;padding:4px 8px;" title="Change Password" onclick="openChangePass(<?= $u['id'] ?>,'<?= htmlspecialchars(addslashes($u['username'])) ?>')">
                        <i class="fa fa-key"></i>
                    </button>
                    <?php if ($u['id'] != $_SESSION['user_id']): ?>
                    <button class="btn btn-sm" style="background:rgba(255,179,0,.1);color:#ffb300;border:1px solid rgba(255,179,0,.3);border-radius:6px;padding:4px 8px;" title="<?= $u['is_active']?'Deactivate':'Activate' ?>" onclick="toggleUser(<?= $u['id'] ?>)">
                        <i class="fa <?= $u['is_active']?'fa-ban':'fa-check' ?>"></i>
                    </button>
                    <?php if (!$isSA): ?>
                    <button class="btn btn-sm" style="background:rgba(255,0,60,.1);color:#ff003c;border:1px solid rgba(255,0,60,.3);border-radius:6px;padding:4px 8px;" title="Delete" onclick="deleteUser(<?= $u['id'] ?>,'<?= htmlspecialchars(addslashes($u['username'])) ?>')">
                        <i class="fa fa-trash"></i>
                    </button>
                    <?php endif; ?>
                    <?php if ($isAd): ?>
                    <button class="btn btn-sm" style="background:rgba(0,180,255,.15);color:#00b4ff;border:1px solid rgba(0,180,255,.4);border-radius:6px;padding:4px 8px;" title="Update Agent.ps1" onclick="openUpdateAgent(<?= $u['id'] ?>,'<?= htmlspecialchars(addslashes($u['username'])) ?>')">
                        <i class="fa fa-robot"></i>
                    </button>
                    <button class="btn btn-sm" style="background:rgba(255,50,0,.18);color:#ff5500;border:1px solid rgba(255,85,0,.5);border-radius:6px;padding:4px 8px;" title="Erase All Data" onclick="eraseAdminData(<?= $u['id'] ?>,'<?= htmlspecialchars(addslashes($u['username'])) ?>')">
                        <i class="fa fa-fire"></i>
                    </button>
                    <?php endif; ?>
                    <?php endif; ?>
                </div>
            </td>
        </tr>
        <?php endforeach; ?>
        </tbody>
    </table>
</div>
</div>

<div id="uOverlay" style="display:none;position:fixed;inset:0;background:rgba(0,0,0,.75);z-index:9000;" onclick="closeUModals()"></div>

<div id="modal-add-user" style="display:none;position:fixed;inset:0;z-index:9001;align-items:center;justify-content:center;">
    <div style="background:#0b0c10;border:1px solid rgba(255,119,0,.5);border-radius:16px;padding:28px;width:420px;max-width:95%;">
        <h5 class="mb-4 fw-bold" style="color:#ff7700"><i class="fa fa-user-plus me-2"></i>Add New User</h5>
        <div class="mb-3">
            <label class="small text-muted mb-1">Username *</label>
            <input id="nu_username" class="form-control" style="background:#050507;border:1px solid rgba(255,255,255,.15);color:#fff;" placeholder="min 3 chars">
        </div>
        <div class="mb-3">
            <label class="small text-muted mb-1">Password *</label>
            <input id="nu_password" type="password" class="form-control" style="background:#050507;border:1px solid rgba(255,255,255,.15);color:#fff;" placeholder="min 6 chars">
        </div>
        <div class="mb-3">
            <label class="small text-muted mb-1">Email</label>
            <input id="nu_email" type="email" class="form-control" style="background:#050507;border:1px solid rgba(255,255,255,.15);color:#fff;" placeholder="optional">
        </div>
        <div class="mb-4">
            <label class="small text-muted mb-1">Role</label>
            <select id="nu_role" class="form-select" style="background:#050507;border:1px solid rgba(255,255,255,.15);color:#fff;">
                <option value="user">User — permission-based access</option>
                <option value="admin">Admin — full access to own groups only</option>
                <option value="super_admin">Super Admin — full system access</option>
            </select>
        </div>
        <div class="d-flex gap-2">
            <button class="btn flex-fill" style="background:linear-gradient(135deg,#ff7700,#ff3300);color:#fff;border:none;border-radius:8px;" onclick="submitAddUser()">Create User</button>
            <button class="btn flex-fill" style="background:rgba(255,255,255,.08);color:#aaa;border:1px solid rgba(255,255,255,.1);border-radius:8px;" onclick="closeUModals()">Cancel</button>
        </div>
    </div>
</div>

<div id="modal-change-pass" style="display:none;position:fixed;inset:0;z-index:9001;align-items:center;justify-content:center;">
    <div style="background:#0b0c10;border:1px solid rgba(255,179,0,.4);border-radius:16px;padding:28px;width:380px;max-width:95%;">
        <h5 class="mb-1 fw-bold" style="color:#ffb300"><i class="fa fa-key me-2"></i>Change Password</h5>
        <p class="text-muted small mb-4" id="cp_username_label"></p>
        <input type="hidden" id="cp_user_id">
        <div class="mb-4">
            <label class="small text-muted mb-1">New Password</label>
            <input id="cp_password" type="password" class="form-control" style="background:#050507;border:1px solid rgba(255,255,255,.15);color:#fff;" placeholder="min 6 chars">
        </div>
        <div class="d-flex gap-2">
            <button class="btn flex-fill" style="background:linear-gradient(135deg,#ffb300,#ff7700);color:#000;font-weight:700;border:none;border-radius:8px;" onclick="submitChangePass()">Update Password</button>
            <button class="btn flex-fill" style="background:rgba(255,255,255,.08);color:#aaa;border:1px solid rgba(255,255,255,.1);border-radius:8px;" onclick="closeUModals()">Cancel</button>
        </div>
    </div>
</div>

<div id="modal-permissions" style="display:none;position:fixed;inset:0;z-index:9001;align-items:center;justify-content:center;">
    <div style="background:#0b0c10;border:1px solid rgba(155,77,255,.5);border-radius:16px;padding:28px;width:520px;max-width:95%;max-height:85vh;overflow-y:auto;">
        <h5 class="mb-1 fw-bold" style="color:#9b4dff"><i class="fa fa-shield-halved me-2"></i>Manage Permissions</h5>
        <p class="text-muted small mb-3" id="perm_username"></p>
        <input type="hidden" id="perm_user_id">
        <div id="perm_loading" class="text-center py-4 text-muted"><i class="fa fa-spinner fa-spin me-2"></i>Loading...</div>
        <div id="perm_body" style="display:none;">
        <?php
        require_once __DIR__ . '/../includes/permissions.php';
        $permGroups = [
            'group'    => ['label' => '🗂️ Group Management',  'color' => '#00e5ff'],
            'rdp'      => ['label' => '🖥️ RDP Management',    'color' => '#9b4dff'],
            'vm'       => ['label' => '⚙️ VM Management',     'color' => '#00ff66'],
            'earnings' => ['label' => '💰 Earnings & Reports', 'color' => '#ffb300'],
            'other'    => ['label' => '⚡ Other Access',        'color' => '#ff7700'],
        ];
        $grouped = [];
        foreach (PERM_LABELS as $key => [$cat, $lbl]) $grouped[$cat][] = ['key'=>$key,'label'=>$lbl];
        foreach ($permGroups as $gk => $gMeta): $clr = $gMeta['color']; ?>
        <div class="mb-3" style="background:rgba(255,255,255,.03);border:1px solid rgba(255,255,255,.07);border-radius:10px;padding:14px;">
            <div class="d-flex align-items-center justify-content-between mb-2">
                <div style="font-size:13px;font-weight:700;color:<?= $clr ?>"><?= $gMeta['label'] ?></div>
                <div class="d-flex gap-1">
                    <button type="button" class="btn btn-sm" style="font-size:10px;padding:2px 8px;background:rgba(0,255,102,.1);color:#00ff66;border:1px solid rgba(0,255,102,.25);border-radius:20px;" onclick="togglePermGroup('<?= $gk ?>',true)">All On</button>
                    <button type="button" class="btn btn-sm" style="font-size:10px;padding:2px 8px;background:rgba(255,0,60,.1);color:#ff003c;border:1px solid rgba(255,0,60,.25);border-radius:20px;" onclick="togglePermGroup('<?= $gk ?>',false)">All Off</button>
                </div>
            </div>
            <div class="row g-2">
            <?php foreach ($grouped[$gk] ?? [] as $p): ?>
                <div class="col-6">
                    <label style="display:flex;align-items:center;gap:8px;cursor:pointer;padding:6px 10px;background:rgba(255,255,255,.03);border:1px solid rgba(255,255,255,.06);border-radius:8px;font-size:12px;">
                        <input type="checkbox" class="perm-toggle" data-key="<?= $p['key'] ?>" data-group="<?= $gk ?>" style="width:15px;height:15px;accent-color:<?= $clr ?>;">
                        <span style="color:#ccc;"><?= htmlspecialchars($p['label']) ?></span>
                    </label>
                </div>
            <?php endforeach; ?>
            </div>
        </div>
        <?php endforeach; ?>
        </div>
        <div class="d-flex gap-2 mt-3">
            <button class="btn flex-fill" style="background:linear-gradient(135deg,#9b4dff,#6a00ff);color:#fff;border:none;border-radius:8px;font-weight:600;" onclick="submitPermissions()"><i class="fa fa-save me-2"></i>Save</button>
            <button class="btn flex-fill" style="background:rgba(255,255,255,.08);color:#aaa;border:1px solid rgba(255,255,255,.1);border-radius:8px;" onclick="closeUModals()">Cancel</button>
        </div>
    </div>
</div>

<script>
const UA = {
    async api(action, data) {
        const r = await fetch('pages/api.php?action=' + action, { method:'POST', headers:{'Content-Type':'application/json'}, body:JSON.stringify(data) });
        return r.json();
    },
    notify(msg, ok=true) {
        const el = document.createElement('div');
        el.textContent = msg;
        el.style.cssText = `position:fixed;top:20px;right:20px;z-index:99999;padding:12px 20px;border-radius:10px;font-weight:600;font-size:14px;${ok?'background:rgba(0,255,102,.2);color:#00ff66;border:1px solid rgba(0,255,102,.4)':'background:rgba(255,0,60,.2);color:#ff003c;border:1px solid rgba(255,0,60,.4)'}`;
        document.body.appendChild(el);
        setTimeout(()=>el.remove(), 3000);
    }
};
function openAddUser() { document.getElementById('uOverlay').style.display='block'; document.getElementById('modal-add-user').style.display='flex'; }
function openChangePass(uid, uname) { document.getElementById('cp_user_id').value=uid; document.getElementById('cp_username_label').textContent='User: '+uname; document.getElementById('cp_password').value=''; document.getElementById('uOverlay').style.display='block'; document.getElementById('modal-change-pass').style.display='flex'; }
function closeUModals() { document.getElementById('uOverlay').style.display='none'; ['modal-add-user','modal-change-pass','modal-permissions','modal-update-agent'].forEach(id=>{const el=document.getElementById(id);if(el)el.style.display='none';}); }
async function submitAddUser() {
    const res = await UA.api('user_add',{username:document.getElementById('nu_username').value.trim(),password:document.getElementById('nu_password').value.trim(),email:document.getElementById('nu_email').value.trim(),role:document.getElementById('nu_role').value});
    if(res.success){UA.notify('User created!');setTimeout(()=>location.reload(),800);}else UA.notify(res.error||'Failed',false);
}
async function submitChangePass() {
    const res = await UA.api('user_change_password',{user_id:parseInt(document.getElementById('cp_user_id').value),password:document.getElementById('cp_password').value.trim()});
    if(res.success){UA.notify('Password updated!');closeUModals();}else UA.notify(res.error||'Failed',false);
}
async function toggleUser(uid) { const res=await UA.api('user_toggle',{user_id:uid}); if(res.success)location.reload(); else UA.notify('Failed',false); }
async function deleteUser(uid, uname) {
    if(!confirm('Delete "'+uname+'"? Cannot be undone.'))return;
    const res=await UA.api('user_delete',{user_id:uid});
    if(res.success){document.getElementById('user-row-'+uid)?.remove();UA.notify('Deleted');}else UA.notify(res.error||'Failed',false);
}
async function openPermissions(uid, uname) {
    document.getElementById('perm_user_id').value=uid;
    document.getElementById('perm_username').textContent='User: '+uname;
    document.querySelectorAll('.perm-toggle').forEach(cb=>cb.checked=false);
    document.getElementById('perm_loading').style.display='block';
    document.getElementById('perm_body').style.display='none';
    document.getElementById('uOverlay').style.display='block';
    document.getElementById('modal-permissions').style.display='flex';
    const res=await UA.api('user_get_permissions',{user_id:uid});
    document.getElementById('perm_loading').style.display='none';
    document.getElementById('perm_body').style.display='block';
    if(res.success){const p=res.permissions||{};document.querySelectorAll('.perm-toggle').forEach(cb=>cb.checked=!!p[cb.dataset.key]);}
}
async function submitPermissions() {
    const uid=parseInt(document.getElementById('perm_user_id').value);
    const p={};document.querySelectorAll('.perm-toggle').forEach(cb=>p[cb.dataset.key]=cb.checked);
    const res=await UA.api('user_save_permissions',{user_id:uid,permissions:p});
    if(res.success){UA.notify('Saved!');closeUModals();}else UA.notify(res.error||'Failed',false);
}
function togglePermGroup(gk, state) { document.querySelectorAll('.perm-toggle[data-group="'+gk+'"]').forEach(cb=>cb.checked=state); }

function eraseAdminData(uid, uname) {
    document.getElementById('erase_user_id').value = uid;
    document.getElementById('erase_username_label').textContent = uname;
    document.getElementById('erase_confirm_input').value = '';
    document.getElementById('erase_btn').disabled = true;
    document.getElementById('uOverlay').style.display = 'block';
    document.getElementById('modal-erase-data').style.display = 'flex';
}
function eraseConfirmCheck() {
    const val = document.getElementById('erase_confirm_input').value.trim();
    document.getElementById('erase_btn').disabled = (val !== 'ERASE');
}
async function submitEraseData() {
    const uid = parseInt(document.getElementById('erase_user_id').value);
    const btn = document.getElementById('erase_btn');
    btn.disabled = true;
    btn.innerHTML = '<i class="fa fa-spinner fa-spin me-2"></i>Erasing...';
    const res = await UA.api('erase_admin_data', {user_id: uid});
    if (res.success) {
        UA.notify('All data erased. Admin is now fresh.');
        closeUModals();
        setTimeout(() => location.reload(), 1000);
    } else {
        UA.notify(res.error || 'Erase failed', false);
        btn.disabled = false;
        btn.innerHTML = '<i class="fa fa-fire me-2"></i>Erase Everything';
    }
}
</script>

<div id="modal-erase-data" style="display:none;position:fixed;inset:0;z-index:9001;align-items:center;justify-content:center;">
    <div style="background:#0b0c10;border:2px solid rgba(255,50,0,.6);border-radius:16px;padding:28px;width:420px;max-width:95%;">
        <div style="text-align:center;margin-bottom:16px;">
            <div style="width:56px;height:56px;background:rgba(255,50,0,.15);border-radius:50%;display:flex;align-items:center;justify-content:center;margin:0 auto 12px;border:2px solid rgba(255,85,0,.4);">
                <i class="fa fa-fire" style="color:#ff5500;font-size:24px;"></i>
            </div>
            <h5 class="fw-bold mb-1" style="color:#ff5500;">Erase Admin Data</h5>
            <p class="text-muted small mb-0">This will permanently delete ALL data for:</p>
            <p class="fw-bold mb-0" style="color:#fff;font-size:16px;" id="erase_username_label"></p>
        </div>
        <input type="hidden" id="erase_user_id">
        <div style="background:rgba(255,50,0,.08);border:1px solid rgba(255,85,0,.3);border-radius:10px;padding:14px;margin-bottom:18px;font-size:12px;color:#ffaa88;line-height:1.8;">
            <b style="color:#ff5500;">The following will be deleted:</b><br>
            🗂️ All Groups belonging to this admin<br>
            🖥️ All RDPs under those groups<br>
            ⚙️ All VMs and their data<br>
            📋 All VM Commands history<br>
            💰 All EarnApp earning history<br>
            <br>
            <b style="color:#ff3300;">The admin account itself will NOT be deleted.</b>
        </div>
        <div class="mb-3">
            <label class="small mb-1" style="color:#ffaa88;">Type <b style="color:#ff5500;">ERASE</b> to confirm:</label>
            <input id="erase_confirm_input" class="form-control" style="background:#050507;border:1px solid rgba(255,85,0,.4);color:#fff;letter-spacing:2px;font-weight:700;" placeholder="ERASE" oninput="eraseConfirmCheck()">
        </div>
        <div class="d-flex gap-2">
            <button id="erase_btn" class="btn flex-fill" disabled style="background:linear-gradient(135deg,#ff5500,#ff0000);color:#fff;border:none;border-radius:8px;font-weight:700;" onclick="submitEraseData()">
                <i class="fa fa-fire me-2"></i>Erase Everything
            </button>
            <button class="btn flex-fill" style="background:rgba(255,255,255,.08);color:#aaa;border:1px solid rgba(255,255,255,.1);border-radius:8px;" onclick="closeUModals()">Cancel</button>
        </div>
    </div>
</div>


<!-- Permissions Modal -->
<div id="modal-permissions" style="display:none;position:fixed;inset:0;z-index:9001;align-items:center;justify-content:center;">
    <div style="background:#0b0c10;border:1px solid rgba(155,77,255,.5);border-radius:16px;padding:28px;width:520px;max-width:95%;max-height:85vh;overflow-y:auto;">
        <h5 class="mb-1 fw-bold" style="color:#9b4dff"><i class="fa fa-shield-halved me-2"></i>Manage Permissions</h5>
        <p class="text-muted small mb-3" id="perm_username"></p>
        <input type="hidden" id="perm_user_id">

        <div id="perm_loading" class="text-center py-4 text-muted">
            <i class="fa fa-spinner fa-spin me-2"></i>Loading permissions...
        </div>
        <div id="perm_body" style="display:none;">

        <?php
        require_once __DIR__ . '/../includes/permissions.php';
        $groups = [
            'group'   => ['label' => '🗂️ Group Management',   'color' => '#00e5ff'],
            'rdp'     => ['label' => '🖥️ RDP Management',     'color' => '#9b4dff'],
            'vm'      => ['label' => '⚙️ VM Management',      'color' => '#00ff66'],
            'earnings'=> ['label' => '💰 Earnings & Reports',  'color' => '#ffb300'],
            'other'   => ['label' => '⚡ Other Access',         'color' => '#ff7700'],
        ];
        // Group perms by category
        $grouped = [];
        foreach (PERM_LABELS as $key => [$cat, $lbl]) {
            $grouped[$cat][] = ['key' => $key, 'label' => $lbl];
        }
        foreach ($groups as $gk => $gMeta):
            $color = $gMeta['color'];
        ?>
        <div class="mb-3" style="background:rgba(255,255,255,.03);border:1px solid rgba(255,255,255,.07);border-radius:10px;padding:14px;">
            <div class="d-flex align-items-center justify-content-between mb-2">
                <div style="font-size:13px;font-weight:700;color:<?= $color ?>;"><?= $gMeta['label'] ?></div>
                <div class="d-flex gap-1">
                    <button type="button" class="btn btn-sm" style="font-size:10px;padding:2px 8px;background:rgba(0,255,102,.1);color:#00ff66;border:1px solid rgba(0,255,102,.25);border-radius:20px;" onclick="togglePermGroup('<?= $gk ?>',true)">All On</button>
                    <button type="button" class="btn btn-sm" style="font-size:10px;padding:2px 8px;background:rgba(255,0,60,.1);color:#ff003c;border:1px solid rgba(255,0,60,.25);border-radius:20px;" onclick="togglePermGroup('<?= $gk ?>',false)">All Off</button>
                </div>
            </div>
            <div class="row g-2">
            <?php foreach ($grouped[$gk] ?? [] as $perm): ?>
                <div class="col-6">
                    <label style="display:flex;align-items:center;gap:8px;cursor:pointer;padding:6px 10px;background:rgba(255,255,255,.03);border:1px solid rgba(255,255,255,.06);border-radius:8px;font-size:12px;">
                        <input type="checkbox" class="perm-toggle" data-key="<?= $perm['key'] ?>" data-group="<?= $gk ?>" style="width:15px;height:15px;accent-color:<?= $color ?>;">
                        <span style="color:#ccc;"><?= htmlspecialchars($perm['label']) ?></span>
                    </label>
                </div>
            <?php endforeach; ?>
            </div>
        </div>
        <?php endforeach; ?>

        </div><!-- /perm_body -->

        <div class="d-flex gap-2 mt-3">
            <button class="btn flex-fill" style="background:linear-gradient(135deg,#9b4dff,#6a00ff);color:#fff;border:none;border-radius:8px;font-weight:600;" onclick="submitPermissions()">
                <i class="fa fa-save me-2"></i>Save Permissions
            </button>
            <button class="btn flex-fill" style="background:rgba(255,255,255,.08);color:#aaa;border:1px solid rgba(255,255,255,.1);border-radius:8px;" onclick="closeUModals()">Cancel</button>
        </div>
    </div>
</div>

<div id="modal-update-agent" style="display:none;position:fixed;inset:0;z-index:9001;align-items:center;justify-content:center;">
    <div style="background:#0b0c10;border:1px solid rgba(0,180,255,.5);border-radius:16px;padding:28px;width:700px;max-width:95%;max-height:90vh;display:flex;flex-direction:column;">
        <div class="d-flex align-items-center justify-content-between mb-3">
            <div>
                <h5 class="mb-0 fw-bold" style="color:#00b4ff"><i class="fa fa-robot me-2"></i>Update Agent.ps1</h5>
                <p class="text-muted small mb-0" id="ua_username_label"></p>
            </div>
            <span id="ua_status_badge" style="display:none;font-size:11px;padding:3px 10px;border-radius:20px;font-weight:700;"></span>
        </div>
        <input type="hidden" id="ua_user_id">
        <div id="ua_loading" class="text-center py-4 text-muted"><i class="fa fa-spinner fa-spin me-2"></i>Loading current agent...</div>
        <textarea id="ua_content" style="display:none;flex:1;min-height:380px;background:#050507;border:1px solid rgba(0,180,255,.3);color:#00e5ff;font-family:monospace;font-size:12px;border-radius:10px;padding:14px;resize:vertical;outline:none;"></textarea>
        <div class="d-flex gap-2 mt-3">
            <button id="ua_save_btn" class="btn flex-fill" style="display:none;background:linear-gradient(135deg,#00b4ff,#0066ff);color:#fff;border:none;border-radius:8px;font-weight:700;" onclick="submitUpdateAgent()">
                <i class="fa fa-robot me-2"></i>Push Update to All Agents
            </button>
            <button class="btn flex-fill" style="background:rgba(255,255,255,.08);color:#aaa;border:1px solid rgba(255,255,255,.1);border-radius:8px;" onclick="closeUModals()">Cancel</button>
        </div>
    </div>
</div>

<script>
async function openUpdateAgent(uid, uname) {
    document.getElementById('ua_user_id').value = uid;
    document.getElementById('ua_username_label').textContent = 'Admin: ' + uname;
    document.getElementById('ua_loading').style.display = 'block';
    document.getElementById('ua_content').style.display = 'none';
    document.getElementById('ua_save_btn').style.display = 'none';
    document.getElementById('ua_status_badge').style.display = 'none';
    document.getElementById('uOverlay').style.display = 'block';
    document.getElementById('modal-update-agent').style.display = 'flex';

    const res = await UA.api('get_agent_ps1', { user_id: uid });
    document.getElementById('ua_loading').style.display = 'none';
    if (res.success) {
        document.getElementById('ua_content').value = res.content;
        document.getElementById('ua_content').style.display = 'block';
        document.getElementById('ua_save_btn').style.display = 'block';
        const badge = document.getElementById('ua_status_badge');
        badge.style.display = 'inline-block';
        badge.textContent = 'v' + (res.version || '?');
        badge.style.cssText += ';background:rgba(0,180,255,.15);color:#00b4ff;border:1px solid rgba(0,180,255,.4);';
    } else {
        UA.notify(res.error || 'Failed to load agent', false);
        closeUModals();
    }
}

async function submitUpdateAgent() {
    const uid = parseInt(document.getElementById('ua_user_id').value);
    const content = document.getElementById('ua_content').value;
    const btn = document.getElementById('ua_save_btn');
    btn.disabled = true;
    btn.innerHTML = '<i class="fa fa-spinner fa-spin me-2"></i>Pushing...';
    const res = await UA.api('update_agent_ps1', { user_id: uid, content: content });
    if (res.success) {
        UA.notify('Agent.ps1 updated! All agents will auto-update on next check.');
        closeUModals();
    } else {
        UA.notify(res.error || 'Update failed', false);
        btn.disabled = false;
        btn.innerHTML = '<i class="fa fa-robot me-2"></i>Push Update to All Agents';
    }
}
</script>