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

date_default_timezone_set('Asia/Kolkata');

/* =======================
   COMMANDS LIST
======================= */
$res = $conn->query("
    SELECT 
        id,
        vm_id,
        `command`,
        `status`,
        created_at
    FROM vm_commands
    ORDER BY id DESC
");
$rows = [];
if ($res) {
    $rows = $res->fetch_all(MYSQLI_ASSOC);
}

/* =======================
   COMMAND STATS
======================= */
$cmd_total = $conn->query("
    SELECT COUNT(*) c FROM vm_commands
")->fetch_assoc()['c'] ?? 0;

$cmd_pending = $conn->query("
    SELECT COUNT(*) c
    FROM vm_commands
    WHERE LOWER(status) LIKE '%pend%'
       OR LOWER(status) LIKE '%queue%'
       OR LOWER(status) LIKE '%run%'
")->fetch_assoc()['c'] ?? 0;

$cmd_done = $conn->query("
    SELECT COUNT(*) c
    FROM vm_commands
    WHERE LOWER(status) LIKE '%done%'
       OR LOWER(status) LIKE '%complete%'
       OR LOWER(status) LIKE '%success%'
")->fetch_assoc()['c'] ?? 0;

$cmd_failed = $conn->query("
    SELECT COUNT(*) c
    FROM vm_commands
    WHERE LOWER(status) LIKE '%fail%'
       OR LOWER(status) LIKE '%error%'
")->fetch_assoc()['c'] ?? 0;

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


/* =======================
   CURRENT BALANCE (VMS)
======================= */
$balance_res = $conn->query("
    SELECT IFNULL(SUM(balance),0) AS total
    FROM vms
");
$current_balance = (float)($balance_res->fetch_assoc()['total'] ?? 0);
?>

<div class="container-fluid px-4 py-3">
<div id="top-stats-wrapper">
    <?php include __DIR__ . '/../parts/vm_top_stats.php'; ?>
</div>

<div class="row mb-4">
    <div class="col-md-2">
        <div class="card bg-dark text-white p-3 border-info text-center">
            <h6>Total Commands</h6>
            <h3><?= $cmd_total ?></h3>
        </div>
    </div>

    <div class="col-md-2">
        <div class="card bg-dark text-white p-3 border-warning text-center">
            <h6>Pending</h6>
            <h3><?= $cmd_pending ?></h3>
        </div>
    </div>

    <div class="col-md-2">
        <div class="card bg-dark text-white p-3 border-success text-center">
            <h6>Done</h6>
            <h3><?= $cmd_done ?></h3>
        </div>
    </div>

    <div class="col-md-2">
        <div class="card bg-dark text-white p-3 border-danger text-center">
            <h6>Failed</h6>
            <h3><?= $cmd_failed ?></h3>
        </div>
    </div>

  
</div>

<div class="d-flex justify-content-between align-items-center mb-3">
    <h4 class="text-white">VM Commands</h4>
    <button class="btn btn-danger btn-sm" onclick="bulkDelete()">Delete Selected</button>
</div>

<table class="table table-dark table-bordered table-hover">
    <thead>
        <tr>
            <th width="40"><input type="checkbox" onclick="toggleAll(this)"></th>
            <th>ID</th>
            <th>VM ID</th>
            <th>Command</th>
            <th>Status</th>
            <th>Created</th>
            <th width="80">Action</th>
        </tr>
    </thead>
   <tbody>
<?php if (!empty($rows)): ?>
    <?php foreach ($rows as $row): ?>
        <tr>
            <td><input type="checkbox" class="cmd-check" value="<?= $row['id'] ?>"></td>
            <td><?= $row['id'] ?></td>
            <td><?= $row['vm_id'] ?></td>
            <td><?= htmlspecialchars($row['command']) ?></td>
            <td>
                <?php
                $cls = 'secondary';
                if (stripos($row['status'],'pend')!==false) $cls='warning';
                if (stripos($row['status'],'done')!==false || stripos($row['status'],'complete')!==false) $cls='success';
                if (stripos($row['status'],'fail')!==false || stripos($row['status'],'error')!==false) $cls='danger';
                ?>
                <span class="badge bg-<?= $cls ?>">
                    <?= strtoupper($row['status']) ?>
                </span>
            </td>
            <td><?= date('d M Y H:i', strtotime($row['created_at'])) ?></td>
            <td>
                <button class="btn btn-sm btn-danger" onclick="deleteCommand(<?= $row['id'] ?>)">Delete</button>
            </td>
        </tr>
    <?php endforeach; ?>
<?php else: ?>
    <tr>
        <td colspan="7" class="text-center text-muted">No commands found</td>
    </tr>
<?php endif; ?>
</tbody>

</table>

</div>

<script>
function toggleAll(cb){
    document.querySelectorAll('.cmd-check').forEach(c => c.checked = cb.checked);
}

function deleteCommand(id){
    if(!confirm('Delete this command?')) return;

    fetch('pages/api.php?action=delete_vm_commands', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ ids: [id] })
    })
    .then(r => r.json())
    .then(res => {
        if(res.success){
            location.reload();
        }else{
            alert('Delete failed');
        }
    });
}

function bulkDelete(){
    const ids = [...document.querySelectorAll('.cmd-check:checked')]
        .map(c => parseInt(c.value));

    if(!ids.length){
        alert('Select commands first');
        return;
    }

    if(!confirm('Delete selected commands?')) return;

    fetch('pages/api.php?action=delete_vm_commands', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify({ ids })
    })
    .then(r => r.json())
    .then(res => {
        if(res.success){
            location.reload();
        }else{
            alert('Delete failed');
        }
    });
}


</script>
