<?php
// CONFIG
$vlcStatusUrl = "http://:vlcpass123@0.0.0.0:8767/requests/status.json";
$icecastStream = "https://floofradio.novafurry.win/floof";
if (isset($_GET['type']) && $_GET['type'] === 'cover') {
    header('Content-Type: image/jpeg');

    $url = "http://novanas.local:8767/art?timestamp=" . time();
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_USERPWD, ":vlcpass123");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);

    $data = curl_exec($ch);
    curl_close($ch);

    if ($data) {
        echo $data;
    } else {
        readfile('placeholder.jpg');
    }
    exit;
}

// --- Handle metadata proxy ---
if (isset($_GET['type']) && $_GET['type'] === 'metadata') {
    header('Content-Type: application/json');
    $meta = @file_get_contents($vlcStatusUrl);
    if ($meta === false) {
        echo json_encode([
            'title' => 'Unknown',
            'artist' => '',
            'artwork_url' => ''
        ]);
    } else {
        echo $meta;
    }
    exit;
}

// --- Default: render dashboard page ---
?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>the gaydio</title>
<style>
    body { font-family: Arial; background:#121212; color:#f5f5f5; display:flex; justify-content:center; padding:30px; }
    .player-card { background:#1e1e1e; padding:20px; border-radius:12px; text-align:center; max-width:320px; box-shadow:0 0 15px rgba(0,0,0,0.5);  min-width: 300px;}
    .cover-art { width:100%; border-radius:8px; margin-bottom:15px; aspect-ratio: 1 / 1; object-fit: cover}
    .song-info { margin-bottom:15px; }
    .song-title { font-size:18px; font-weight:bold; margin:0; }
    .song-artist { font-size:14px; color:#ccc; margin:0; }
    audio { width:100%; border-radius:8px; outline:none; }
</style>
</head>
<div class="player-card">
    <img id="cover" class="cover-art" src="" alt="Cover Art">
    <div class="song-info">
        <p id="title" class="song-title">Loading...</p>
        <p id="artist" class="song-artist"></p>
    </div>
    <audio controls autoplay>
        <source src="<?= htmlspecialchars($icecastStream) ?>" type="audio/mpeg">
        Your browser does not support the audio element.
    </audio>
</div>

<script>
// Fetch metadata every 5s and update page
async function updateMetadata() {
    try {
        const res = await fetch('?type=metadata');
        const data = await res.json();
        const meta = data.information?.category?.meta || {};

        document.getElementById('title').textContent = meta.title || 'Unknown';
        document.getElementById('artist').textContent = meta.artist || '';

        document.getElementById('cover').src = '?type=cover&stamp='+String(Date.now());
    } catch(e) {
        console.error('Failed to fetch metadata', e);
    }
}

updateMetadata();
setInterval(updateMetadata, 5000);
</script>
</body></html>
