<?php

/*

ET-Chat Copyright by SEDesign | ET-Chat v3.x.x Lizenz: CCPL | Autor: Evgeni Tcherkasski (info@s-e-d.de)

ET-Chat_T-FISH-MOD Weiterentwicklung des ET-Chats durch Tommy (Thomas Kuhn) und Harlekin (Bernd Witte)

Die Weiterentwicklungen, Optimierungen und Ergänzungen am Code sind das geistige Eigentum von Tommy (Thomas Kuhn) und Harlekin (Bernd Witte).

*/

$CACHE_DIR  = __DIR__ . '/cache';
$CACHE_TIME = 15; // Sekunden Cache

if (!is_dir($CACHE_DIR)) {
    mkdir($CACHE_DIR, 0777, true);
}

function getCacheFile($url) {
    global $CACHE_DIR;
    return $CACHE_DIR . '/title_' . md5($url) . '.cache';
}

function getCachedTitle($url) {
    global $CACHE_TIME;
    $file = getCacheFile($url);

    if (file_exists($file)) {
        $data = json_decode(file_get_contents($file), true);
        if ($data && time() - $data['time'] < $CACHE_TIME) {
            return $data['title'];
        }
    }
    return null;
}

function setCachedTitle($url, $title) {
    $file = getCacheFile($url);
    $data = [
        'time'  => time(),
        'title' => $title
    ];
    file_put_contents($file, json_encode($data));
}

function getStreamTitle(string $url): string
{
    $parsed = parse_url($url);
    $host   = $parsed['host'] ?? '';
    $scheme = $parsed['scheme'] ?? 'http';
    $port   = $parsed['port'] ?? 80;

    if (empty($host)) {
        return "Ungültiger Host";
    }

    // Cache zuerst
    $cached = getCachedTitle($url);
    if ($cached !== null) {
        return $cached;
    }

    // 🔹 Laut.fm
    if (str_contains($host, 'laut.fm')) {
        $path = trim($parsed['path'] ?? '', '/');
        if (!empty($path)) {
            $station = explode('/', $path)[0];
            $lautUrl = "https://api.laut.fm/station/{$station}/current_song";

            $json = @file_get_contents($lautUrl, false, stream_context_create([
                'http' => ['timeout' => 2]
            ]));

            if ($json) {
                $data = json_decode($json, true);
                if (isset($data['title'], $data['artist']['name'])) {
                    $title = $data['artist']['name'] . " - " . $data['title'];
                    setCachedTitle($url, $title);
                    return $title;
                }
            }
        }
    }

    // 🔹 Shoutcast /currentsong
    $shoutcastCurrent = "{$scheme}://{$host}:{$port}/currentsong";
    $title = @file_get_contents($shoutcastCurrent, false, stream_context_create([
        'http' => ['timeout' => 2]
    ]));

    if ($title && stripos($title, 'html') === false) {
        $title = trim(substr($title, 0, 200));
        setCachedTitle($url, $title);
        return $title;
    }

    // 🔹 Icecast /status-json.xsl
    $statusUrl = "{$scheme}://{$host}:{$port}/status-json.xsl";
    $json = @file_get_contents($statusUrl, false, stream_context_create([
        'http' => ['timeout' => 2]
    ]));

    if ($json && strlen($json) < 20000) {
        $data = json_decode($json, true);

        if (!empty($data['icestats']['source'])) {
            $source = $data['icestats']['source'];

            if (isset($source['title'])) {
                $title = $source['title'];
                setCachedTitle($url, $title);
                return $title;
            }

            if (is_array($source)) {
                foreach ($source as $mount) {
                    if (isset($mount['title'])) {
                        $title = $mount['title'];
                        setCachedTitle($url, $title);
                        return $title;
                    }
                }
            }
        }
    }

    return "Titel nicht verfügbar";
}

if (isset($_GET['url'])) {
    echo getStreamTitle(urldecode($_GET['url']));
} else {
    echo "Keine Stream-URL angegeben";
}