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

<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">Web Terminal</h1>
        <p class="page-subtitle">
            <?= htmlspecialchars($server['name']) ?> &mdash; <?= htmlspecialchars($server['ip_address']) ?>:<?= $server['ssh_port'] ?>
        </p>
    </div>
    <div class="page-header-right">
        <button class="btn btn-secondary" onclick="clearTerminal()">
            <i class="fas fa-eraser"></i> Clear
        </button>
        <button class="btn btn-danger btn-sm" onclick="clearHistory()">
            <i class="fas fa-trash"></i> Clear History
        </button>
    </div>
</div>

<div class="terminal-container" id="terminalContainer">
    <div class="terminal-header">
        <span class="terminal-title">
            <i class="fas fa-terminal"></i>
            <?= htmlspecialchars($server['ssh_user']) ?>@<?= htmlspecialchars($server['ip_address']) ?>
        </span>
        <span class="terminal-status" id="connectionStatus">
            <span class="status-dot offline"></span> Disconnected
        </span>
    </div>
    <div class="terminal-body" id="terminalOutput">
        <div class="terminal-welcome">
            <pre class="terminal-ascii">
  ____                              __  __
 / ___|  ___ _ ____   _____ _ __   |  \/  | __ _ _ __   __ _  __ _  ___ _ __
 \___ \ / _ \ '__\ \ / / _ \ '__|  | |\/| |/ _` | '_ \ / _` |/ _` |/ _ \ '__|
  ___) |  __/ |   \ V /  __/ |     | |  | | (_| | | | | (_| | (_| |  __/ |
 |____/ \___|_|    \_/ \___|_|     |_|  |_|\__,_|_| |_|\__,_|\__, |\___|_|
                                                              |___/
</pre>
            <p>Connected to <strong><?= htmlspecialchars($server['name']) ?></strong></p>
            <p class="text-muted">Type commands below to execute them on the remote server.</p>
        </div>
    </div>
    <div class="terminal-input-area">
        <div class="terminal-prompt">
            <span class="prompt-user"><?= htmlspecialchars($server['ssh_user']) ?></span>
            <span>@</span>
            <span class="prompt-host"><?= htmlspecialchars($server['ip_address']) ?></span>
            <span>:</span>
            <span class="prompt-path">~</span>
            <span>$ </span>
        </div>
        <input type="text" id="terminalInput" class="terminal-input"
               placeholder="Type command and press Enter..."
               autocomplete="off" autofocus>
        <button class="btn btn-primary" id="executeBtn" onclick="executeCommand()">
            <i class="fas fa-play"></i>
        </button>
    </div>
</div>

<div class="dashboard-grid" style="margin-top: 1.5rem;">
    <div class="dashboard-card">
        <div class="card-header">
            <h2><i class="fas fa-history"></i> Command History</h2>
        </div>
        <div class="card-body">
            <?php if (empty($commandHistory)): ?>
                <div class="empty-state small">
                    <p>No command history.</p>
                </div>
            <?php else: ?>
                <div class="table-responsive" style="max-height: 300px; overflow-y: auto;">
                    <table class="table table-sm">
                        <thead>
                            <tr>
                                <th>Time</th>
                                <th>Command</th>
                                <th>Status</th>
                                <th>User</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php foreach ($commandHistory as $entry): ?>
                                <tr>
                                    <td><?= date('H:i:s', strtotime($entry['executed_at'] ?? '')) ?></td>
                                    <td><code><?= htmlspecialchars($entry['command']) ?></code></td>
                                    <td>
                                        <span class="badge <?= ($entry['exit_status'] ?? 1) == 0 ? 'badge-success' : 'badge-danger' ?>">
                                            <?= ($entry['exit_status'] ?? 1) == 0 ? 'OK' : 'ERR' ?>
                                        </span>
                                    </td>
                                    <td><?= htmlspecialchars($entry['username'] ?? 'System') ?></td>
                                </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>
        </div>
    </div>

    <div class="dashboard-card">
        <div class="card-header">
            <h2><i class="fas fa-question-circle"></i> Quick Commands</h2>
        </div>
        <div class="card-body">
            <div class="quick-commands">
                <button class="quick-cmd" onclick="runQuickCmd('uptime')">
                    <i class="fas fa-clock"></i> uptime
                </button>
                <button class="quick-cmd" onclick="runQuickCmd('free -h')">
                    <i class="fas fa-memory"></i> free -h
                </button>
                <button class="quick-cmd" onclick="runQuickCmd('df -h')">
                    <i class="fas fa-hdd"></i> df -h
                </button>
                <button class="quick-cmd" onclick="runQuickCmd('top -bn1 | head -20')">
                    <i class="fas fa-chart-bar"></i> top
                </button>
                <button class="quick-cmd" onclick="runQuickCmd('ps aux --sort=-%cpu | head -20')">
                    <i class="fas fa-tasks"></i> ps aux
                </button>
                <button class="quick-cmd" onclick="runQuickCmd('who')">
                    <i class="fas fa-users"></i> who
                </button>
                <button class="quick-cmd" onclick="runQuickCmd('netstat -tulpn 2>/dev/null || ss -tulpn')">
                    <i class="fas fa-network-wired"></i> netstat
                </button>
                <button class="quick-cmd" onclick="runQuickCmd('systemctl list-units --type=service --state=running')">
                    <i class="fas fa-cogs"></i> services
                </button>
                <button class="quick-cmd" onclick="runQuickCmd('tail -n 50 /var/log/syslog 2>/dev/null || tail -n 50 /var/log/messages')">
                    <i class="fas fa-file-alt"></i> syslog
                </button>
                <button class="quick-cmd" onclick="runQuickCmd('last -n 20')">
                    <i class="fas fa-history"></i> last
                </button>
            </div>
        </div>
    </div>
</div>

<script>
const serverId = <?= $server['id'] ?>;

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

const terminalInput = document.getElementById('terminalInput');
const terminalOutput = document.getElementById('terminalOutput');
const connectionStatus = document.getElementById('connectionStatus');

terminalInput.addEventListener('keydown', function(e) {
    if (e.key === 'Enter') {
        executeCommand();
    }
});

function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}

function executeCommand() {
    const command = terminalInput.value.trim();
    if (!command) return;

    appendTerminalLine(command, 'command');

    terminalInput.value = '';
    terminalInput.disabled = true;
    document.getElementById('executeBtn').disabled = true;

    updateStatus('executing', 'Executing...');

    fetch('/terminal/' + serverId + '/execute', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'X-CSRF-Token': getCsrfToken(),
        },
        body: 'command=' + encodeURIComponent(command) + '&_csrf_token=' + encodeURIComponent(getCsrfToken()),
    })
    .then(r => r.json())
    .then(data => {
        terminalInput.disabled = false;
        document.getElementById('executeBtn').disabled = false;
        terminalInput.focus();

        if (data.success) {
            if (data.output) {
                appendTerminalLine(data.output, 'output');
            }
            if (data.stderr) {
                appendTerminalLine(data.stderr, 'error');
            }
            updateStatus('connected', 'Connected');
        } else {
            appendTerminalLine(data.message || 'Command failed', 'error');
            updateStatus('error', 'Error');
        }

        const terminalBody = document.getElementById('terminalOutput');
        terminalBody.scrollTop = terminalBody.scrollHeight;
    })
    .catch(err => {
        terminalInput.disabled = false;
        document.getElementById('executeBtn').disabled = false;
        appendTerminalLine('Connection error: ' + err.message, 'error');
        updateStatus('error', 'Error');
    });
}

function appendTerminalLine(text, type) {
    const line = document.createElement('div');
    line.className = 'terminal-line terminal-' + type;
    if (type === 'command') {
        line.innerHTML = '<span class="terminal-prompt-inline">$</span> ' + escapeHtml(text);
    } else {
        line.innerHTML = '<pre>' + escapeHtml(text) + '</pre>';
    }
    terminalOutput.appendChild(line);
    terminalOutput.scrollTop = terminalOutput.scrollHeight;
}

function runQuickCmd(cmd) {
    terminalInput.value = cmd;
    executeCommand();
}

function clearTerminal() {
    terminalOutput.innerHTML = '';
}

function clearHistory() {
    if (!confirm('Clear all command history for this server?')) return;

    fetch('/terminal/' + serverId + '/clear-history', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'X-CSRF-Token': getCsrfToken(),
        },
        body: '_csrf_token=' + encodeURIComponent(getCsrfToken()),
    })
    .then(r => r.json())
    .then(data => {
        showToast(data.success ? 'success' : 'error', data.message);
        if (data.success) location.reload();
    });
}

function updateStatus(status, text) {
    const dot = connectionStatus.querySelector('.status-dot');
    dot.className = 'status-dot ' + status;
    connectionStatus.lastChild.textContent = ' ' + text;
}

terminalInput.focus();
</script>
