<?php
$host = 'localhost';
$user = 'bdmaco_earnapp';
$pass = '6Q6iQXMs8eEJ';
$name = 'bdmaco_earnapp';

$conn = new mysqli($host, $user, $pass, $name);
if ($conn->connect_error) { die(json_encode(array('success'=>false,'error'=>'DB connection failed'))); }
$conn->set_charset('utf8mb4');
$conn->query("SET time_zone = '+05:30'");

function isSuperAdmin() {
    return isset($_SESSION['role']) && $_SESSION['role'] === 'super_admin';
}
function isAdmin() {
    return isset($_SESSION['role']) && in_array($_SESSION['role'], array('admin','super_admin'));
}
function currentUserId() {
    if (isSuperAdmin() && !empty($_SESSION['view_as_id'])) return (int)$_SESSION['view_as_id'];
    return (int)(isset($_SESSION['user_id']) ? $_SESSION['user_id'] : 0);
}
function isViewingAs() {
    return isSuperAdmin() && !empty($_SESSION['view_as_id']);
}
function getUserGroupIds($db, $userId, $admin) {
    $ids = array();
    if (isSuperAdmin() && !isViewingAs()) {
        $r = $db->query("SELECT id FROM `groups`");
    } elseif (isAdmin()) {
        $uid = (int)$userId;
        $tenantRes = $db->query("SELECT tenant_id FROM users WHERE id=$uid LIMIT 1");
        $tenantRow = $tenantRes ? $tenantRes->fetch_assoc() : null;
        $tid = ($tenantRow && $tenantRow['tenant_id'] !== null) ? (int)$tenantRow['tenant_id'] : $uid;
        $r = $db->query("SELECT id FROM `groups` WHERE tenant_id=$tid");
    } else {
        $uid = (int)$userId;
        $r = $db->query("SELECT group_id AS id FROM user_groups WHERE user_id=$uid");
    }
    if ($r) while ($row = $r->fetch_assoc()) $ids[] = (int)$row['id'];
    return $ids ? $ids : array(0);
}
function getVmData($db) {
    $uid     = currentUserId();
    $gids    = getUserGroupIds($db, $uid, isAdmin());
    $gidList = implode(',', $gids);
    $vmIds   = array(0);
    $tokens  = array("''");
    $unitIds = array("''");
    $r = $db->query("SELECT v.id, v.unit_id, v.earnapp_token FROM vms v JOIN rdps r ON r.id=v.rdp_id WHERE r.group_id IN ($gidList)");
    if ($r) {
        while ($row = $r->fetch_assoc()) {
            $vmIds[] = (int)$row['id'];
            if (!empty($row['earnapp_token'])) $tokens[]  = "'".$db->real_escape_string($row['earnapp_token'])."'";
            if (!empty($row['unit_id']))        $unitIds[] = "'".$db->real_escape_string($row['unit_id'])."'";
        }
    }
    return array(
        'gidList'   => $gidList,
        'vmIdList'  => implode(',', $vmIds),
        'tokenList' => implode(',', $tokens),
        'unitList'  => implode(',', $unitIds),
    );
}