<?php
require_once __DIR__ . '/../db.php';

date_default_timezone_set('Asia/Kolkata');



$res = $conn->query("SELECT COUNT(*) AS c FROM vms");
$stats['total_vms'] = (int)$res->fetch_assoc()['c'];

$app_running = 0;
$app_paused  = 0;
$app_blocked = 0;

$res = $conn->query("
    SELECT LOWER(status) AS status, COUNT(*) AS c
    FROM vms
    GROUP BY LOWER(status)
");

if ($res) {
    while ($r = $res->fetch_assoc()) {
        if ($r['status'] === 'running')  $app_running = (int)$r['c'];
        if ($r['status'] === 'paused')   $app_paused  = (int)$r['c'];
        if ($r['status'] === 'blocked')  $app_blocked = (int)$r['c'];
    }
}


$res = $conn->query("
    SELECT COUNT(*) AS c
    FROM vms
    WHERE last_heartbeat IS NOT NULL
      AND last_heartbeat >= NOW() - INTERVAL 5 MINUTE
");
$stats['online_vms'] = (int)$res->fetch_assoc()['c'];

$res = $conn->query("
    SELECT COUNT(*) AS c
    FROM vms
    WHERE last_heartbeat IS NULL
       OR last_heartbeat < NOW() - INTERVAL 5 MINUTE
");
$stats['offline_vms'] = (int)$res->fetch_assoc()['c'];


$today_res = $conn->query("
    SELECT IFNULL(SUM(earning), 0) AS total 
    FROM vm_earnings 
    WHERE date = CURDATE()
");
$stats['earning_today'] = (float)$today_res->fetch_assoc()['total'];

 
$month_res = $conn->query("
    SELECT IFNULL(SUM(earning), 0) AS total 
    FROM vm_earnings
    WHERE YEAR(date) = YEAR(CURDATE())
      AND MONTH(date) = MONTH(CURDATE())
");
$stats['earning_month'] = (float)$month_res->fetch_assoc()['total'];
 


$tree = [];
$data_res = $conn->query("
    SELECT 
        g.id AS g_id,
        g.name AS g_name,
        r.id AS r_id,
        r.name AS r_name,
        v.id AS v_id,
        v.unit_id,
        v.current_ip,
        v.last_heartbeat, 
        v.status,
        IF(v.last_heartbeat >= NOW() - INTERVAL 5 MINUTE, 1, 0) AS is_online,
        COALESCE(v.balance, 0) AS balance,
        v.traffic,
        v.earnapp_token
    FROM groups g
    LEFT JOIN rdps r ON g.id = r.group_id
    LEFT JOIN vms v ON r.id = v.rdp_id
    ORDER BY g.name ASC, r.name ASC, v.unit_id ASC
");

if ($data_res) {
    while($row = $data_res->fetch_assoc()){
        $gid = $row['g_id']; 
        $rid = $row['r_id'];
        
        if(!$gid) continue;
        
        if(!isset($tree[$gid])) {
            $tree[$gid] = ['id'=>$gid, 'name'=>$row['g_name'], 'rdps'=>[]];
        }
        
        if($rid) {
            if(!isset($tree[$gid]['rdps'][$rid])) {
                $tree[$gid]['rdps'][$rid] = ['id'=>$rid, 'name'=>$row['r_name'], 'vms'=>[]];
            }
            
            if($row['v_id'] !== null){
                $tree[$gid]['rdps'][$rid]['vms'][] = $row;
            }
        }
    }
}

$jsGroupData = [];
foreach($tree as $g) {
    $rdps = [];
    if(isset($g['rdps'])){
        foreach($g['rdps'] as $r) {
            $rdps[] = ['id' => $r['id'], 'name' => $r['name']];
        }
    }
    $jsGroupData[] = ['id' => $g['id'], 'name' => $g['name'], 'rdps' => $rdps];
}


$total_lifetime_res = $conn->query("SELECT IFNULL(SUM(balance),0) AS total FROM vms");
$total_lifetime = (float)($total_lifetime_res->fetch_assoc()['total'] ?? 0);
?>
<style>.ea-token-text {
    word-break: break-all;
    overflow-wrap: anywhere;
    white-space: normal;
}
</style>

<script>
    window.groupData = <?php echo json_encode($jsGroupData); ?>;
</script>

<div class="container-fluid px-4 py-3">
<div class="row mb-4 row-cols-8 g-2">

  <div class="col">
    <div class="card bg-dark text-white p-3 border-danger text-center">
      <h6>Total VMs</h6>
      <h3><?= $stats['total_vms'] ?></h3>
    </div>
  </div>

  <div class="col">
    <div class="card bg-dark text-white p-3 border-success text-center">
      <h6>Online</h6>
      <h3><?= $stats['online_vms'] ?></h3>
    </div>
  </div>

  <div class="col">
    <div class="card bg-dark text-white p-3 border-success text-center">
      <h6>App Running</h6>
      <h3><?= $app_running ?></h3>
    </div>
  </div>

  <div class="col">
    <div class="card bg-dark text-white p-3 border-warning text-center">
      <h6>App Paused</h6>
      <h3><?= $app_paused ?></h3>
    </div>
  </div>

  <div class="col">
    <div class="card bg-dark text-white p-3 border-danger text-center">
      <h6>IP Blocked</h6>
      <h3><?= $app_blocked ?></h3>
    </div>
  </div>

  <div class="col">
    <div class="card bg-dark text-white p-3 border-warning text-center">
      <h6>Today</h6>
      <h3>$<?= number_format($stats['earning_today'], 2) ?></h3>
    </div>
  </div>

  <div class="col">
    <div class="card bg-dark text-white p-3 border-info text-center">
      <h6>This Month</h6>
      <h3>$<?= number_format($stats['earning_month'], 2) ?></h3>
    </div>
  </div>

  <div class="col">
    <div class="card bg-dark text-white p-3 border-info text-center">
      <h6>Current Balance</h6>
      <h3>$<?= number_format($total_lifetime, 2) ?></h3>
    </div>
  </div>

</div> 
<div class="row mb-3">
        <div class="col-md-6">
            <input id="searchInput" class="form-control bg-dark text-white border-secondary" placeholder="Search..." onkeyup="app.search()">
        </div>
        <div class="col-md-6 text-end">
            <button class="ea-ibtn1" title="Restart All VMs" onclick="app.restartAllVms()">
              <i class="fa fa-power-off"></i>
            </button>
        
          <button class="ea-ibtn1" title="Fetch Balance All" onclick="app.fetchAllBalances()">
              <i class="fa fa-dollar-sign"></i>
            </button>
            <button class="ea-ibtn1" title="Add Group" onclick="app.openModal('group')">
                <i class="fa fa-folder"></i>
              </button>
          <button class="ea-ibtn1" onclick="app.openModal('rdp')" title="Add RDP">
            <i class="fa fa-server"></i>
          </button>
          <button class="ea-ibtn1" onclick="app.openModal('vm')" title="Add VM">
            <i class="fa fa-desktop"></i>
          </button>
        </div>
    </div>
     <div class="row">
              <div class="col-md-3 nav-col">
              
            
                <div class="card bg-dark text-white border-secondary nav-full">
                  <div class="card-header nav-header">
                      <span>Navigator</span>
                      <i class="fa fa-chevron-left nav-toggle-icon" onclick="toggleNavigator()"></i>
                    </div>
                  <div class="list-group list-group-flush small nav-tree">

                    <?php foreach ($tree as $g): ?>
                      <div class="nav-group">
                    
                        <div class="nav-group-title" onclick="toggleGroup(this)">
                          <?= $g['name'] ?>
                          
                        </div>
                    
                        <div class="nav-group-body">
                          <?php foreach ($g['rdps'] as $r): ?>
                            <div class="nav-rdp">
                    
                              <div class="nav-rdp-title" onclick="toggleRdp(this)">
                                RDP: <?= $r['name'] ?>
                              </div>
                    
                              <div class="nav-rdp-body">
                                  <?php foreach ($r['vms'] as $v): ?>
                                    <a href="#vm-card-<?= $v['v_id'] ?>" class="nav-vm">
                                      <?= htmlspecialchars($v['unit_id']) ?>
                                    </a>
                                  <?php endforeach; ?>
                                </div>
                    
                            </div>
                          <?php endforeach; ?>
                        </div>
                    
                      </div>
                    <?php endforeach; ?>
                    
                    </div>

            </div>
        </div>

        <div class="col-md-9 main-col">
            
             <div id="mainContent">

<?php foreach ($tree as $g): ?>

<?php
$groupVmTotal = 0;
$groupVmOffline = 0;
$groupVmPending = 0;

foreach ($g['rdps'] as $r) {
    foreach ($r['vms'] as $v) {
        $groupVmTotal++;
        if (empty($v['last_heartbeat'])) {
            $groupVmPending++;
        } elseif ((int)$v['is_online'] === 0) {
            $groupVmOffline++;
        }
    }
}
?>

<div class="group-box mb-4 p-3 border border-secondary rounded bg-dark shadow searchable-item"
     data-name="<?= $g['name'] ?>" id="g-<?= $g['id'] ?>">
    
    <?php $groupCount = 1;
$rdpCount = count($g['rdps']);
$vmCount = 0;

foreach ($g['rdps'] as $r) {
    $vmCount += count($r['vms']);
}?>

  <div class="grp-header grp-toggle" onclick="toggleMainGroup(this)">
      <div class="grp-left" onclick="toggleMainGroup(this.parentNode)">
       
        <span class="grp-name"><?= $g['name'] ?></span>
      </div>
    
     <div class="grp-icons">
          <span class="dot green"><?= $groupCount ?></span>
          <span class="dot red"><?= $rdpCount ?></span>
          <span class="dot yellow"><?= $vmCount ?></span>
        
          <button class="grp-ibtn" title="Add RDP"
                  onclick="event.stopPropagation();app.openRdpFromGroup(<?= $g['id'] ?>)">
            <i class="fa fa-server"></i>
          </button>
        
          <button class="grp-ibtn" title="Add VM"
                  onclick="event.stopPropagation();app.openVmFromGroup(<?= $g['id'] ?>)">
            <i class="fa fa-desktop"></i>
          </button>
        
          <button class="grp-ibtn danger"
                    onclick="event.stopPropagation();app.deleteGroup(<?= $g['id'] ?>)">
              <i class="fa fa-trash"></i>
            </button>
        </div>

    </div>


  <div class="grp-body" style="display:none">
    <?php foreach ($g['rdps'] as $r): ?>
    <div class="rdp-box ms-3 mt-3 searchable-item" data-name="<?= $r['name'] ?>">
 

      <div class="row">

<?php foreach ($r['vms'] as $v): ?>

<?php 
$statusRaw = strtolower(trim($v['status'] ?? 'unknown'));

$statusColor = 'ok';
if ($statusRaw === 'blocked') {
    $statusColor = 'bad';
} elseif ($statusRaw === 'paused') {
    $statusColor = 'warn';
} elseif ($statusRaw === 'offline') {
    $statusColor = 'bad';
}
?>

 

<?php

$dbStatus = strtolower(trim($v['status'] ?? ''));

$isVmOnline = ((int)$v['is_online'] === 1);

if ($isVmOnline) {
    $statusText  = 'ONLINE';
    $statusSub   = 'VM ALIVE';
    $statusClass = 'on';
} else {
    $statusText  = 'OFFLINE';
    $statusSub   = 'VM OFFLINE';
    $statusClass = 'off';
} 

$isOnline = $isVmOnline;
 
 

/* OTHER */
$balanceTxt = '$' . number_format((float)$v['balance'], 2);

$earnappLink = !empty($v['earnapp_token'])
    ? 'https://earnapp.com/dashboard/link/sdk-win-' . $v['earnapp_token']
    : null;

$lastSeenTxt = !empty($v['last_heartbeat'])
    ? date('j/n/Y, g:i:s A', strtotime($v['last_heartbeat']))
    : 'Never';

?>



<div class="col-12 searchable-item"
     data-name="<?= $v['unit_id'] ?>"
     id="vm-card-<?= $v['v_id'] ?>">
    
    
  <div class="ea-card">

    <div class="ea-left">
      <div class="ea-status <?= $statusClass ?>">
        <?= $statusText ?>
        <?php if(!$isOnline): ?><small><?= $statusSub ?></small><?php endif; ?>
    </div>
    
    <?php
$hbTxt = 'No heartbeat';

if (!empty($v['last_heartbeat'])) {
    $hbTs = strtotime($v['last_heartbeat']);
    $now  = strtotime(gmdate('Y-m-d H:i:s'));
    $diff = abs($now - $hbTs);

    if ($diff < 60) {
        $hbTxt = $diff . ' sec ago';
    } elseif ($diff < 3600) {
        $hbTxt = floor($diff / 60) . ' min ago';
    } elseif ($diff < 86400) {
        $hbTxt = floor($diff / 3600) . ' hours ago';
    } else {
        $hbTxt = floor($diff / 86400) . ' days ago';
    }
}
?>

<div class="ea-left-meta">
    <div class="ea-vm"><?= $v['unit_id'] ?></div>

    <div class="ea-ip">
        <i class="fas fa-wifi"></i> <?= $v['current_ip'] ?: 'No IP' ?>
    </div>

    <div class="ea-hb" style="margin-top:4px;font-size:12px;color:#aaa">
        <i class="fas fa-heartbeat" style="color: var(--primary-color);"></i>
       <?= !empty($v['last_heartbeat'])
    ? date('H:i:s', strtotime($v['last_heartbeat']))
    : 'No heartbeat' ?>

    </div>
</div>


    </div>

    <div class="ea-center">
      <div class="ea-token-box" style="display:none">
          <?php if($earnappLink): ?>
            <span class="ea-token-text"
                  onclick="app.copyText('<?= $earnappLink ?>')">
              <a href="<?= $earnappLink ?>" target="_blank"><?= $earnappLink ?></a>
            </span>
            
          <?php else: ?>
            No token yet
          <?php endif; ?>
        </div>

      <div class="ea-flags">
    <span>Status:
        <?php if (!$isVmOnline): ?>
            <b style="color:#dc3545;font-weight:bold;">OFFLINE</b>
        <?php else: ?>
            <b class="<?= $statusColor ?>">
                <?= strtoupper($statusRaw) ?>
            </b>
        <?php endif; ?>
    </span>
</div>

      <div class="ea-sync">Sync: <?= $lastSeenTxt ?></div>
      <div class="ea-balance">Balance: <b><?= $balanceTxt ?></b></div>
    </div>

     <div class="ea-right ea-icon-strip">
          <button class="ea-btn" title="Add VM" onclick="app.openModal('vm')">
            <i class="fa fa-plus"></i>
          </button>
        
          <button class="ea-btn" title="Token" onclick="toggleToken(this)">
            <i class="fa fa-key"></i>
          </button>
        
          <button class="ea-btn" title="Restart" onclick="app.restartVm(<?= $v['v_id'] ?>)">
            <i class="fa fa-power-off"></i>
          </button>
        
          <button id="fetch-btn-<?= $v['v_id'] ?>" class="ea-btn"
                  title="Fetch Balance"
                  onclick="app.fetchBalance(<?= $v['v_id'] ?>)">
            <i class="fa fa-dollar-sign"></i>
          </button>
        
          <button class="ea-btn" title="Terminal"
            onclick="app.openTerminal(<?= htmlspecialchars(json_encode($v)) ?>,'<?= $r['name'] ?>','<?= $g['name'] ?>')">
            <i class="fa fa-terminal"></i>
          </button>
          <button class="ea-btn danger" onclick="app.deleteVm(<?= $v['v_id'] ?>)"><i class="fa fa-trash"></i> </button>
        </div>



  </div>
</div>

<?php endforeach; ?>

</div>
      </div>
    </div>
  <?php endforeach; ?>

</div>

<?php endforeach; ?>

</div>  
            </div>
        </div>
    </div>
</div>
<div id="overlay" onclick="app.closeModal()"></div>
<?php include __DIR__.'/../modals/group.php'; ?>
<?php include __DIR__.'/../modals/rdp.php'; ?>
<?php include __DIR__.'/../modals/vm.php'; ?>

<div id="terminalModal" class="modal">
  <div class="modal-content bg-dark text-white border-danger" style="max-width:800px; width:95%">
    <div class="modal-header border-secondary">
      <h5 class="modal-title"><i class="fa fa-terminal me-2"></i> <span id="termTitle">Terminal</span></h5>
      <button class="btn-close btn-close-white" onclick="app.closeModal()"></button>
    </div>
    <div class="modal-body">
      <div class="mb-3 small p-2 bg-black border border-secondary rounded d-flex justify-content-around">
          <span>VM ID: <b id="termVmId"></b></span>
          <span>Group: <b id="termGroup"></b></span>
          <span>RDP: <b id="termRdp"></b></span>
      </div>
      
      <div class="mb-3">
        <label class="small text-muted">Install Command (PowerShell)</label>
        <div class="input-group">
          <input id="installCmd" class="form-control bg-black text-success small" readonly>
          <button class="btn btn-danger btn-sm" onclick="app.copy('installCmd')">Copy</button>
        </div>
      </div>

      <div class="mb-3">
        <label class="small text-muted">Uninstall Command</label>
        <div class="input-group">
          <input id="uninstallCmdInput" class="form-control bg-black text-white" readonly>
          <button class="btn btn-danger btn-sm" onclick="app.copy('uninstallCmdInput')">Copy</button>
        </div>
      </div>

    </div>
  </div>
</div>



<script>
window.app = {
    async api(action, data = {}) {
        try {
            console.log('API Call:', action, data);
            
            const r = await fetch('pages/api.php?action=' + action, {
                method: 'POST',
                headers: {'Content-Type': 'application/json'},
                body: JSON.stringify(data)
            });
            
            const text = await r.text();
            console.log('Raw API Response:', text);
            
            try {
                return JSON.parse(text);
            } catch (e) {
                console.error('JSON Parse Error:', e, 'Response was:', text);
                return {success: false, error: 'Invalid JSON response'};
            }
        } catch (e) {
            console.error('Network Error:', e);
            return {success: false, error: 'Network error'};
        }
    },

    copyText(text) {
        const ta = document.createElement('textarea');
        ta.value = text;
        ta.style.position = 'fixed';
        ta.style.opacity = '0';
        document.body.appendChild(ta);
        ta.focus();
        ta.select();
        document.execCommand('copy');
        document.body.removeChild(ta);
    },

    search() {
        const term = document.getElementById('searchInput').value.toLowerCase().trim();
    
        document.querySelectorAll('.group-box').forEach(group => {
            let groupMatch = false;
    
            group.querySelectorAll('.searchable-item[id^="vm-card"]').forEach(vm => {
                const name = (vm.getAttribute('data-name') || '').toLowerCase();
    
                if (!term || name.includes(term)) {
                    vm.style.display = '';
                    groupMatch = true;
    
                    const body = group.querySelector('.grp-body');
                    if (body) body.style.display = 'block';
                } else {
                    vm.style.display = 'none';
                }
            });
    
            group.style.display = groupMatch || !term ? '' : 'none';
        });
    },

    openModal(type) {
        document.getElementById('overlay').style.display = 'block';
        const modal = document.getElementById(type === 'terminal' ? 'terminalModal' : 'modal-' + type);
        if (modal) modal.style.display = 'flex';
    },

    closeModal() {
        document.getElementById('overlay').style.display = 'none';
        document.querySelectorAll('.modal').forEach(m => m.style.display = 'none');
        
        const vmInput = document.getElementById('vmInput');
        if (vmInput) vmInput.value = '';
        const rdpInput = document.getElementById('rdpInput');
        if (rdpInput) rdpInput.value = '';
        const groupInput = document.getElementById('groupInput');
        if (groupInput) groupInput.value = '';
    },


    openTerminal(v, rName, gName) {
        const base = window.location.origin + window.location.pathname.split('/index.php')[0];
        document.getElementById('termTitle').innerText = v.unit_id;
        document.getElementById('termVmId').innerText = v.v_id;
        document.getElementById('termGroup').innerText = gName;
        document.getElementById('termRdp').innerText = rName;

        document.getElementById('installCmd').value =
            'irm "' + base + '/static/install.ps1" -OutFile i.ps1; .\\i.ps1 -VMId ' + v.v_id +
            ' -UnitId "' + v.unit_id + '" -Group "' + gName +
            '" -RdpNickname "' + rName + '" -BackendUrl "' + base + '"';

        const uninst = document.getElementById('uninstallCmdInput');
        if(uninst) uninst.value = 'irm "' + base + '/static/uninstall.ps1" | iex';

        this.openModal('terminal');
    },

    copy(id) {
        const el = document.getElementById(id);
        el.select();
        navigator.clipboard.writeText(el.value);
    },

    filterRdpList(groupId) {
        const rdpSelect = document.getElementById('vmRdpSelect');
        rdpSelect.innerHTML = '<option value="">-- Select RDP --</option>';
    
        if (!groupId) return;
    
        const group = window.groupData.find(g => g.id == groupId);
        if (!group || !group.rdps || !group.rdps.length) return;
    
        group.rdps.forEach((rdp, index) => {
            const opt = document.createElement('option');
            opt.value = rdp.id;
            opt.textContent = rdp.name;
            rdpSelect.appendChild(opt);
    
            if (index === 0) {
                rdpSelect.value = rdp.id;
            }
        });
    },

    async addVM() {
        const rdpId = document.getElementById('vmRdpSelect').value;
        const unitId = document.getElementById('vmInput').value.trim();
    
        console.log('addVM called - rdpId:', rdpId, 'unitId:', unitId);
    
        if (!rdpId || rdpId === '' || !unitId || unitId === '') {
            alert('Please fill all fields');
            return;
        }
    
        const btn = document.querySelector('#modal-vm .btn-danger');
        if (btn) {
            if (btn.dataset.submitting === 'true') return;
            btn.dataset.submitting = 'true';
            btn.disabled = true;
        }
    
        const res = await this.api('add_vm', {
            rdp_id: rdpId,
            unit_id: unitId
        });
    
        if (btn) {
            btn.dataset.submitting = 'false';
            btn.disabled = false;
        }
    
        if (res && res.success) {
            location.reload();
        } else {
            alert('Failed: ' + (res?.error || 'Unknown error'));
        }
    },
    
    async restartAllVms(){
        if(!confirm('Restart all VMs?')) return;
    
        const res = await this.api('send_global_command', {
            command: 'restart_vm'
        });
    
        if(res && res.success) alert('Restart command sent to all VMs');
        else alert('Failed');
    },

    async fetchAllBalances(){
        if(!confirm('Fetch balance for all VMs?')) return;
    
        const res = await this.api('send_global_command', {
            command: 'fetch_balance'
        });
    
        if(res && res.success) alert('Balance fetch sent to all VMs');
        else alert('Failed');
    },


    async restartVm(vmId) {
        if (!confirm('Restart this VM?')) return;
        const res = await this.api('send_command', {
            vm_id: parseInt(vmId),
            command: 'restart_vm'
        });
        if (res && res.success) alert('Command sent');
        else alert('Failed');
    },

    async fetchBalance(vmId) {
        const btn = document.getElementById('fetch-btn-' + vmId);
        if (btn) btn.disabled = true;
    
        const res = await this.api('send_command', {
            vm_id: parseInt(vmId),
            command: 'fetch_balance'
        });
    
        if (res && res.success) alert('Request sent');
        else alert('Failed');
    
        setTimeout(() => { if (btn) btn.disabled = false; }, 3000);
    },
    
    async deleteGroup(groupId){
        if(!confirm('Delete this group permanently?')) return;
    
        const res = await this.api('delete_groups', {
            ids: [parseInt(groupId)]
        });
    
        if(res && res.success){
            location.reload();
        }else{
            alert('Delete failed');
        }
    },
    async deleteVm(vmId){
        if(!confirm('Delete this VM permanently?')) return;
    
        const res = await this.api('delete_vms', {
            ids: [parseInt(vmId)]
        });
    
        if(res && res.success){
            location.reload();
        }else{
            alert('Delete failed');
        }
    },

    openRdpFromGroup(groupId){
    document.getElementById('overlay').style.display = 'block';
    const modal = document.getElementById('modal-rdp');
    if(modal){
        modal.style.display = 'flex';
        const sel = document.getElementById('rdpGroupSelect');
        if(sel) sel.value = groupId;
    }
},

openVmFromGroup(groupId){
    const vmInput = document.getElementById('vmInput');
    if (vmInput) vmInput.value = '';

    const vmRdpSelect = document.getElementById('vmRdpSelect');
    if (vmRdpSelect) vmRdpSelect.innerHTML = '<option value="">-- Select RDP --</option>';

    const grpSel = document.getElementById('vmGroupSelect');
    if(grpSel){
        grpSel.value = String(groupId);
        console.log('Group set to:', grpSel.value);
    }

    if(typeof app.filterRdpList === 'function'){
        app.filterRdpList(groupId);
    }

    document.getElementById('overlay').style.display = 'block';
    const modal = document.getElementById('modal-vm');
    if(modal) modal.style.display = 'flex';
},


async addRDP(){
    const name = document.getElementById('rdpInput').value;
    const groupId = document.getElementById('rdpGroupSelect').value;

    if(!name || !groupId){
        alert('Fill all fields');
        return;
    }

    const res = await this.api('add_rdp', {
        name,
        group_id: parseInt(groupId)
    });

    if(res && res.success){
        location.reload();
    }else{
        alert('Failed to add RDP');
    }
},

async fetchGroupBalance(groupId){

    if(!confirm('Fetch balance for all VMs?')) return;

    const res = await this.api('send_global_command');

    if(res && res.success){
        alert('Command sent to all VMs');
    }else{
        alert('Failed');
    }
},

async addGroup(){
    const name = document.getElementById('groupInput').value;
    if(!name) return alert('Enter group name');

    const res = await this.api('add_group', { name });

    if(res && res.success){
        location.reload();
    }else{
        alert('Failed to add group');
    }
},
    async bulkDelete(type) {
        const ids = [...document.querySelectorAll('.' + type + '-check:checked')].map(c => c.value);
        if(!ids.length || !confirm('Delete ' + ids.length + ' items?')) return;
        await this.api('delete_' + type + 's', {ids});
        location.reload();
    }
};

window.toggleMainGroup = function(el) {
    const body = el.nextElementSibling;
    if(!body) return;
    body.style.display = (body.style.display === 'block') ? 'none' : 'block';
};

window.toggleGroup = function(el) {
    const body = el.nextElementSibling;
    if(body) body.style.display = (body.style.display === 'block') ? 'none' : 'block';
};

window.toggleRdp = function(el) {
    const body = el.nextElementSibling;
    if(body) body.style.display = (body.style.display === 'block') ? 'none' : 'block';
};

window.toggleToken = function(btn) {
    const box = btn.closest('.ea-card').querySelector('.ea-token-box');
    if(box) box.style.display = (box.style.display === 'none') ? 'block' : 'none';
};


</script>

<script>
function toggleNavigator(){
  document.querySelector('.nav-col').classList.toggle('nav-collapsed');
}
</script>
 
 <script>
let sortDirection = {};

function sortTable(columnIndex) {

    const table = document.getElementById("inventoryTable");
    const tbody = table.querySelector("tbody");
    const rows  = Array.from(tbody.querySelectorAll("tr"));

    sortDirection[columnIndex] = !sortDirection[columnIndex];

    rows.sort((a, b) => {

        let aText = a.children[columnIndex].innerText.trim().toLowerCase();
        let bText = b.children[columnIndex].innerText.trim().toLowerCase();

        let aNum = parseFloat(aText);
        let bNum = parseFloat(bText);

        if (!isNaN(aNum) && !isNaN(bNum)) {
            return sortDirection[columnIndex] 
                ? aNum - bNum 
                : bNum - aNum;
        }

        return sortDirection[columnIndex] 
            ? aText.localeCompare(bText)
            : bText.localeCompare(aText);
    });

    tbody.innerHTML = "";
    rows.forEach(row => tbody.appendChild(row));
}
</script>
