<?php
// --- Konfiguration ---
$logFile = 'history.json';
$entriesPerPage = 25;

// --- Logik: Speicherung ---
if (isset($_GET['log_action']) && $_GET['log_action'] === 'save') {
    $newEntry = [
        'time' => date('d.m.Y H:i:s'),
        'artist' => $_GET['artist'] ?? 'Unbekannt',
        'title' => $_GET['title'] ?? 'Unbekannt',
        'ip' => $_SERVER['REMOTE_ADDR']
    ];

    $history = file_exists($logFile) ? json_decode(file_get_contents($logFile), true) : [];
    if (!is_array($history)) $history = [];
    array_unshift($history, $newEntry); 
    $history = array_slice($history, 0, 200); // Speicherlimit 200
    file_put_contents($logFile, json_encode($history));
    exit;
}

// --- Logik: Auslesen & Pagination ---
$allHistory = file_exists($logFile) ? json_decode(file_get_contents($logFile), true) : [];
if (!is_array($allHistory)) $allHistory = [];

$totalEntries = count($allHistory);
$totalPages = ceil($totalEntries / $entriesPerPage);
$currentPage = isset($_GET['page']) ? (int)$_GET['page'] : 1;
if ($currentPage < 1) $currentPage = 1;
if ($currentPage > $totalPages && $totalPages > 0) $currentPage = $totalPages;

$offset = ($currentPage - 1) * $entriesPerPage;
$displayHistory = array_slice($allHistory, $offset, $entriesPerPage);
?>
<!DOCTYPE html>
<html lang="de">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Hotstarradio - Admin Panel</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha1/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.3/font/bootstrap-icons.css">
    <style>
        /* Erzwungene Schriftfarbe #e0e0e0 für absolut alle Elemente */
        * {
            color: #e0e0e0 !important;
        }

        body { 
            background-color: #121212; 
            padding: 20px; 
            font-family: sans-serif;
        }

        .card { 
            background-color: #1e1e1e; 
            border: 1px solid #333; 
            border-radius: 12px; 
        }

        .card-header { 
            background: linear-gradient(45deg, #0d6efd, #0043a8); 
            border: none; 
        }

        .form-control { 
            background-color: #2b2b2b; 
            border: 1px solid #444; 
        }

        .form-control:focus { 
            background-color: #333; 
            border-color: #0d6efd; 
            box-shadow: none; 
        }

        /* Platzhalter etwas dunkler, damit man sieht dass es leer ist */
        .form-control::placeholder { 
            color: #777 !important; 
        }

        .table { 
            border-color: #333; 
        }

        .table-hover tbody tr:hover { 
            background-color: #252525; 
        }

        /* Pagination Styling */
        .pagination .page-link { 
            background-color: #2b2b2b; 
            border-color: #444; 
        }

        .pagination .page-item.active .page-link { 
            background-color: #0d6efd; 
            border-color: #0d6efd; 
        }

        .pagination .page-item.disabled .page-link {
            background-color: #1a1a1a;
            border-color: #333;
            opacity: 0.5;
        }

        code { 
            background-color: #2b2b2b; 
            padding: 2px 5px; 
            border-radius: 4px; 
        }
    </style>
</head>
<body>

<div class="container" style="max-width: 1000px;">
    <div class="card shadow-lg mb-5">
        <div class="card-header text-center py-3">
            <h4 class="mb-0"><i class="bi bi-broadcast"></i> Metadata Control</h4>
        </div>
        <div class="card-body p-4">
            <div id="report"></div>
            <div class="row">
                <div class="col-md-6 mb-3">
                    <label class="form-label small fw-bold text-uppercase">Interpret</label>
                    <input type="text" class="form-control" id="artist" placeholder="z.B. Depeche Mode">
                </div>
                <div class="col-md-6 mb-3">
                    <label class="form-label small fw-bold text-uppercase">Songtitel</label>
                    <input type="text" class="form-control" id="title" placeholder="z.B. Enjoy the Silence">
                </div>
            </div>
            <button type="button" id="updateBtn" class="btn btn-primary btn-lg w-100 mt-2" onclick="sendMetadata()">
                <i class="bi bi-send-fill"></i> Update senden
            </button>
        </div>
    </div>

    <div class="card shadow-lg">
        <div class="card-header bg-dark d-flex justify-content-between align-items-center">
            <h5 class="mb-0 small text-uppercase"><i class="bi bi-clock-history"></i> Letzte Updates</h5>
            <span class="badge bg-secondary">Seite <?php echo $currentPage; ?> von <?php echo max(1, $totalPages); ?></span>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover mb-0" id="historyTable">
                    <thead class="table-dark">
                        <tr style="font-size: 0.85rem;">
                            <th class="ps-3">Zeitpunkt</th>
                            <th>Interpret / Titel</th>
                            <th class="text-end pe-3">IP-Adresse</th>
                        </tr>
                    </thead>
                    <tbody style="font-size: 0.9rem;">
                        <?php if (empty($displayHistory)): ?>
                            <tr><td colspan="3" class="text-center py-4">Noch keine Einträge vorhanden.</td></tr>
                        <?php else: ?>
                            <?php foreach ($displayHistory as $entry): ?>
                            <tr>
                                <td class="ps-3"><?php echo $entry['time']; ?></td>
                                <td>
                                    <strong><?php echo htmlspecialchars($entry['artist']); ?></strong><br>
                                    <span><?php echo htmlspecialchars($entry['title']); ?></span>
                                </td>
                                <td class="text-end pe-3"><code><?php echo $entry['ip']; ?></code></td>
                            </tr>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </tbody>
                </table>
            </div>
        </div>
        
        <?php if ($totalPages > 1): ?>
        <div class="card-footer d-flex justify-content-center py-3">
            <nav>
                <ul class="pagination mb-0">
                    <li class="page-item <?php if($currentPage <= 1) echo 'disabled'; ?>">
                        <a class="page-link" href="?page=<?php echo $currentPage - 1; ?>">&laquo;</a>
                    </li>
                    <?php for($i = 1; $i <= $totalPages; $i++): ?>
                        <li class="page-item <?php if($currentPage == $i) echo 'active'; ?>">
                            <a class="page-link" href="?page=<?php echo $i; ?>"><?php echo $i; ?></a>
                        </li>
                    <?php endfor; ?>
                    <li class="page-item <?php if($currentPage >= $totalPages) echo 'disabled'; ?>">
                        <a class="page-link" href="?page=<?php echo $currentPage + 1; ?>">&raquo;</a>
                    </li>
                </ul>
            </nav>
        </div>
        <?php endif; ?>
    </div>
</div>

<script>
const API_KEY = "65681e24b91a6bcd:3907a5e06dba57d44850049da1b7f190";
const STATION_ID = "4";
const BASE_URL = "https://hotstarradio.com:9443";

function sendMetadata() {
    const artist = document.getElementById("artist").value.trim();
    const title = document.getElementById("title").value.trim();
    const btn = document.getElementById("updateBtn");
    
    if (!artist || !title) return alert("Bitte Felder ausfüllen.");

    btn.disabled = true;
    btn.innerHTML = 'Sende...';

    const url = `${BASE_URL}/api/station/${STATION_ID}/nowplaying/update?api_key=${API_KEY}&artist=${encodeURIComponent(artist)}&title=${encodeURIComponent(title)}`;

    const xhr = new XMLHttpRequest();
    xhr.open("POST", url);
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status === 200) {
                fetch(`?log_action=save&artist=${encodeURIComponent(artist)}&title=${encodeURIComponent(title)}`)
                .then(() => {
                    // Nach Erfolg immer auf Seite 1 springen, um das neue Update zu sehen
                    window.location.href = '?page=1';
                });
            } else {
                alert("Fehler beim Update!");
                btn.disabled = false;
                btn.innerHTML = 'Update senden';
            }
        }
    };
    xhr.send();
}
</script>
</body>
</html>