<?php
$server = $server ?? [];
$processList = $processList ?? [];
?>

<div class="page-header">
    <div class="page-header-left">
        <div class="back-link">
            <a href="/servers/<?= $server['id'] ?>"><i class="fas fa-arrow-left"></i> Back to Server</a>
        </div>
        <h1 class="page-title">Processes</h1>
        <p class="page-subtitle">
            <?= htmlspecialchars($server['name']) ?>
            &middot; <?= count($processList) ?> processes
        </p>
    </div>
    <div class="page-header-right">
        <button class="btn btn-secondary" onclick="location.reload()">
            <i class="fas fa-sync-alt"></i> Refresh
        </button>
    </div>
</div>

<div class="card">
    <div class="card-body">
        <?php if (empty($processList)): ?>
            <div class="empty-state">
                <i class="fas fa-microchip empty-icon"></i>
                <p>No process data available.</p>
            </div>
        <?php else: ?>
            <div class="table-responsive">
                <table class="table table-hover table-sm" id="processTable">
                    <thead>
                        <tr>
                            <th>PID</th>
                            <th>User</th>
                            <th>CPU %</th>
                            <th>MEM %</th>
                            <th>RSS</th>
                            <th>STAT</th>
                            <th>Time</th>
                            <th>Command</th>
                            <th>Actions</th>
                        </tr>
                    </thead>
                    <tbody>
                        <?php foreach ($processList as $p): ?>
                            <tr>
                                <td class="font-mono"><?= $p['pid'] ?></td>
                                <td><?= htmlspecialchars($p['user']) ?></td>
                                <td>
                                    <span class="badge <?= $p['cpu'] > 50 ? 'badge-danger' : ($p['cpu'] > 10 ? 'badge-warning' : 'badge-info') ?>">
                                        <?= number_format($p['cpu'], 1) ?>%
                                    </span>
                                </td>
                                <td><?= number_format($p['mem'], 1) ?>%</td>
                                <td class="font-mono"><?= format_bytes($p['rss'] * 1024) ?></td>
                                <td><code><?= htmlspecialchars($p['stat']) ?></code></td>
                                <td class="font-mono"><?= htmlspecialchars($p['time']) ?></td>
                                <td class="cell-command" title="<?= htmlspecialchars($p['command']) ?>">
                                    <code><?= htmlspecialchars(mb_substr($p['command'], 0, 60)) ?><?= mb_strlen($p['command']) > 60 ? '...' : '' ?></code>
                                </td>
                                <td>
                                    <button class="btn btn-xs btn-danger" onclick="killProcess(<?= $p['pid'] ?>, this)"
                                            title="Kill process <?= $p['pid'] ?>">
                                        <i class="fas fa-times"></i> Kill
                                    </button>
                                </td>
                            </tr>
                        <?php endforeach; ?>
                    </tbody>
                </table>
            </div>
        <?php endif; ?>
    </div>
</div>

<div id="killModal" class="modal">
    <div class="modal-dialog">
        <div class="modal-header">
            <h3><i class="fas fa-exclamation-triangle text-danger"></i> Kill Process</h3>
            <button class="modal-close" onclick="closeKillModal()">&times;</button>
        </div>
        <div class="modal-body">
            <p>Are you sure you want to terminate process <strong id="killPidDisplay"></strong>?</p>
            <div class="form-group" style="margin-top: 1rem;">
                <label class="checkbox-label">
                    <input type="checkbox" id="killForce">
                    <span>Force kill (SIGKILL -9) if process does not respond</span>
                </label>
            </div>
        </div>
        <div class="modal-footer">
            <button class="btn btn-secondary" onclick="closeKillModal()">Cancel</button>
            <button class="btn btn-danger" id="confirmKillBtn" onclick="confirmKill()">
                <i class="fas fa-times"></i> Terminate
            </button>
        </div>
    </div>
</div>

<script>
let pendingPid = null;
let pendingBtn = null;

function getCsrfToken() {
    return document.querySelector('meta[name="csrf-token"]')?.content || '';
}

function killProcess(pid, btn) {
    pendingPid = pid;
    pendingBtn = btn;
    document.getElementById('killPidDisplay').textContent = pid;
    document.getElementById('killModal').style.display = 'flex';
}

function closeKillModal() {
    pendingPid = null;
    pendingBtn = null;
    document.getElementById('killForce').checked = false;
    document.getElementById('killModal').style.display = 'none';
}

function confirmKill() {
    if (!pendingPid) return;

    const signal = document.getElementById('killForce').checked ? 9 : 15;
    const btn = document.getElementById('confirmKillBtn');
    const originalText = btn.innerHTML;
    btn.disabled = true;
    btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> Killing...';

    fetch('/servers/<?= $server['id'] ?>/processes/kill', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'X-CSRF-Token': getCsrfToken(),
        },
        body: 'pid=' + pendingPid + '&signal=' + signal + '&_csrf_token=' + encodeURIComponent(getCsrfToken()),
    })
    .then(r => r.json())
    .then(data => {
        showToast(data.success ? 'success' : 'error', data.message);
        if (data.success && pendingBtn) {
            const row = pendingBtn.closest('tr');
            row.style.opacity = '0.4';
            pendingBtn.disabled = true;
            pendingBtn.innerHTML = '<i class="fas fa-check"></i> Killed';
        }
        closeKillModal();
    })
    .catch(err => {
        showToast('error', 'Request failed: ' + err.message);
        closeKillModal();
    })
    .finally(() => {
        btn.disabled = false;
        btn.innerHTML = originalText;
    });
}

document.addEventListener('keydown', function(e) {
    if (e.key === 'Escape') closeKillModal();
});
</script>
