<?php
// --- Konfiguration ---
$logFile = __DIR__ . '/history.json';
$defaultImage = 'album_base.jpg';
$entriesPerPage = 5;
$apiKey = "65681e24b91a6bcd:3907a5e06dba57d44850049da1b7f190";
$stationId = 4;
$baseUrl = "https://hotstarradio.com:9443";

// --- PHP Logik: Cover suchen & an Azura schicken ---
if (isset($_GET['log_action']) && $_GET['log_action'] === 'save') {
    $artist = $_GET['artist'] ?? 'Unbekannt';
    $title  = $_GET['title'] ?? 'Unbekannt';

    // 1. iTunes Suche
    $searchTerm = urlencode($artist . " " . $title);
    $itunesUrl = "https://itunes.apple.com/search?term=$searchTerm&entity=song&limit=1";
    $itunesData = @json_decode(file_get_contents($itunesUrl), true);
    
    $artworkUrl = "";
    if (!empty($itunesData['results'][0]['artworkUrl100'])) {
        $artworkUrl = str_replace('100x100bb.jpg', '600x600bb.jpg', $itunesData['results'][0]['artworkUrl100']);
    }
    $finalCoverPath = (!empty($artworkUrl)) ? $artworkUrl : $defaultImage;

    // 2. Bild-Upload an AzuraCast /art (Multipart-Form-Data)
    $imageData = @file_get_contents($finalCoverPath);
    if ($imageData) {
        $tempFile = __DIR__ . '/temp_art.jpg';
        file_put_contents($tempFile, $imageData);

        $ch = curl_init("$baseUrl/api/station/$stationId/art");
        curl_setopt($ch, CURLOPT_HTTPHEADER, ["Authorization: Bearer $apiKey"]);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, ['art' => new CURLFile($tempFile, 'image/jpeg', 'art.jpg')]);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_exec($ch);
        curl_close($ch);
        @unlink($tempFile);
    }

    // 3. History Log
    $history = file_exists($logFile) ? json_decode(file_get_contents($logFile), true) : [];
    if (!is_array($history)) $history = [];
    array_unshift($history, [
        'time' => date('d.m.Y H:i:s'), 
        'artist' => $artist, 
        'title' => $title, 
        'ip' => $_SERVER['REMOTE_ADDR'], 
        'cover' => $finalCoverPath
    ]);
    file_put_contents($logFile, json_encode(array_slice($history, 0, 200)));
    exit;
}

// History laden & 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;
$displayHistory = array_slice($allHistory, ($currentPage - 1) * $entriesPerPage, $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>
        * { 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; }
        .form-control::placeholder { color: #777 !important; }
        .table { border-color: #333; }
        .table-hover tbody tr:hover { background-color: #252525; }
        .pagination .page-link { background-color: #2b2b2b; border-color: #444; }
        .pagination .page-item.active .page-link { background-color: #0d6efd; border-color: #0d6efd; }
        .cover-preview { width: 40px; height: 40px; border-radius: 4px; object-fit: cover; border: 1px solid #444; }
    </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 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="sendAll()">
                <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; ?></span>
        </div>
        <div class="card-body p-0">
            <div class="table-responsive">
                <table class="table table-hover mb-0">
                    <thead class="table-dark">
                        <tr style="font-size: 0.85rem;">
                            <th class="ps-3">Zeitpunkt</th>
                            <th>Cover</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="4" class="text-center py-4">Noch keine Einträge vorhanden.</td></tr>
                        <?php else: ?>
                            <?php foreach ($displayHistory as $entry): ?>
                            <tr>
                                <td class="ps-3" style="vertical-align: middle;"><?php echo $entry['time']; ?></td>
                                <td style="vertical-align: middle;">
                                    <img src="<?php echo $entry['cover']; ?>" class="cover-preview" onerror="this.src='album_base.jpg'">
                                </td>
                                <td style="vertical-align: middle;">
                                    <strong><?php echo htmlspecialchars($entry['artist']); ?></strong><br>
                                    <span><?php echo htmlspecialchars($entry['title']); ?></span>
                                </td>
                                <td class="text-end pe-3" style="vertical-align: middle;"><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>
function sendAll() {
    const artist = document.getElementById("artist").value.trim();
    const title = document.getElementById("title").value.trim();
    const btn = document.getElementById("updateBtn");
    
    if(!artist || !title) return;

    btn.disabled = true;
    btn.innerHTML = 'Sende Daten...';
    
    // 1. Text-Update an AzuraCast via Browser (XHR)
    const url = `<?php echo $baseUrl; ?>/api/station/<?php echo $stationId; ?>/nowplaying/update?api_key=<?php echo $apiKey; ?>&artist=${encodeURIComponent(artist)}&title=${encodeURIComponent(title)}`;
    const xhr = new XMLHttpRequest();
    xhr.open("POST", url);
    xhr.onreadystatechange = function() {
        if(xhr.readyState === 4) {
            // 2. Cover & Log via PHP (Serverseitig)
            fetch(`?log_action=save&artist=${encodeURIComponent(artist)}&title=${encodeURIComponent(title)}`)
            .then(() => { 
                window.location.href = '?page=1'; 
            });
        }
    };
    xhr.send();
}
</script>
</body>
</html>