<?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;
}

$agentPath     = __DIR__ . '/../static/agent.ps1';
$serverVersion = '?.?.?';
if (file_exists($agentPath)) {
    $agentContent = file_get_contents($agentPath);
    if (preg_match('/\$AGENT_VERSION\s*=\s*"([^"]+)"/', $agentContent, $m)) {
        $serverVersion = trim($m[1]);
    }
}

$tableCheck = $conn->query("SHOW TABLES LIKE 'agent_update_log'");
$tablesExist = ($tableCheck && $tableCheck->num_rows > 0);

$logs = [];
$lRes = @$conn->query("SELECT * FROM agent_update_log ORDER BY logged_at DESC LIMIT 500");
if ($lRes) while ($r = $lRes->fetch_assoc()) $logs[] = $r;

$allVMs = [];
$vRes = $conn->query("
    SELECT v.id, v.unit_id, v.status, v.agent_version, v.current_ip, v.last_heartbeat,
           r.name AS rdp_name, g.name AS group_name
    FROM vms v
    LEFT JOIN rdps r ON r.id = v.rdp_id
    LEFT JOIN `groups` g ON g.id = r.group_id
    ORDER BY g.name, r.name, v.unit_id
");
if ($vRes) while ($r = $vRes->fetch_assoc()) $allVMs[] = $r;

$pushes = [];
$pRes = @$conn->query("
    SELECT p.*,
        (SELECT COUNT(*) FROM agent_push_vm_status WHERE push_id=p.id AND status='done')    AS done_count,
        (SELECT COUNT(*) FROM agent_push_vm_status WHERE push_id=p.id AND status='pending') AS pending_count,
        (SELECT COUNT(*) FROM agent_push_vm_status WHERE push_id=p.id AND status='failed')  AS failed_count,
        (SELECT COUNT(*) FROM agent_push_vm_status WHERE push_id=p.id AND status='skipped') AS skipped_count
    FROM agent_push_log p ORDER BY p.id DESC LIMIT 10
");
if ($pRes) while ($r = $pRes->fetch_assoc()) $pushes[] = $r;

$activePushId = 0;
foreach ($pushes as $p) {
    if ((int)$p['pending_count'] > 0) { $activePushId = (int)$p['id']; break; }
}

$latestPushVMs = [];
if (!empty($pushes)) {
    $latestPid = (int)$pushes[0]['id'];
    $lvRes = @$conn->query("SELECT * FROM agent_push_vm_status WHERE push_id=$latestPid ORDER BY FIELD(status,'pending','failed','done','skipped'), unit_id ASC");
    if ($lvRes) while ($r = $lvRes->fetch_assoc()) $latestPushVMs[] = $r;
}

$totalVMs  = count($allVMs);
$upToDate  = count(array_filter($allVMs, function($v) use ($serverVersion) { return $v['agent_version'] === $serverVersion; }));
$outdated  = count(array_filter($allVMs, function($v) use ($serverVersion) { return $v['agent_version'] !== null && $v['agent_version'] !== '' && $v['agent_version'] !== $serverVersion; }));
$neverSeen = count(array_filter($allVMs, function($v) { return empty($v['agent_version']); }));
$totalLogs = count($logs);

function agoStr($ts) {
    $ago = time() - strtotime($ts);
    if ($ago < 60)        return $ago.'s ago';
    elseif ($ago < 3600)  return round($ago/60).'m ago';
    elseif ($ago < 86400) return round($ago/3600).'h ago';
    else                  return round($ago/86400).'d ago';
}
?>

<style>
.al-stat{background:#0b0c10;border-radius:14px;padding:16px 20px;display:flex;align-items:center;gap:14px;border:1px solid rgba(255,255,255,.07);transition:border-color .2s,transform .15s;}
.al-stat:hover{transform:translateY(-2px);}
.al-stat-ico{width:44px;height:44px;border-radius:11px;display:flex;align-items:center;justify-content:center;font-size:18px;flex-shrink:0;}
.al-stat-n{font-size:26px;font-weight:800;line-height:1;}
.al-stat-l{font-size:10px;color:#555;margin-top:3px;letter-spacing:.5px;text-transform:uppercase;}

.al-box{background:#0b0c10;border:1px solid rgba(255,255,255,.07);border-radius:14px;overflow:hidden;margin-bottom:20px;}
.al-box-head{padding:13px 20px;border-bottom:1px solid rgba(255,255,255,.06);display:flex;align-items:center;justify-content:space-between;flex-wrap:wrap;gap:8px;}
.al-box-title{font-size:13px;font-weight:700;color:#00b4ff;display:flex;align-items:center;gap:8px;}

.vm-grid{display:grid;grid-template-columns:minmax(110px,1.8fr) minmax(90px,1.4fr) minmax(90px,1.4fr) 145px 115px 145px 130px;align-items:center;gap:6px;padding:10px 20px;}
.vm-grid.hdr{border-bottom:1px solid rgba(0,180,255,.12);background:rgba(0,180,255,.04);padding:9px 20px;}
.vm-grid.hdr>span{font-size:10px;font-weight:700;color:#3a4a55;letter-spacing:.8px;text-transform:uppercase;}
.vm-grid.row{border-bottom:1px solid rgba(255,255,255,.035);transition:background .15s;}
.vm-grid.row:hover{background:rgba(255,255,255,.025);}
.vm-grid.row:last-child{border-bottom:none;}

.push-vm-grid{display:grid;grid-template-columns:minmax(110px,2fr) minmax(90px,1.4fr) minmax(90px,1.4fr) 90px 110px 200px;align-items:center;gap:6px;padding:9px 20px;}
.push-vm-grid.hdr{border-bottom:1px solid rgba(255,119,0,.1);background:rgba(255,119,0,.04);padding:8px 20px;}
.push-vm-grid.hdr>span{font-size:10px;font-weight:700;color:#3a4a55;letter-spacing:.8px;text-transform:uppercase;}
.push-vm-grid.row{border-bottom:1px solid rgba(255,255,255,.03);transition:background .15s;}
.push-vm-grid.row:hover{background:rgba(255,255,255,.02);}
.push-vm-grid.row:last-child{border-bottom:none;}

.log-grid{display:grid;grid-template-columns:100px minmax(110px,2fr) minmax(90px,1.4fr) minmax(90px,1.4fr) 120px 85px 85px 130px;align-items:center;gap:6px;padding:9px 20px;}
.log-grid.hdr{background:rgba(0,0,0,.35);border-bottom:1px solid rgba(255,255,255,.05);padding:9px 20px;position:sticky;top:0;z-index:2;}
.log-grid.hdr>span{font-size:10px;font-weight:700;color:#3a4a55;letter-spacing:.8px;text-transform:uppercase;}
.log-grid.row{border-bottom:1px solid rgba(255,255,255,.03);transition:background .15s;}
.log-grid.row:hover{background:rgba(255,255,255,.02);}
.log-grid.row:last-child{border-bottom:none;}

.al-scroll{max-height:370px;overflow-y:auto;}
.al-scroll::-webkit-scrollbar{width:3px;}
.al-scroll::-webkit-scrollbar-thumb{background:#1e2028;border-radius:3px;}

.al-vbadge{display:inline-block;font-size:11px;font-weight:700;padding:3px 10px;border-radius:20px;font-family:'Courier New',monospace;white-space:nowrap;}
.al-ebadge{display:inline-block;font-size:10px;font-weight:700;padding:2px 8px;border-radius:20px;white-space:nowrap;}
.al-sbadge{display:inline-block;font-size:10px;font-weight:700;padding:3px 10px;border-radius:20px;white-space:nowrap;}

.al-inp{background:#050507;border:1px solid rgba(255,255,255,.09);color:#fff;border-radius:8px;padding:5px 12px;font-size:12px;outline:none;width:200px;transition:border-color .2s;}
.al-inp:focus{border-color:rgba(0,180,255,.45);}
.al-inp::placeholder{color:#333;}
.al-sel{background:#050507;border:1px solid rgba(255,255,255,.09);color:#fff;border-radius:8px;padding:5px 10px;font-size:12px;outline:none;}

.al-lbl{font-size:12px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}
.al-sub{font-size:10px;color:#3d4450;margin-top:2px;}
.al-mono{font-family:'Courier New',monospace;font-size:11px;}
.al-empty{padding:44px 20px;text-align:center;color:#333;font-size:13px;}
.al-btn{border-radius:8px;padding:7px 15px;font-size:12px;cursor:pointer;transition:opacity .15s;}
.al-btn:hover{opacity:.8;}

.push-pill{display:inline-flex;align-items:center;gap:5px;padding:3px 10px;border-radius:20px;font-size:11px;font-weight:700;cursor:pointer;border:1px solid;transition:opacity .15s;}
.push-pill:hover{opacity:.8;}
.push-pill.active-push{animation:pulse-border 2s infinite;}
@keyframes pulse-border{0%,100%{box-shadow:0 0 0 0 rgba(255,119,0,.3);}50%{box-shadow:0 0 0 5px rgba(255,119,0,0);}}

.progress-bar-wrap{width:100%;height:6px;background:rgba(255,255,255,.06);border-radius:3px;overflow:hidden;margin-top:4px;}
.progress-bar-fill{height:100%;border-radius:3px;transition:width .5s;}
</style>

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

<?php if (!$tablesExist): ?>
<div style="background:rgba(255,119,0,.12);border:1px solid rgba(255,119,0,.4);color:#ff9500;border-radius:10px;padding:14px 18px;margin-bottom:20px;font-size:13px;">
    <i class="fa fa-triangle-exclamation me-2"></i>
    <strong>Migration nahi chali!</strong> &nbsp;
    <code style="background:rgba(0,0,0,.3);padding:2px 8px;border-radius:5px;font-size:12px;">migration_agent_log.sql</code>
    &nbsp; run karo phpMyAdmin mein. Bina is ke agent version track nahi hoga.
</div>
<?php endif; ?>

<div style="display:flex;align-items:flex-start;justify-content:space-between;gap:10px;margin-bottom:20px;min-width:0;">
    <div style="min-width:0;">
        <h4 class="mb-1 fw-bold" style="color:#00b4ff;">
            <i class="fa fa-robot me-2"></i>Agent Update Log
        </h4>
        <div style="font-size:12px;color:#455;">
            Server version &nbsp;
            <code style="color:#00ff66;background:rgba(0,255,102,.08);border:1px solid rgba(0,255,102,.18);padding:2px 8px;border-radius:6px;font-size:12px;">v<?= htmlspecialchars($serverVersion) ?></code>
            &nbsp;·&nbsp; agents auto-update every 30 min
        </div>
    </div>
    <div style="display:flex;gap:8px;flex-shrink:0;margin-top:4px;">
        <button class="al-btn" onclick="location.reload()" style="background:rgba(0,180,255,.1);color:#00b4ff;border:1px solid rgba(0,180,255,.25);">
            <i class="fa fa-rotate-right me-1"></i>Refresh
        </button>
        <button id="clear_btn" class="al-btn" onclick="clearLog()" style="background:rgba(255,0,60,.1);color:#ff003c;border:1px solid rgba(255,0,60,.25);">
            <i class="fa fa-trash me-1"></i>Clear Log
        </button>
    </div>
</div>
<div id="al_notify" style="display:none;padding:10px 16px;border-radius:10px;font-size:13px;font-weight:600;margin-bottom:14px;"></div>

<div class="row g-3 mb-4">
    <div class="col-6 col-xl-3">
        <div class="al-stat" style="border-color:rgba(0,180,255,.18);">
            <div class="al-stat-ico" style="background:rgba(0,180,255,.1);color:#00b4ff;"><i class="fa fa-desktop"></i></div>
            <div><div class="al-stat-n" style="color:#00b4ff;"><?= $totalVMs ?></div><div class="al-stat-l">Total VMs</div></div>
        </div>
    </div>
    <div class="col-6 col-xl-3">
        <div class="al-stat" style="border-color:rgba(0,255,102,.18);">
            <div class="al-stat-ico" style="background:rgba(0,255,102,.1);color:#00ff66;"><i class="fa fa-circle-check"></i></div>
            <div><div class="al-stat-n" style="color:#00ff66;"><?= $upToDate ?></div><div class="al-stat-l">Up to Date</div></div>
            <?php if($totalVMs > 0): ?><div style="margin-left:auto;font-size:20px;font-weight:800;color:#00ff6618;"><?= round($upToDate/$totalVMs*100) ?>%</div><?php endif; ?>
        </div>
    </div>
    <div class="col-6 col-xl-3">
        <div class="al-stat" style="border-color:rgba(255,179,0,.18);">
            <div class="al-stat-ico" style="background:rgba(255,179,0,.1);color:#ffb300;"><i class="fa fa-triangle-exclamation"></i></div>
            <div><div class="al-stat-n" style="color:#ffb300;"><?= $outdated ?></div><div class="al-stat-l">Outdated</div></div>
        </div>
    </div>
    <div class="col-6 col-xl-3">
        <div class="al-stat" style="border-color:rgba(255,255,255,.05);">
            <div class="al-stat-ico" style="background:rgba(255,255,255,.04);color:#444;"><i class="fa fa-circle-question"></i></div>
            <div><div class="al-stat-n" style="color:#444;"><?= $neverSeen ?></div><div class="al-stat-l">Never Reported</div></div>
        </div>
    </div>
</div>

<?php if (!empty($pushes)): ?>
<div class="al-box" style="border-color:rgba(255,119,0,.15);">
    <div class="al-box-head" style="border-color:rgba(255,119,0,.1);">
        <div class="al-box-title" style="color:#ff7700;">
            <i class="fa fa-rocket"></i>Push History
            <?php if ($activePushId): ?>
            <span style="font-size:10px;background:rgba(255,119,0,.2);color:#ff7700;border:1px solid rgba(255,119,0,.4);padding:2px 8px;border-radius:20px;animation:pulse-border 2s infinite;">
                <i class="fa fa-spinner fa-spin me-1" style="font-size:9px;"></i>LIVE
            </span>
            <?php endif; ?>
        </div>
        <div class="d-flex gap-2 flex-wrap">
            <?php foreach ($pushes as $i => $p):
                $pd = (int)$p['pending_count'];
                $pc = $pd > 0 ? '#ff7700' : ((int)$p['failed_count'] > 0 ? '#ff003c' : '#00ff66');
                $pb = $pd > 0 ? 'rgba(255,119,0,.15)' : ((int)$p['failed_count'] > 0 ? 'rgba(255,0,60,.12)' : 'rgba(0,255,102,.1)');
                $pbrd = $pd > 0 ? 'rgba(255,119,0,.4)' : ((int)$p['failed_count'] > 0 ? 'rgba(255,0,60,.3)' : 'rgba(0,255,102,.3)');
                $lbl = $pd > 0 ? '⏳' : ((int)$p['failed_count'] > 0 ? '⚠' : '✓');
            ?>
            <span class="push-pill <?= $i===0&&$pd>0?'active-push':'' ?>" onclick="showPush(<?= $p['id'] ?>)"
                style="background:<?= $pb ?>;color:<?= $pc ?>;border-color:<?= $pbrd ?>;">
                <?= $lbl ?> v<?= htmlspecialchars($p['to_version']) ?>
                <span style="opacity:.6;font-size:10px;"><?= date('d/m H:i',strtotime($p['pushed_at'])) ?></span>
            </span>
            <?php endforeach; ?>
        </div>
    </div>

    <div id="push_detail_wrap">
    <?php if (!empty($pushes)):
        $lp = $pushes[0];
        $lpTotal   = (int)$lp['total_vms'];
        $lpDone    = (int)$lp['done_count'];
        $lpPending = (int)$lp['pending_count'];
        $lpFailed  = (int)$lp['failed_count'];
        $lpSkipped = (int)$lp['skipped_count'];
        $lpPct = $lpTotal > 0 ? round(($lpDone + $lpSkipped) / $lpTotal * 100) : 0;
    ?>
    <div style="padding:14px 20px;border-bottom:1px solid rgba(255,255,255,.05);display:flex;align-items:center;gap:20px;flex-wrap:wrap;" id="push_summary">
        <div>
            <div style="font-size:10px;color:#555;text-transform:uppercase;letter-spacing:.5px;">Push</div>
            <div style="font-size:13px;color:#ff7700;font-weight:700;">v<?= htmlspecialchars($lp['from_version']) ?> → v<?= htmlspecialchars($lp['to_version']) ?></div>
        </div>
        <div>
            <div style="font-size:10px;color:#555;text-transform:uppercase;letter-spacing:.5px;">By</div>
            <div style="font-size:13px;color:#ccc;"><?= htmlspecialchars($lp['pushed_by']) ?></div>
        </div>
        <div>
            <div style="font-size:10px;color:#555;text-transform:uppercase;letter-spacing:.5px;">Time</div>
            <div style="font-size:13px;color:#888;"><?= date('d/m/y H:i',strtotime($lp['pushed_at'])) ?></div>
        </div>
        <div style="flex:1;min-width:200px;">
            <div style="display:flex;justify-content:space-between;font-size:11px;margin-bottom:4px;">
                <span style="color:#00ff66;">✓ <?= $lpDone ?> done</span>
                <span style="color:#ffb300;">⏳ <?= $lpPending ?> pending</span>
                <span style="color:#ff003c;">✗ <?= $lpFailed ?> failed</span>
                <span style="color:#555;">– <?= $lpSkipped ?> skipped</span>
            </div>
            <div class="progress-bar-wrap">
                <div class="progress-bar-fill" id="push_progress_bar" style="width:<?= $lpPct ?>%;background:<?= $lpFailed>0?'linear-gradient(90deg,#00ff66,#ffb300)':'#00ff66' ?>;"></div>
            </div>
        </div>
    </div>

    <div class="push-vm-grid hdr" id="push_vm_hdr">
        <span>VM / Unit</span><span>RDP</span><span>Group</span><span>Was</span><span>Status</span><span>Reason / Time</span>
    </div>
    <div class="al-scroll" id="push_vm_list">
    <?php foreach ($latestPushVMs as $pv):
        $ps = $pv['status'];
        if ($ps==='done')     { $sc='#00ff66'; $sb='rgba(0,255,102,.1)';  $sbrd='rgba(0,255,102,.2)';  $sl='✓ DONE'; }
        elseif ($ps==='pending') { $sc='#ffb300'; $sb='rgba(255,179,0,.1)'; $sbrd='rgba(255,179,0,.2)'; $sl='⏳ PENDING'; }
        elseif ($ps==='failed')  { $sc='#ff003c'; $sb='rgba(255,0,60,.1)';  $sbrd='rgba(255,0,60,.2)';  $sl='✗ FAILED'; }
        else                     { $sc='#555';    $sb='rgba(255,255,255,.04)';$sbrd='rgba(255,255,255,.1)'; $sl='– SKIP'; }
    ?>
    <div class="push-vm-grid row">
        <div class="al-lbl" style="color:#ddd;font-size:12px;font-weight:600;"><?= htmlspecialchars($pv['unit_id'] ?: 'VM #'.$pv['vm_id']) ?></div>
        <div class="al-lbl" style="color:#888;font-size:11px;"><?= htmlspecialchars($pv['rdp_nickname'] ?: '—') ?></div>
        <div class="al-lbl" style="color:#666;font-size:11px;"><?= htmlspecialchars($pv['group_name'] ?: '—') ?></div>
        <div class="al-mono" style="color:#555;"><?= $pv['version_at_push'] ? 'v'.htmlspecialchars($pv['version_at_push']) : '—' ?></div>
        <div><span class="al-sbadge" style="background:<?= $sb ?>;color:<?= $sc ?>;border:1px solid <?= $sbrd ?>;"><?= $sl ?></span></div>
        <div style="font-size:11px;">
            <?php if ($ps==='failed' && $pv['fail_reason']): ?>
            <span style="color:#ff6666;"><?= htmlspecialchars($pv['fail_reason']) ?></span>
            <?php elseif ($ps==='done' && $pv['updated_at']): ?>
            <span style="color:#555;"><?= agoStr($pv['updated_at']) ?></span>
            <?php elseif ($ps==='pending'): ?>
            <span style="color:#555;">Waiting for heartbeat…</span>
            <?php else: ?>
            <span style="color:#333;">Already on target version</span>
            <?php endif; ?>
        </div>
    </div>
    <?php endforeach; ?>
    <?php if (empty($latestPushVMs)): ?>
    <div class="al-empty">No VM status data for this push.</div>
    <?php endif; ?>
    </div>
    <?php endif; ?>
    </div>
</div>
<?php endif; ?>

<div class="al-box">
    <div class="al-box-head">
        <div class="al-box-title"><i class="fa fa-desktop"></i>VM Agent Status</div>
        <input class="al-inp" id="vm_search" oninput="filterVMs()" placeholder="Search VM / RDP / Group…">
    </div>
    <div class="vm-grid hdr">
        <span>VM / Unit</span><span>RDP</span><span>Group</span><span>Agent Version</span><span>Status</span><span>IP Address</span><span>Last Heartbeat</span>
    </div>
    <div class="al-scroll" id="vm_list">
    <?php foreach ($allVMs as $v):
        $ver = $v['agent_version'] ?? '';
        $isUpToDate = ($ver === $serverVersion);
        $isOutdated = ($ver !== '' && !$isUpToDate);
        if ($isUpToDate)     { $vc='#00ff66'; $vb='rgba(0,255,102,.1)';    $vbrd='rgba(0,255,102,.22)';  $vl='v'.$ver; }
        elseif ($isOutdated) { $vc='#ffb300'; $vb='rgba(255,179,0,.1)';    $vbrd='rgba(255,179,0,.22)';  $vl='v'.$ver; }
        else                 { $vc='#3a4450'; $vb='rgba(255,255,255,.04)';  $vbrd='rgba(255,255,255,.08)'; $vl='—'; }

        $status = $v['status'] ?? 'Offline';
        $hb     = $v['last_heartbeat'];
        $online = $hb && (strtotime($hb) > time() - 300);
        if ($online && $status==='Running')  { $sc='#00ff66'; }
        elseif ($status==='Blocked')         { $sc='#ff003c'; }
        elseif ($status==='Paused')          { $sc='#ffb300'; }
        elseif ($online)                     { $sc='#00e5ff'; }
        else                                 { $sc='#3a4450'; }

        $agoStr = $hb ? agoStr($hb) : '';
    ?>
    <div class="vm-grid row vm-row" data-vm="<?= htmlspecialchars(strtolower(($v['unit_id']??'').($v['rdp_name']??'').($v['group_name']??''))) ?>">
        <div><div class="al-lbl" style="color:#ddd;font-weight:600;font-size:13px;"><?= htmlspecialchars($v['unit_id'] ?: 'VM #'.$v['id']) ?></div></div>
        <div class="al-lbl" style="color:#888;"><?= htmlspecialchars($v['rdp_name'] ?: '—') ?></div>
        <div class="al-lbl" style="color:#666;"><?= htmlspecialchars($v['group_name'] ?: '—') ?></div>
        <div>
            <span class="al-vbadge" style="background:<?= $vb ?>;color:<?= $vc ?>;border:1px solid <?= $vbrd ?>;">
                <?= htmlspecialchars($vl) ?><?= $isOutdated ? ' ⚠' : '' ?>
            </span>
            <?php if($isOutdated): ?><div style="font-size:9px;color:#444;margin-top:3px;">latest v<?= htmlspecialchars($serverVersion) ?></div><?php endif; ?>
        </div>
        <div style="color:<?= $sc ?>;font-size:12px;font-weight:600;"><span style="font-size:7px;margin-right:5px;vertical-align:middle;">●</span><?= htmlspecialchars($status) ?></div>
        <div class="al-mono" style="color:#666;"><?= htmlspecialchars($v['current_ip'] ?: '—') ?></div>
        <div>
            <?php if($hb): ?>
            <div style="font-size:12px;font-weight:<?= $online?'600':'400' ?>;color:<?= $online?'#00ff66':'#444' ?>;"><?= $online ? date('H:i:s',strtotime($hb)) : date('d/m H:i',strtotime($hb)) ?></div>
            <div class="al-sub"><?= $agoStr ?></div>
            <?php else: ?><span style="color:#2a2f38;font-size:12px;">Never</span><?php endif; ?>
        </div>
    </div>
    <?php endforeach; ?>
    <?php if(empty($allVMs)): ?><div class="al-empty"><i class="fa fa-desktop me-2"></i>No VMs registered yet.</div><?php endif; ?>
    </div>
</div>

<div class="al-box">
    <div class="al-box-head">
        <div class="al-box-title"><i class="fa fa-list-check"></i>Update Event Log <span style="font-size:11px;color:#333;font-weight:400;"><?= $totalLogs ?> events</span></div>
        <select class="al-sel" id="log_filter" onchange="filterLog()">
            <option value="">All Events</option>
            <option value="update">↑ Updates</option>
            <option value="first_seen">★ First Seen</option>
            <option value="downgrade">↓ Downgrades</option>
        </select>
    </div>
    <div class="al-scroll" id="log_list">
    <div class="log-grid hdr">
        <span>Time</span><span>VM / Unit</span><span>RDP</span><span>Group</span><span>Event</span><span>Old Ver</span><span>New Ver</span><span>IP</span>
    </div>
    <?php foreach ($logs as $l):
        $evt = $l['event'];
        if ($evt==='update')         { $ec='#00b4ff'; $eb='rgba(0,180,255,.1)';  $ebrd='rgba(0,180,255,.2)';  $el='↑ UPDATE'; }
        elseif ($evt==='first_seen') { $ec='#00ff66'; $eb='rgba(0,255,102,.1)';  $ebrd='rgba(0,255,102,.2)';  $el='★ FIRST'; }
        else                         { $ec='#ff003c'; $eb='rgba(255,0,60,.1)';   $ebrd='rgba(255,0,60,.2)';   $el='↓ DOWNGRADE'; }
    ?>
    <div class="log-grid row log-row" data-event="<?= $evt ?>">
        <div>
            <div style="font-size:11px;color:#4a5260;white-space:nowrap;"><?= date('d/m H:i:s',strtotime($l['logged_at'])) ?></div>
            <div class="al-sub"><?= agoStr($l['logged_at']) ?></div>
        </div>
        <div class="al-lbl" style="color:#ccc;font-size:12px;"><?= htmlspecialchars($l['unit_id'] ?: 'VM #'.$l['vm_id']) ?></div>
        <div class="al-lbl" style="color:#666;font-size:11px;"><?= htmlspecialchars($l['rdp_nickname'] ?: '—') ?></div>
        <div class="al-lbl" style="color:#555;font-size:11px;"><?= htmlspecialchars($l['group_name'] ?: '—') ?></div>
        <div><span class="al-ebadge" style="background:<?= $eb ?>;color:<?= $ec ?>;border:1px solid <?= $ebrd ?>;"><?= $el ?></span></div>
        <div class="al-mono" style="color:#444;"><?= $l['old_version'] ? 'v'.htmlspecialchars($l['old_version']) : '—' ?></div>
        <div class="al-mono" style="color:#00ff66;font-weight:700;">v<?= htmlspecialchars($l['new_version']) ?></div>
        <div class="al-mono al-lbl" style="color:#444;"><?= htmlspecialchars($l['ip_address'] ?: '—') ?></div>
    </div>
    <?php endforeach; ?>
    <?php if(empty($logs)): ?><div class="al-empty"><i class="fa fa-robot me-2"></i>No events yet. Agents report here on next heartbeat.</div><?php endif; ?>
    </div>
</div>

</div>

<script>
const ACTIVE_PUSH_ID = <?= $activePushId ?>;

function filterVMs() {
    const q = document.getElementById('vm_search').value.toLowerCase();
    document.querySelectorAll('.vm-row').forEach(r => {
        r.style.display = r.dataset.vm.includes(q) ? '' : 'none';
    });
}
function filterLog() {
    const f = document.getElementById('log_filter').value;
    document.querySelectorAll('.log-row').forEach(r => {
        r.style.display = (!f || r.dataset.event === f) ? '' : 'none';
    });
}

function alNotify(msg, ok) {
    const el = document.getElementById('al_notify');
    el.textContent = msg;
    el.style.display = 'block';
    el.style.cssText = `display:block;padding:10px 16px;border-radius:10px;font-size:13px;font-weight:600;margin-bottom:14px;${ok ? 'background:rgba(0,255,102,.12);color:#00ff66;border:1px solid rgba(0,255,102,.3);' : 'background:rgba(255,0,60,.12);color:#ff003c;border:1px solid rgba(255,0,60,.3);'}`;
    setTimeout(() => el.style.display = 'none', 4000);
}

async function clearLog() {
    if (!confirm('Clear all agent update log entries? VM agent_version data will stay.')) return;
    const btn = document.getElementById('clear_btn');
    btn.disabled = true;
    btn.innerHTML = '<i class="fa fa-spinner fa-spin me-1"></i>Clearing...';
    try {
        const res = await fetch('pages/api.php?action=clear_agent_log', { method:'POST', headers:{'Content-Type':'application/json'}, body:'{}' });
        const text = await res.text();
        let data;
        try { data = JSON.parse(text); } catch(e) { alNotify('Server error: ' + text.substring(0,100), false); btn.disabled=false; btn.innerHTML='<i class="fa fa-trash me-1"></i>Clear Log'; return; }
        if (data.success) {
            alNotify('Log cleared. Reloading...', true);
            setTimeout(() => location.reload(), 800);
        } else {
            alNotify('Failed: ' + (data.error || 'unknown error'), false);
        }
    } catch(e) {
        alNotify('Network error: ' + e.message, false);
    }
    btn.disabled = false;
    btn.innerHTML = '<i class="fa fa-trash me-1"></i>Clear Log';
}

async function showPush(pushId) {
    const res = await fetch('pages/api.php?action=get_push_status', { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({push_id: pushId}) });
    const data = await res.json();
    if (!data.success) return;

    const p = data.push;
    const vms = data.vms;
    const total = parseInt(p.total_vms) || 1;
    const done = vms.filter(v => v.status === 'done').length;
    const pending = vms.filter(v => v.status === 'pending').length;
    const failed = vms.filter(v => v.status === 'failed').length;
    const skipped = vms.filter(v => v.status === 'skipped').length;
    const pct = Math.round((done + skipped) / total * 100);

    document.getElementById('push_summary').innerHTML = `
        <div><div style="font-size:10px;color:#555;text-transform:uppercase;letter-spacing:.5px;">Push</div>
        <div style="font-size:13px;color:#ff7700;font-weight:700;">v${p.from_version} → v${p.to_version}</div></div>
        <div><div style="font-size:10px;color:#555;text-transform:uppercase;letter-spacing:.5px;">By</div>
        <div style="font-size:13px;color:#ccc;">${p.pushed_by}</div></div>
        <div><div style="font-size:10px;color:#555;text-transform:uppercase;letter-spacing:.5px;">Time</div>
        <div style="font-size:13px;color:#888;">${p.pushed_at}</div></div>
        <div style="flex:1;min-width:200px;">
            <div style="display:flex;justify-content:space-between;font-size:11px;margin-bottom:4px;">
                <span style="color:#00ff66;">✓ ${done} done</span>
                <span style="color:#ffb300;">⏳ ${pending} pending</span>
                <span style="color:#ff003c;">✗ ${failed} failed</span>
                <span style="color:#555;">– ${skipped} skipped</span>
            </div>
            <div class="progress-bar-wrap"><div class="progress-bar-fill" style="width:${pct}%;background:${failed>0?'linear-gradient(90deg,#00ff66,#ffb300)':'#00ff66'};"></div></div>
        </div>`;

    const statusColor = {done:'#00ff66',pending:'#ffb300',failed:'#ff003c',skipped:'#555'};
    const statusBg    = {done:'rgba(0,255,102,.1)',pending:'rgba(255,179,0,.1)',failed:'rgba(255,0,60,.1)',skipped:'rgba(255,255,255,.04)'};
    const statusBrd   = {done:'rgba(0,255,102,.2)',pending:'rgba(255,179,0,.2)',failed:'rgba(255,0,60,.2)',skipped:'rgba(255,255,255,.1)'};
    const statusLbl   = {done:'✓ DONE',pending:'⏳ PENDING',failed:'✗ FAILED',skipped:'– SKIP'};

    let html = '';
    vms.forEach(v => {
        const sc = statusColor[v.status]||'#555';
        const sb = statusBg[v.status]||'rgba(255,255,255,.04)';
        const sbrd = statusBrd[v.status]||'rgba(255,255,255,.1)';
        const sl = statusLbl[v.status]||v.status;
        const reason = v.status==='failed' && v.fail_reason ? `<span style="color:#ff6666;">${v.fail_reason}</span>` :
                       v.status==='done' && v.updated_at ? `<span style="color:#555;">${v.updated_at}</span>` :
                       v.status==='pending' ? `<span style="color:#555;">Waiting for heartbeat…</span>` :
                       `<span style="color:#333;">Already on target version</span>`;
        html += `<div class="push-vm-grid row">
            <div class="al-lbl" style="color:#ddd;font-size:12px;font-weight:600;">${v.unit_id||'VM #'+v.vm_id}</div>
            <div class="al-lbl" style="color:#888;font-size:11px;">${v.rdp_nickname||'—'}</div>
            <div class="al-lbl" style="color:#666;font-size:11px;">${v.group_name||'—'}</div>
            <div class="al-mono" style="color:#555;">${v.version_at_push?'v'+v.version_at_push:'—'}</div>
            <div><span class="al-sbadge" style="background:${sb};color:${sc};border:1px solid ${sbrd};">${sl}</span></div>
            <div style="font-size:11px;">${reason}</div>
        </div>`;
    });
    document.getElementById('push_vm_list').innerHTML = html || '<div class="al-empty">No VM data.</div>';
}

if (ACTIVE_PUSH_ID > 0) {
    setInterval(async () => {
        const res = await fetch('pages/api.php?action=get_push_status', { method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({push_id: ACTIVE_PUSH_ID}) });
        const data = await res.json();
        if (!data.success) return;
        const pending = data.vms.filter(v => v.status === 'pending').length;
        if (pending > 0) showPush(ACTIVE_PUSH_ID);
        else location.reload();
    }, 15000);
}
</script>