<?php
/**
 * RadioWebSystem - CRON skript pro sběr metadat a logování historie
 * Nastavte spouštění tohoto souboru na hostingu (např. každou minutu).
 */

ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);

// Ochrana běhu na pozadí a uvolnění limitů
ignore_user_abort(true);
set_time_limit(0);

header('Content-Type: text/plain; charset=utf-8');
header("Access-Control-Allow-Origin: *");
if (php_sapi_name() !== 'cli' && isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] === 'OPTIONS') { exit(0); }

require_once __DIR__ . '/JsonDB.php';

$settingsDb = new JsonDB('settings');
$statsDb = new JsonDB('stats');
$songsDb = new JsonDB('songs');
$requestsDb = new JsonDB('requests');

$icecastUrl = '';
$streamType = 'icecast2';
$streamUrl = '';
$streams = [];
foreach ($settingsDb->getAll() as $row) {
    if (!is_array($row)) continue;
    if (isset($row['key']) && $row['key'] === 'streams') { $streams = $row['value']; } 
    if (isset($row['key']) && $row['key'] === 'icecast_url') { $icecastUrl = $row['value']; } 
    if (isset($row['key']) && $row['key'] === 'stream_type') { $streamType = $row['value']; } 
    if (isset($row['key']) && $row['key'] === 'stream_url') { $streamUrl = $row['value']; } 
}

if (empty($streams) && !empty($icecastUrl)) {
    $streams = [['name' => 'Hlavní stream', 'type' => $streamType, 'status_url' => $icecastUrl, 'listen_url' => $streamUrl]];
}

if (empty($streams)) {
    $f = __DIR__ . '/data/settings.json';
    $content = @file_get_contents($f);
    $dbg = file_exists($f) ? "Size: " . filesize($f) . "B, Perms: " . substr(sprintf('%o', fileperms($f)), -4) : "File missing";
    $dbg2 = $content === false ? 'Read fail' : 'Read OK (' . strlen($content) . 'B)';
    die("CHYBA: Nejsou nastaveny zadne streamy v konfiguraci systemu. (Debug: $dbg | $dbg2)\n");
}

$listeners = 0; 
$nowPlaying = '';
$matchedMount = null;

foreach ($streams as $stream) {
    $sUrl = $stream['status_url'] ?? ''; $sType = $stream['type'] ?? 'icecast2'; $sListen = $stream['listen_url'] ?? '';
    if (empty($sUrl)) continue;

    $parsedUrl = parse_url($sUrl); if (empty($parsedUrl['path']) || $parsedUrl['path'] === '/') { $sUrl = rtrim($sUrl, '/') . ($sType === 'shoutcast2' ? '/stats?json=1' : '/status-json.xsl'); }

    if (function_exists('curl_init')) { $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $sUrl); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_TIMEOUT, 15); curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; RadioWebSystem/Cron)'); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); curl_setopt($ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4); $json = curl_exec($ch); if (is_resource($ch) || (PHP_VERSION_ID >= 80000 && $ch instanceof CurlHandle)) { @curl_close($ch); } }
    else { $ctx = stream_context_create(['http' => ['timeout' => 15, 'ignore_errors' => true, 'user_agent' => 'Mozilla/5.0'], 'ssl' => ['verify_peer' => false, 'verify_peer_name' => false]]); $json = @file_get_contents($sUrl, false, $ctx); }

    if ($json && $data = json_decode($json, true)) {
        $sList = 0; $sNp = '';
        if ($sType === 'shoutcast2') {
            $sList = isset($data['currentlisteners']) ? (int)$data['currentlisteners'] : 0;
            $sNp = isset($data['songtitle']) ? $data['songtitle'] : '';
            if (!$matchedMount) $matchedMount = $data;
        } else {
            if (isset($data['icestats']['source'])) {
                $src = $data['icestats']['source'];
                $mounts = is_array($src) && isset($src[0]) ? $src : [$src];
                $foundMount = null; $streamPath = '';
                if (!empty($sListen)) { $parsed = parse_url($sListen, PHP_URL_PATH); if ($parsed && $parsed !== '/') $streamPath = $parsed; }
                if (!empty($streamPath)) { foreach($mounts as $mount) { $listenUrl = isset($mount['listenurl']) ? $mount['listenurl'] : ''; if (strpos($listenUrl, $streamPath) !== false) { $foundMount = $mount; break; } } }
                if (!$foundMount && count($mounts) > 0) $foundMount = $mounts[0];
                if ($foundMount) {
                    if(isset($foundMount['listeners'])) $sList = (int)$foundMount['listeners']; 
                    if(isset($foundMount['title'])) $sNp = $foundMount['title']; 
                    elseif(isset($foundMount['server_name'])) $sNp = $foundMount['server_name'];
                }
                if (!$matchedMount) $matchedMount = $foundMount;
            }
        }
        $listeners += $sList;
        if (empty($nowPlaying) && !empty($sNp)) { $nowPlaying = $sNp; }
    }
}

// Normalizace názvu před dalším zpracováním (přípony a pomlčky)
$nowPlaying = preg_replace('/\.(mp3|wav|ogg|m4a|aac|flac|wma)$/i', '', $nowPlaying);
$nowPlaying = preg_replace('/\s*-\s*/', ' - ', $nowPlaying);

// 1. Dlouhodobá Roční Statistika (Hodinové agregace pro max. výkon a grafy)
$yearlyDb = new JsonDB('stats_yearly');
$currentHour = date('Y-m-d H:00:00');
$allYearly = $yearlyDb->getAll();
$targetYearlyId = null;
$currentYearlyRecord = null;
foreach ($allYearly as $id => $record) {
    if (isset($record['hour']) && $record['hour'] === $currentHour) {
        $targetYearlyId = $id; $currentYearlyRecord = $record; break;
    }
}

$mountData = isset($matchedMount) && $matchedMount ? $matchedMount : (isset($data) ? $data : []);
if ($currentYearlyRecord) {
    $yearlyDb->update($targetYearlyId, [
        'listeners_peak' => max($currentYearlyRecord['listeners_peak'] ?? 0, $listeners),
        'listeners_avg' => round(((($currentYearlyRecord['listeners_avg'] ?? 0) * ($currentYearlyRecord['samples'] ?? 1)) + $listeners) / (($currentYearlyRecord['samples'] ?? 1) + 1)),
        'samples' => ($currentYearlyRecord['samples'] ?? 1) + 1,
        'last_raw_data' => $mountData
    ]);
} else {
    $yearlyDb->insert([
        'hour' => $currentHour, 'listeners_peak' => $listeners, 'listeners_avg' => $listeners,
        'samples' => 1, 'last_raw_data' => $mountData
    ]);
    
    // Promazání dat starších než 1 rok (zajistí, že systém se nikdy nezahltí, max 8760 záznamů)
    $oneYearAgo = date('Y-m-d H:00:00', strtotime('-1 year'));
    foreach ($yearlyDb->getAll() as $id => $record) {
        if (isset($record['hour']) && $record['hour'] < $oneYearAgo) { $yearlyDb->delete($id); }
    }
}

// 2. Aktualizace aktuálních realtime statistik (Max 50 záznamů pro live graf v administraci)
$statsDb->insert(['timestamp' => date('Y-m-d H:i:s'), 'listeners' => $listeners]);
$allStats = $statsDb->getAll();
if (count($allStats) > 50) {
    uasort($allStats, function($a, $b) { return strtotime($a['timestamp']) <=> strtotime($b['timestamp']); });
    foreach(array_slice(array_keys($allStats), 0, count($allStats) - 50) as $id) { $statsDb->delete($id); }
}

// 3. Aktualizace aktualne hrajiciho songu (pro okamzite zobrazeni na webu)
$targetNpId = null; 
$targetArtId = null;
foreach ($settingsDb->getAll() as $id => $row) { if (isset($row['key']) && $row['key'] === 'now_playing') { $targetNpId = $id; break; } }
foreach ($settingsDb->getAll() as $id => $row) { if (isset($row['key']) && $row['key'] === 'now_playing_artwork') { $targetArtId = $id; break; } }
$npData = ['key' => 'now_playing', 'value' => $nowPlaying];
$targetNpId ? $settingsDb->update($targetNpId, $npData) : $settingsDb->insert($npData);

// 4. Logovani historie songu (Rozdeleni interpret - song a overeni, zda uz neni nahrany)
if (!empty($nowPlaying)) {
    $allSongs = array_values($songsDb->getAll());
    usort($allSongs, function($a, $b) { return strtotime($b['played_at']) <=> strtotime($a['played_at']); });
    $lastSong = !empty($allSongs) ? $allSongs[0] : null;
    $parts = explode(' - ', $nowPlaying, 2);
    $artist = trim($parts[0]); $title = isset($parts[1]) ? trim($parts[1]) : 'Neznámý název';
    $isDifferent = !$lastSong || ($lastSong['artist'] . ' - ' . $lastSong['title'] !== $artist . ' - ' . $title && $lastSong['artist'] . ' - ' . $lastSong['title'] !== $nowPlaying);
    
    if ($isDifferent) {
        $artworkUrl = '';
        $term = urlencode($artist . ' ' . $title);
        $itunesJson = @file_get_contents("https://itunes.apple.com/search?term={$term}&entity=song&limit=1&country=cz");
        if ($itunesJson && $itunesData = json_decode($itunesJson, true)) {
            $artworkUrl = $itunesData['results'][0]['artworkUrl100'] ?? '';
        }
        $songsDb->insert(['artist' => $artist, 'title' => $title, 'played_at' => date('Y-m-d H:i:s'), 'artwork' => $artworkUrl]);
        $artData = ['key' => 'now_playing_artwork', 'value' => $artworkUrl];
        $targetArtId ? $settingsDb->update($targetArtId, $artData) : $settingsDb->insert($artData);
        echo "NOVY SONG ZAZNAMENAN: $artist - $title\n";
    } 
    else { echo "STALE HRAJE: $nowPlaying\n"; }
    
    // Promazání historie songů
    $retentionDays = 365;
    foreach ($settingsDb->getAll() as $row) { if (is_array($row) && isset($row['key']) && $row['key'] === 'songs_retention_days') { $retentionDays = (int)$row['value']; break; } }
    $cutoffDate = date('Y-m-d H:i:s', strtotime("-{$retentionDays} days"));
    foreach ($songsDb->getAll() as $id => $record) {
        if (isset($record['played_at']) && $record['played_at'] < $cutoffDate) { $songsDb->delete($id); }
    }
}

// 5. Promazání starých přání pro moderátory (starší než 48 hodin)
$oldReq = date('Y-m-d H:i:s', strtotime('-48 hours'));
foreach ($requestsDb->getAll() as $id => $record) {
    if (isset($record['created_at']) && $record['created_at'] < $oldReq) { $requestsDb->delete($id); }
}

// 6. Promazání staré statistiky webu (starší než 1 rok)
$wsDb = new JsonDB('web_stats');
$oneYearAgoWs = date('Y-m-d H:00:00', strtotime('-1 year'));
foreach ($wsDb->getAll() as $id => $record) {
    if (isset($record['hour']) && $record['hour'] < $oneYearAgoWs) { $wsDb->delete($id); }
}