<?php
function ugfx_read_json(string $path, $default = []) {
    if (!file_exists($path)) return $default;
    $data = json_decode(file_get_contents($path), true);
    return is_array($data) ? $data : $default;
}

function ugfx_write_json(string $path, $data): bool {
    $dir = dirname($path);
    if (!is_dir($dir)) mkdir($dir, 0775, true);
    return (bool) file_put_contents($path, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
}

function ugfx_asset(string $path): string {
    return 'assets/' . ltrim($path, '/');
}

function ugfx_vendor_asset(string $localPath, string $cdnUrl, string $prefix = ''): string {
    $normalized = ltrim($localPath, '/');
    $absolute = dirname(__DIR__) . '/' . $normalized;
    if (file_exists($absolute)) {
        return $prefix . $normalized;
    }
    return $cdnUrl;
}

function ugfx_is_active(string $page, string $current): string {
    return $page === $current ? 'active' : '';
}

function ugfx_slugify(string $text): string {
    $text = strtolower(trim($text));
    $text = preg_replace('/[^a-z0-9]+/', '-', $text);
    return trim($text ?? '', '-') ?: 'page';
}

function ugfx_strlen(string $text): int {
    return function_exists('mb_strlen') ? mb_strlen($text) : strlen($text);
}

function ugfx_substr(string $text, int $start, ?int $length = null): string {
    if (function_exists('mb_substr')) {
        return $length === null ? mb_substr($text, $start) : mb_substr($text, $start, $length);
    }
    return $length === null ? substr($text, $start) : substr($text, $start, $length);
}

function ugfx_excerpt(string $text, int $length = 180): string {
    $text = trim(strip_tags($text));
    return ugfx_strlen($text) > $length ? ugfx_substr($text, 0, $length - 1) . '…' : $text;
}

function ugfx_sort_items_by_date_desc(array $items): array {
    usort($items, function ($a, $b) {
        return strtotime((string)($b['start'] ?? $b['date'] ?? '')) <=> strtotime((string)($a['start'] ?? $a['date'] ?? ''));
    });
    return $items;
}

function ugfx_get_news(int $limit = 6): array {
    global $ugfx;
    $items = ugfx_read_json($ugfx['storage']['news'], []);
    $items = array_values(array_filter($items, function ($item) { return ($item['published'] ?? 0) == 1; }));
    return array_slice($items, 0, $limit);
}

function ugfx_get_events(int $limit = 4): array {
    global $ugfx;
    $items = ugfx_read_json($ugfx['storage']['events'], []);
    $items = array_values(array_filter($items, function ($item) { return ($item['published'] ?? 0) == 1; }));
    $items = ugfx_sort_items_by_date_desc($items);
    return array_slice($items, 0, $limit);
}

function ugfx_get_djs(int $limit = 8): array {
    global $ugfx;
    return array_slice(ugfx_read_json($ugfx['storage']['djs'], []), 0, $limit);
}

function ugfx_get_top50(int $limit = 10): array {
    global $ugfx;
    $items = ugfx_read_json($ugfx['storage']['top50'], []);
    uasort($items, function ($a, $b) { return ($b['count'] ?? 0) <=> ($a['count'] ?? 0); });
    return array_slice($items, 0, $limit, true);
}

function ugfx_get_schedule(): array {
    global $ugfx;
    return ugfx_read_json($ugfx['storage']['schedule'], []);
}

function ugfx_get_friends(int $limit = 12): array {
    global $ugfx;
    return array_slice(ugfx_read_json($ugfx['storage']['friends'], []), 0, $limit);
}

function ugfx_get_pages(bool $publishedOnly = true): array {
    global $ugfx;
    $items = ugfx_read_json($ugfx['storage']['pages'], []);
    if ($publishedOnly) {
        $items = array_values(array_filter($items, function ($item) { return ($item['published'] ?? 0) == 1; }));
    }
    return $items;
}

function ugfx_get_page_by_slug(string $slug): ?array {
    foreach (ugfx_get_pages(false) as $page) {
        if (($page['slug'] ?? '') === $slug) {
            return $page;
        }
    }
    return null;
}

function ugfx_day_name(?int $timestamp = null): string {
    return date('l', $timestamp ?? time());
}

function ugfx_current_show(): array {
    $schedule = ugfx_get_schedule();
    $day = ugfx_day_name();
    $hour = (int) date('G');
    $current = $schedule[$day][$hour] ?? 'Underground FX Live';
    $next = $schedule[$day][($hour + 1) % 24] ?? 'Underground FX Live';
    return ['day' => $day, 'hour' => $hour, 'current' => $current, 'next' => $next];
}


function ugfx_merge_global_stats(array ...$sets): array {
    $merged = [
        'listeners' => 0,
        'listener_connections' => 0,
        'clients' => 0,
        'sources' => 0,
        'host' => '',
        'server_id' => '',
        'server_start' => '',
    ];
    foreach ($sets as $set) {
        if (!is_array($set)) continue;
        foreach (['listeners','listener_connections','clients','sources'] as $field) {
            if (isset($set[$field]) && (int)$set[$field] > (int)$merged[$field]) {
                $merged[$field] = (int)$set[$field];
            }
        }
        foreach (['host','server_id','server_start'] as $field) {
            if (($merged[$field] ?? '') === '' && trim((string)($set[$field] ?? '')) !== '') {
                $merged[$field] = trim((string)$set[$field]);
            }
        }
    }
    return $merged;
}

function ugfx_icecast_status(): array {
    static $cached = null;
    if ($cached !== null) {
        return $cached;
    }

    $cfg = ugfx_get_stream_config();
    $playerUrls = ugfx_get_player_urls();
    $cacheFile = __DIR__ . '/../data/icecast_stats_cache.json';
    $cacheTtl = 15;

    if (is_file($cacheFile) && (time() - (int)filemtime($cacheFile) <= $cacheTtl)) {
        $cachedData = json_decode((string)@file_get_contents($cacheFile), true);
        $cacheHasUsefulData = is_array($cachedData)
            && isset($cachedData['server_listeners'])
            && (
                (int)($cachedData['source_count'] ?? 0) > 0
                || !empty($cachedData['public_status_ok'])
                || !empty($cachedData['admin_status_ok'])
                || (int)($cachedData['server_listeners'] ?? 0) > 0
                || trim((string)($cachedData['title'] ?? '')) !== ''
            );
        $cacheLooksDead = $cacheHasUsefulData
            && (int)($cachedData['server_listeners'] ?? 0) <= 0
            && (int)($cachedData['current_listeners'] ?? 0) <= 0
            && trim((string)($cachedData['title'] ?? '')) !== '';
        if ($cacheHasUsefulData && !$cacheLooksDead) {
            return $cached = $cachedData;
        }
    }

    $show = ugfx_current_show();
    $fallback = [
        'ok' => false,
        'server_listeners' => 0,
        'current_listeners' => 0,
        'total_listener_connections' => 0,
        'title' => 'Underground FX Live',
        'artist' => $show['current'] ?? 'Underground FX Radio',
        'mount' => (string)($cfg['mount_auto'] ?? '/autodj'),
        'is_live' => false,
        'status' => 'LIVE',
        'stream_url' => $playerUrls['preferred'],
        'public_stream_url' => $playerUrls['public'],
        'direct_stream_url' => $playerUrls['direct'],
        'proxy_stream_url' => $playerUrls['proxy'],
    ];


    $publicXsl = ugfx_fetch_public_status_xsl();
    $parsedPublic = $publicXsl !== '' ? ugfx_parse_public_status_xsl($publicXsl) : ['global' => [], 'sources' => []];

    $needAdmin = false;
    if (empty($parsedPublic['sources'])) {
        $needAdmin = true;
    } else {
        $autoMount = (string)($cfg['mount_auto'] ?? '/autodj');
        $mainMount = (string)($cfg['mount_main'] ?? '/stream');
        $hasUseful = false;
        foreach (($parsedPublic['sources'] ?? []) as $src) {
            $mount = (string)($src['mount'] ?? '');
            $titleProbe = trim((string)($src['title'] ?? $src['x_icy_title'] ?? ''));
            if (($mount === $mainMount && (int)($src['listeners'] ?? 0) > 0) || ($mount === $autoMount && $titleProbe !== '')) {
                $hasUseful = true;
                break;
            }
        }
        $needAdmin = !$hasUseful;
    }

    $xml = '';
    $xsl = '';
    if ($needAdmin) {
        $xsl = ugfx_fetch_icecast_xsl();
        if ($xsl === '') {
            $xml = ugfx_fetch_icecast_xml();
        }
    }

    if ($xml === '' && $xsl === '' && $publicXsl === '') {
        if (is_file($cacheFile)) {
            $stale = json_decode((string)@file_get_contents($cacheFile), true);
            $staleIsUseful = is_array($stale)
                && (
                    (int)($stale['source_count'] ?? 0) > 0
                    || !empty($stale['public_status_ok'])
                    || !empty($stale['admin_status_ok'])
                    || (int)($stale['server_listeners'] ?? 0) > 0
                    || trim((string)($stale['title'] ?? '')) !== ''
                );
            if ($staleIsUseful) {
                $stale['ok'] = false;
                $stale['_warning'] = 'Icecast fetch failed (served stale cache)';
                return $cached = $stale;
            }
        }
        return $cached = $fallback;
    }

    $parsedXml = $xml !== '' ? ugfx_parse_icecast_data($xml) : ['global' => [], 'sources' => []];
    $parsedXsl = $xsl !== '' ? ugfx_parse_stats_xsl($xsl) : ['global' => [], 'sources' => []];

    $global = ugfx_merge_global_stats($parsedPublic['global'] ?? [], $parsedXsl['global'] ?? [], $parsedXml['global'] ?? []);
    $sources = ugfx_merge_icecast_sources(ugfx_merge_icecast_sources($parsedPublic['sources'] ?? [], $parsedXsl['sources'] ?? []), $parsedXml['sources'] ?? []);
    $active = ugfx_pick_preferred_source($sources) ?? [];

    $autoSource = null;
    foreach ($sources as $source) {
        if (($source['mount'] ?? '') === (string)$cfg['mount_auto']) {
            $autoSource = $source;
            break;
        }
    }

    $isLive = (($active['mount'] ?? '') === (string)$cfg['mount_main']) && (int)($active['listeners'] ?? 0) > 0;
    $rawTitle = trim((string)($active['title'] ?? $active['x_icy_title'] ?? ''));
    $artist = trim((string)($active['server_name'] ?? ''));

    if ($isLive) {
        $title = $rawTitle !== '' ? $rawTitle : 'Live DJ On Air';
        if ($artist === '') $artist = $show['current'] ?? 'Underground FX Live';
    } else {
        $fallbackTitle = trim((string)($autoSource['title'] ?? $autoSource['x_icy_title'] ?? ''));
        $title = $rawTitle !== '' ? $rawTitle : ($fallbackTitle !== '' ? $fallbackTitle : 'Underground FX Live');
        if ($artist === '') $artist = trim((string)($autoSource['server_name'] ?? 'Underground FX AutoDJ'));
        if ($artist === '') $artist = 'Underground FX AutoDJ';
    }

    $currentListeners = (int)($active['listeners'] ?? 0);
    $maxSourceListeners = 0;
    foreach ($sources as $sourceProbe) {
        $maxSourceListeners = max($maxSourceListeners, (int)($sourceProbe['listeners'] ?? 0));
    }
    $serverListeners = max(
        $currentListeners,
        (int)($autoSource['listeners'] ?? 0),
        $maxSourceListeners,
        (int)($global['listeners'] ?? 0)
    );
    if ($serverListeners <= 0 && $currentListeners > 0) {
        $serverListeners = $currentListeners;
    }
    $displayListeners = (int)($global['listener_connections'] ?? 0);
    if ($displayListeners <= 0) {
        $displayListeners = max(
            (int)($global['listeners'] ?? 0),
            $serverListeners,
            (int)($autoSource['listeners'] ?? 0),
            $currentListeners
        );
    }

    $data = [
        'ok' => true,
        'server_listeners' => $displayListeners,
        'current_listeners' => $currentListeners,
        'display_listeners' => $displayListeners,
        'total_listener_connections' => (int)($global['listener_connections'] ?? 0),
        'global_listeners' => (int)($global['listeners'] ?? 0),
        'public_status_ok' => ($publicXsl !== ''),
        'admin_status_ok' => ($xml !== '' || $xsl !== ''),
        'title' => $title,
        'artist' => $artist,
        'mount' => (string)($active['mount'] ?? ($cfg['mount_auto'] ?? '/autodj')),
        'display_show' => ($isLive ? ($show['current'] ?? 'LIVE DJ') : 'Underground FX AutoDJ'),
        'is_live' => $isLive,
        'status' => 'LIVE',
        'stream_url' => $playerUrls['preferred'],
        'public_stream_url' => $playerUrls['public'],
        'direct_stream_url' => $playerUrls['direct'],
        'proxy_stream_url' => $playerUrls['proxy'],
        'sources' => $sources,
        'source_count' => count($sources),
        'ts' => time(),
    ];

    $shouldWriteCache = (
        (int)($data['source_count'] ?? 0) > 0
        || !empty($data['public_status_ok'])
        || !empty($data['admin_status_ok'])
        || (int)($data['server_listeners'] ?? 0) > 0
        || trim((string)($data['title'] ?? '')) !== ''
    );
    if ($shouldWriteCache) {
        @file_put_contents($cacheFile, json_encode($data, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE), LOCK_EX);
    } elseif (is_file($cacheFile)) {
        @unlink($cacheFile);
    }
    return $cached = $data;
}



function ugfx_listener_count_fast(): int {
    static $count = null;
    if ($count !== null) return $count;

    $public = ugfx_parse_public_status_xsl(ugfx_fetch_public_status_xsl());
    $publicConnections = (int)($public['global']['listener_connections'] ?? 0);

    $adminXsl = ugfx_fetch_icecast_xsl();
    $admin = $adminXsl !== '' ? ugfx_parse_stats_xsl($adminXsl) : ugfx_parse_icecast_data(ugfx_fetch_icecast_xml());
    $adminConnections = (int)($admin['global']['listener_connections'] ?? 0);

    $status = ugfx_icecast_status();
    $statusConnections = (int)($status['total_listener_connections'] ?? 0);

    $bestConnections = max($publicConnections, $adminConnections, $statusConnections);
    if ($bestConnections > 0) {
        return $count = $bestConnections;
    }

    $publicListeners = (int)($public['global']['listeners'] ?? 0);
    $adminListeners = (int)($admin['global']['listeners'] ?? 0);
    $statusListeners = (int)($status['server_listeners'] ?? 0);

    return $count = max($publicListeners, $adminListeners, $statusListeners, 0);
}
function ugfx_now_playing(): array {
    $show = ugfx_current_show();
    $icecast = ugfx_icecast_status();
    return [
        'title' => $icecast['title'] ?: 'Underground FX Live',
        'artist' => $icecast['artist'] ?: $show['current'],
        'album' => 'Underground FX Radio',
        'art' => ugfx_asset('img/brand/ugfx-hero.png'),
        'listeners' => ugfx_listener_count_fast(),
        'current_listeners' => (int)($icecast['current_listeners'] ?? 0),
        'total_listener_connections' => (int)($icecast['total_listener_connections'] ?? 0),
        'status' => $icecast['status'] ?? 'LIVE',
        'mount' => $icecast['mount'] ?? '',
        'is_live' => !empty($icecast['is_live']),
        'stream_url' => $icecast['stream_url'] ?? '',
        'public_stream_url' => $icecast['public_stream_url'] ?? '',
        'direct_stream_url' => $icecast['direct_stream_url'] ?? '',
        'proxy_stream_url' => $icecast['proxy_stream_url'] ?? '',
    ];
}


function ugfx_compute_listener_display_count(): int {
    return ugfx_listener_count_fast();
}

function ugfx_nav_items(): array {
    return [
        ['label' => 'Home', 'href' => 'index.php'],
        ['label' => 'Listen Live', 'href' => 'listen-live.php'],
        ['label' => 'Schedule', 'href' => 'schedule.php'],
        ['label' => 'Requests', 'href' => 'requests.php'],
        ['label' => 'News', 'href' => 'news.php'],
        ['label' => 'Team', 'href' => 'team.php'],
        ['label' => 'Join', 'href' => 'join.php'],
        ['label' => 'Events', 'href' => 'events.php'],
        ['label' => 'Friends', 'href' => 'friends.php'],
        ['label' => 'Chat', 'href' => 'chat.php'],
        ['label' => 'Contact', 'href' => 'contact.php'],
    ];
}

function ugfx_safe_links(string $text): string {
    $escaped = nl2br(htmlspecialchars($text, ENT_QUOTES, 'UTF-8'));
    return preg_replace_callback('/(https?:\/\/[^\s<]+)/i', function ($matches) {
        $url = htmlspecialchars($matches[1], ENT_QUOTES, 'UTF-8');
        return '<a href="' . $url . '" target="_blank" rel="noopener noreferrer nofollow">' . $url . '</a>';
    }, $escaped);
}
