<?php
session_start();
if (!isset($_SESSION['auth']) || $_SESSION['auth'] !== true) {
    header("Location: login.php");
    exit;
}
?>
<!DOCTYPE html>
<html lang="cs">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>MC Dash ⛏️ // Nox Control</title>
    <style>
        :root {
            --bg: #050505;
            --card: #0d0d0e;
            --accent: #00f2ff;
            --accent-glow: rgba(0, 242, 255, 0.3);
            --text: #e0e0e0;
            --muted: #666;
            --green: #00ff88;
            --red: #ff4b2b;
        }

        body {
            background-color: var(--bg);
            color: var(--text);
            font-family: 'Inter', sans-serif;
            margin: 0;
            display: flex;
            flex-direction: column;
            align-items: center;
            padding: 40px 20px;
        }

        .dashboard {
            max-width: 1000px;
            width: 100%;
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
            gap: 20px;
        }

        header {
            width: 100%;
            max-width: 1000px;
            display: flex;
            justify-content: space-between;
            align-items: flex-end;
            margin-bottom: 40px;
            border-bottom: 1px solid #1a1a1a;
            padding-bottom: 20px;
        }

        .brand h1 { margin: 0; font-size: 2rem; letter-spacing: -1px; color: #fff; }
        .brand span { color: var(--accent); text-transform: uppercase; font-size: 0.8rem; letter-spacing: 2px; }

        .status-badge {
            display: flex;
            align-items: center;
            gap: 8px;
            padding: 6px 12px;
            border-radius: 20px;
            font-size: 0.8rem;
            font-weight: 600;
        }

        .status-online { background: rgba(0, 255, 136, 0.1); color: var(--green); border: 1px solid rgba(0, 255, 136, 0.2); }
        .status-offline { background: rgba(255, 75, 43, 0.1); color: var(--red); border: 1px solid rgba(255, 75, 43, 0.2); }

        .card { background: var(--card); border: 1px solid #1a1a1a; border-radius: 16px; padding: 24px; }
        .card h2 { margin: 0 0 15px 0; font-size: 0.9rem; text-transform: uppercase; color: var(--muted); }

        .console {
            grid-column: 1 / -1;
            background: #000;
            border-radius: 12px;
            border: 1px solid #1a1a1a;
            padding: 20px;
            font-family: 'JetBrains Mono', monospace;
            font-size: 0.85rem;
            height: 450px;
            overflow-y: auto;
            display: flex;
            flex-direction: column;
            color: #ccc;
            white-space: pre-wrap;
            box-shadow: inset 0 0 10px rgba(0,0,0,0.5);
        }

        .console div {
            margin-bottom: 2px;
            line-height: 1.4;
            border-left: 2px solid transparent;
            padding-left: 8px;
        }

        .console .info { color: #80cbc4; }
        .console .warn { color: #fff176; border-left-color: #fbc02d; }
        .console .error { color: #ff8a65; border-left-color: #d84315; }

        .stat-card {
            background: var(--card);
            border: 1px solid #1a1a1a;
            border-radius: 16px;
            padding: 20px;
            text-align: center;
        }

        .stat-value {
            font-size: 1.8rem;
            font-weight: 800;
            color: var(--accent);
            display: block;
        }

        .stat-label {
            font-size: 0.7rem;
            color: var(--muted);
            text-transform: uppercase;
            letter-spacing: 1px;
        }

        .backup-section {
            grid-column: 1 / -1;
            background: var(--card);
            border: 1px solid #1a1a1a;
            border-radius: 16px;
            padding: 24px;
            margin-top: 10px;
        }

        .backup-list {
            display: grid;
            grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
            gap: 15px;
            margin-top: 15px;
        }

        .backup-item {
            background: #111;
            border: 1px solid #222;
            padding: 15px;
            border-radius: 12px;
            display: flex;
            flex-direction: column;
            gap: 8px;
        }

        .backup-info { font-size: 0.85rem; color: #888; }
        .backup-name { font-weight: 600; color: #fff; font-size: 0.9rem; overflow: hidden; text-overflow: ellipsis; }

        .input-group {
            grid-column: 1 / -1;
            display: flex;
            gap: 10px;
            margin-top: 10px;
        }

        input[type="text"] {
            flex: 1;
            background: #111;
            border: 1px solid #222;
            padding: 12px;
            border-radius: 8px;
            color: #fff;
            outline: none;
        }

        input[type="text"]:focus { border-color: var(--accent); }

        .btn {
            padding: 10px 20px;
            border-radius: 8px;
            border: none;
            cursor: pointer;
            font-weight: 600;
            transition: 0.2s;
        }

        .btn-primary { background: var(--accent); color: #000; }
        .btn-red { background: var(--red); color: #fff; }
        .btn-green { background: var(--green); color: #000; }
        .btn:hover { opacity: 0.8; transform: translateY(-1px); }

        .player-item { padding: 8px 0; border-bottom: 1px solid #1a1a1a; font-size: 0.9rem; }
        .logout { color: var(--muted); text-decoration: none; font-size: 0.8rem; margin-top: 20px; }
        .logout:hover { color: var(--red); }
    </style>
</head>
<body>
    <header>
        <div class="brand">
            <span>Server Control</span>
            <h1>MC.FUSHIFT.FUN ⛏️</h1>
        </div>
        <div id="statusBadge" class="status-badge status-offline">Offline</div>
    </header>

    <div class="dashboard">
        <div class="card">
            <h2>Server Management</h2>
            <div style="display: flex; gap: 10px; flex-wrap: wrap;">
                <button class="btn btn-green" onclick="action('start')">START SERVER</button>
                <button class="btn btn-red" onclick="action('stop')">STOP SERVER</button>
                <button class="btn btn-primary" style="background:#5c6bc0; color:#fff;" onclick="action('restart')">RESTART</button>
            </div>
            <div style="margin-top: 15px; display: flex; gap: 10px;">
                <button class="btn" style="background:#424242; color:#fff;" onclick="action('backup')">CREATE BACKUP</button>
            </div>
        </div>

        <div class="card">
            <h2>Quick Actions</h2>
            <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 10px;">
                <button class="btn btn-primary" onclick="sendCmd('list')">List Players</button>
                <button class="btn btn-primary" onclick="sendCmd('tps')">Check TPS</button>
                <button class="btn btn-primary" onclick="sendCmd('save-all')">Save World</button>
                <button class="btn btn-primary" onclick="sendCmd('version')">Version Info</button>
            </div>
        </div>

        <div class="stat-card">
            <span class="stat-label">Online Status</span>
            <strong id="statusText" class="stat-value">OFFLINE</strong>
        </div>

        <div class="stat-card">
            <span class="stat-label">Players Online</span>
            <strong id="playerCount" class="stat-value">0 / 20</strong>
        </div>

        <div class="console" id="console">
            <div>Initializing Nox Terminal...</div>
        </div>

        <div class="backup-section">
            <h2 style="margin:0; font-size:1rem; color:var(--muted); text-transform:uppercase;">Backup Management</h2>
            <div id="backupList" class="backup-list">
                <div class="backup-item">Scanning for backups...</div>
            </div>
        </div>

        <div class="input-group">
            <input type="text" id="cmdInput" placeholder="Zadej příkaz do konzole..." onkeydown="if(event.key==='Enter') sendCmd()">
            <button class="btn btn-primary" onclick="sendCmd()">SEND</button>
        </div>
    </div>

    <a href="login.php?logout=1" class="logout" onclick="return confirm('Odhlásit?')">Secure Logout</a>

    <script>
        async function update() {
            try {
                const res = await fetch('stats.php');
                const data = await res.json();
                
                const badge = document.getElementById('statusBadge');
                const statusText = document.getElementById('statusText');
                
                if (data.online) {
                    badge.className = 'status-badge status-online';
                    badge.textContent = 'Online';
                    statusText.textContent = 'RUNNING';
                    statusText.style.color = 'var(--green)';
                } else {
                    badge.className = 'status-badge status-offline';
                    badge.textContent = 'Offline';
                    statusText.textContent = 'OFFLINE';
                    statusText.style.color = 'var(--red)';
                }

                const consoleEl = document.getElementById('console');
                const lines = data.log ? data.log.split('\n') : ['No logs available'];
                
                consoleEl.innerHTML = lines.map(line => {
                    let type = 'info';
                    if (line.includes('WARN')) type = 'warn';
                    if (line.includes('ERROR')) type = 'error';
                    return `<div class="${type}">${line}</div>`;
                }).join('');
                
                // Auto-scroll to bottom
                consoleEl.scrollTop = consoleEl.scrollHeight;

                document.getElementById('playerCount').textContent = (data.players ? data.players.length : 0) + ' / 20';

                // Update Backup List
                const bList = document.getElementById('backupList');
                if (data.backups && data.backups.length > 0) {
                    bList.innerHTML = data.backups.map(b => `
                        <div class="backup-item">
                            <span class="backup-name">${b.name}</span>
                            <div class="backup-info">
                                📅 ${b.date}<br>
                                📦 ${b.size}
                            </div>
                            <button class="btn" style="background:#424242; color:#fff; font-size:0.7rem; padding:5px;" onclick="restore('${b.name}')">RESTORE THIS</button>
                        </div>
                    `).join('');
                } else {
                    bList.innerHTML = '<div class="backup-info">No backups found.</div>';
                }

            } catch (e) { console.error(e); }
        }

        async function restore(filename) {
            if (!confirm(`VAROVÁNÍ: Obnovením zálohy '${filename}' dojde ke smazání aktuálního světa! Server bude vypnut. Pokračovat?`)) return;
            
            const badge = document.getElementById('statusBadge');
            badge.textContent = 'RESTORING...';
            badge.className = 'status-badge status-offline';

            await fetch('cmd.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ action: 'restore', file: filename })
            });
            
            alert('Obnova dokončena. Nyní můžete server znovu zapnout.');
            update();
        }

        async function action(type) {
            if (type === 'restart' && !confirm('Opravdu restartovat server?')) return;
            await fetch('cmd.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ action: type })
            });
            setTimeout(update, 1000);
        }

        async function sendCmd(forcedCmd = null) {
            const input = document.getElementById('cmdInput');
            const cmd = forcedCmd || input.value;
            if(!cmd) return;
            await fetch('cmd.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ action: 'cmd', command: cmd })
            });
            if (!forcedCmd) input.value = '';
            setTimeout(update, 500);
        }

        setInterval(update, 3000);
        update();
    </script>
</body>
</html>
