<?php
require __DIR__ . "/../api/monitoring/koneksi.php";
$pcs = $conn->query("SELECT id, hostname FROM pc_clients ORDER BY hostname");
?>
<!DOCTYPE html>
<html lang="id">
<head>
    <meta charset="UTF-8">
    <title>Monitoring Data</title>
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link rel="stylesheet" href="../assets/css/dashboard.css">
</head>
<body>

<div class="main">

<h2>📊 Data PC Monitoring</h2>

<!-- FILTER -->
<form id="filterForm">
    <label>Dari:</label>
    <input type="date" name="from">

    <label>Sampai:</label>
    <input type="date" name="to">

    <label>PC:</label>
    <select name="pc_id">
        <option value="">Semua</option>
        <?php while ($p = $pcs->fetch_assoc()): ?>
            <option value="<?= $p['id'] ?>"><?= $p['hostname'] ?></option>
        <?php endwhile ?>
    </select>

    <button type="submit">🔍 Filter</button>
</form>

<br>

<!-- DELETE -->
<button onclick="deleteData()" style="background:#e53935;color:#fff;padding:8px;border-radius:6px;">
    🗑 Hapus Data (Sesuai Filter)
</button>

<br><br>

<!-- TABLE -->
<table border="1" width="100%" cellpadding="6">
    <thead>
        <tr>
            <th>Waktu</th>
            <th>PC</th>
            <th>CPU %</th>
            <th>RAM %</th>
            <th>Temp CPU</th>
        </tr>
    </thead>
    <tbody id="tableBody"></tbody>
</table>

</div>

<script>
function loadData() {
    const form = document.getElementById('filterForm');
    const params = new URLSearchParams(new FormData(form));

    fetch('../api/monitoring/list_monitoring.php?' + params)
        .then(r => r.json())
        .then(rows => {
            const tb = document.getElementById('tableBody');
            tb.innerHTML = '';

            rows.forEach(r => {
                tb.innerHTML += `
                    <tr>
                        <td>${r.created_at}</td>
                        <td>${r.hostname}</td>
                        <td>${r.cpu_usage}%</td>
                        <td>${r.ram_percent}%</td>
                        <td>${r.cpu_temp ?? '-'}</td>
                    </tr>
                `;
            });
        });
}

document.getElementById('filterForm').onsubmit = e => {
    e.preventDefault();
    loadData();
};

loadData();

function deleteData() {
    if (!confirm('Yakin ingin menghapus data sesuai filter?')) return;

    const form = document.getElementById('filterForm');
    const data = new FormData(form);

    fetch('../api/monitoring/delete_monitoring.php', {
        method: 'POST',
        body: data
    })
    .then(r => r.json())
    .then(res => {
        alert(res.message);
        loadData();
    });
}
</script>

</body>
</html>
