
<?php
if (!function_exists('smurf_get_stream_config')) {
function smurf_get_stream_config(): array {
    return [
        'server_ip' => 'cr3.broadcasturself.com',
        'server_port' => '1982',
        'admin_user' => 'Admin',
        'admin_password' => '71yn3p8eyr6RjY8u',
        'mount_main' => '/stream',
        'mount_auto' => '/autodj',
        'mount_backup' => '/autodj2',
        'listen_url' => 'http://cr3.broadcasturself.com:1982/stream',
    ];
}
}

if (!function_exists('smurf_fetch_icecast_xml')) {
function smurf_fetch_icecast_xml(): string {
    $cfg = smurf_get_stream_config();
    $url = 'http://' . rawurlencode($cfg['admin_user']) . ':' . rawurlencode($cfg['admin_password']) . '@' .
           $cfg['server_ip'] . ':' . trim((string)$cfg['server_port']) . '/admin/stats.xml';
    $ctx = stream_context_create(['http'=>['timeout'=>6, 'ignore_errors'=>true]]);
    $raw = @file_get_contents($url, false, $ctx);
    return is_string($raw) ? $raw : '';
}
}

if (!function_exists('smurf_extract_title_from_xml')) {
function smurf_extract_title_from_xml(string $xml, string $mount): string {
    if ($xml === '' || $mount === '') return '';
    $mountTag = '<source mount="' . $mount . '">';
    $pos = strpos($xml, $mountTag);
    if ($pos === false) return '';
    $slice = substr($xml, $pos);
    $start = strpos($slice, '<x_icy_title>');
    $end   = strpos($slice, '</x_icy_title>');
    if ($start === false || $end === false || $end <= $start) return '';
    $val = substr($slice, $start + 13, $end - ($start + 13));
    return trim(html_entity_decode(strip_tags($val), ENT_QUOTES, 'UTF-8'));
}
}

if (!function_exists('smurf_get_nowplaying_title')) {
function smurf_get_nowplaying_title(): string {
    $xml = smurf_fetch_icecast_xml();
    if ($xml === '') return '';
    $cfg = smurf_get_stream_config();
    foreach ([$cfg['mount_main'], $cfg['mount_auto'], $cfg['mount_backup']] as $mount) {
        $t = smurf_extract_title_from_xml($xml, $mount);
        if ($t !== '') return $t;
    }
    return '';
}
}

if (!function_exists('smurf_top50_touch')) {
function smurf_top50_touch(string $storeFile, string $stateFile): string {
    $title = smurf_get_nowplaying_title();
    if ($title === '') return '';
    $store = [];
    if (file_exists($storeFile)) {
        $store = json_decode((string)file_get_contents($storeFile), true);
        if (!is_array($store)) $store = [];
    }
    $state = [];
    if (file_exists($stateFile)) {
        $state = json_decode((string)file_get_contents($stateFile), true);
        if (!is_array($state)) $state = [];
    }
    $last = trim((string)($state['last_title'] ?? ''));
    if (!isset($store[$title]) || !is_array($store[$title])) {
        $store[$title] = ['title'=>$title,'count'=>0,'first_seen'=>date('Y-m-d H:i:s'),'last_seen'=>date('Y-m-d H:i:s')];
    }
    if ($last !== $title) {
        $store[$title]['count'] = (int)($store[$title]['count'] ?? 0) + 1;
        $store[$title]['last_seen'] = date('Y-m-d H:i:s');
        $state['last_title'] = $title;
        $state['last_seen_ts'] = time();
        @file_put_contents($storeFile, json_encode($store, JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
        @file_put_contents($stateFile, json_encode($state, JSON_PRETTY_PRINT|JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE));
    }
    return $title;
}
}

if (!function_exists('smurf_top50_sorted')) {
function smurf_top50_sorted(string $storeFile): array {
    $store = [];
    if (file_exists($storeFile)) {
        $store = json_decode((string)file_get_contents($storeFile), true);
        if (!is_array($store)) $store = [];
    }
    $rows = array_values(array_filter($store, 'is_array'));
    usort($rows, function($a,$b){
        $ca = (int)($a['count'] ?? 0);
        $cb = (int)($b['count'] ?? 0);
        if ($ca === $cb) return strcmp((string)($a['title'] ?? ''), (string)($b['title'] ?? ''));
        return $cb <=> $ca;
    });
    return array_slice($rows, 0, 50);
}
}
?>
