<?php

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

// Ultimátní záchytná síť pro Fatální chyby
register_shutdown_function(function() {
    $err = error_get_last();
    if ($err !== null && in_array($err['type'], [E_ERROR, E_PARSE, E_CORE_ERROR, E_COMPILE_ERROR])) {
        http_response_code(500);
        echo "<div style='background:#ff4b2b; color:#fff; padding:20px; font-family:sans-serif; position:fixed; top:0; left:0; width:100%; z-index:999999;'>";
        echo "<h2 style='margin-top:0;'>Kritická chyba systému (Fatal Error)</h2>";
        echo "<b>Chyba:</b> " . htmlspecialchars($err['message']) . "<br><br>";
        echo "<b>Soubor:</b> " . htmlspecialchars($err['file']) . "<br>";
        echo "<b>Řádek:</b> " . htmlspecialchars($err['line']);
        echo "</div>";
    }
});

// Multijazyčnost: Zpracování volby jazyka
$sysLangsAll = ['cs'=>'Čeština', 'en'=>'English', 'de'=>'Deutsch', 'fr'=>'Français', 'es'=>'Español', 'hu'=>'Magyar', 'pt'=>'Português', 'ru'=>'Русский', 'uk'=>'Українська', 'zh'=>'中文', 'ja'=>'日本語', 'vi'=>'Tiếng Việt'];
$flagCodes = ['cs'=>'cz', 'en'=>'gb', 'de'=>'de', 'fr'=>'fr', 'es'=>'es', 'hu'=>'hu', 'pt'=>'pt', 'ru'=>'ru', 'uk'=>'ua', 'zh'=>'cn', 'ja'=>'jp', 'vi'=>'vn'];
$currentLang = $_COOKIE['rws_lang'] ?? 'cs';
if (isset($_GET['lang']) && array_key_exists($_GET['lang'], $sysLangsAll)) {
    setcookie('rws_lang', $_GET['lang'], time() + (86400 * 365), '/');
    $currentLang = $_GET['lang'];
}

/**
 * RadioWebSystem - Hlavní vstupní bod aplikace
 */

// Získání cesty pro "falešné složkování" z .htaccess (např. clanek/jmenoclanku)
$route = isset($_GET['route']) && $_GET['route'] !== '' ? trim($_GET['route'], '/') : 'home';

// Zakázání cachování globálně pro celou aplikaci (Frontend i Backend)
header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
header("Cache-Control: post-check=0, pre-check=0", false);
header("Pragma: no-cache");
header("Expires: 0");

// Zde budeme rozdělovat požadavky (Router)
$routeParts = explode('/', $route);
$mainSection = $routeParts[0];

// Definice backendových sekcí (pokud route není v tomto poli, vykresluje se Frontend web)
$backendRoutes = ['dashboard', 'moderators', 'calendar', 'ads', 'songs', 'stats', 'template', 'settings', 'moderator-profile', 'pages', 'requests', 'podcasts'];
$isBackend = false;
require_once __DIR__ . '/JsonDB.php';

// API Router pro backendové AJAX požadavky
if ($mainSection === 'api') {
    header('Content-Type: application/json; charset=utf-8');
    
    $endpoint = $routeParts[1] ?? '';
    $response = ['status' => 'error', 'message' => 'Neznámý endpoint'];
    
    // CRUD logika pro moderátory
    if ($endpoint === 'moderators') {
        $db = new JsonDB('moderators');
        $method = $_SERVER['REQUEST_METHOD'];
        
        if ($method === 'GET') {
            $response = ['status' => 'success', 'data' => array_values($db->getAll())];
        } elseif ($method === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true);
            if ($input && isset($input['name'])) {
                if (isset($input['id']) && !empty($input['id'])) {
                    // Update
                    $id = $input['id'];
                    unset($input['id']);
                        if ($db->update($id, $input)) {
                            $response = ['status' => 'success', 'message' => 'Moderátor upraven.'];
                        } else {
                            $response = ['status' => 'error', 'message' => 'Moderátor nenalezen.'];
                        }
                } else {
                    // Insert
                    unset($input['id']);
                    $id = $db->insert($input);
                    $response = ['status' => 'success', 'message' => 'Moderátor přidán.', 'id' => $id];
                }
            } else {
                $response = ['status' => 'error', 'message' => 'Chybí povinné údaje.'];
            }
        } elseif ($method === 'DELETE') {
            $input = json_decode(file_get_contents('php://input'), true);
            if (isset($input['id']) && $db->delete($input['id'])) {
                $response = ['status' => 'success', 'message' => 'Moderátor smazán.'];
            } else {
                $response = ['status' => 'error', 'message' => 'Chyba při mazání.'];
            }
        }
    }
    
    // CRUD logika pro kalendář (směny)
    if ($endpoint === 'calendar') {
        $db = new JsonDB('shifts');
        $method = $_SERVER['REQUEST_METHOD'];
        
        if ($method === 'GET') {
            $response = ['status' => 'success', 'data' => array_values($db->getAll())];
        } elseif ($method === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true);
            if ($input && isset($input['date']) && isset($input['hour'])) {
                $existing = $db->getAll();
                $targetId = null;
                foreach ($existing as $id => $shift) {
                    if ($shift['date'] === $input['date'] && (int)$shift['hour'] === (int)$input['hour']) {
                        $targetId = $id; break;
                    }
                }
                
                $mods = $input['moderator_ids'] ?? [];
                if (empty($mods)) {
                    if ($targetId) $db->delete($targetId);
                } else {
                    $data = ['date' => $input['date'], 'hour' => (int)$input['hour'], 'moderator_ids' => $mods];
                    $targetId ? $db->update($targetId, $data) : $db->insert($data);
                }
                $response = ['status' => 'success', 'message' => 'Směna uložena.'];
            }
        }
    }

    // Logika pro DashBoard (Aktuálně ON-AIR)
    if ($endpoint === 'onair') {
        $shiftsDb = new JsonDB('shifts');
        $modsDb = new JsonDB('moderators');
        $settingsDb = new JsonDB('settings');
        $method = $_SERVER['REQUEST_METHOD'];

        if ($method === 'GET') {
            $currentDate = date('Y-m-d');
            $currentHour = (int)date('H');
            
            // 1. Zjistit, kdo má vysílat podle kalendáře
            $scheduledModIds = [];
            foreach ($shiftsDb->getAll() as $shift) {
                if ($shift['date'] === $currentDate && (int)$shift['hour'] === $currentHour) {
                    $scheduledModIds = $shift['moderator_ids'] ?? []; break;
                }
            }

            // 2. Zjistit, zda neexistuje ruční přepsání (Override)
            $overrideRecord = null;
            $targetOverrideId = null;
            foreach ($settingsDb->getAll() as $id => $row) {
                if (isset($row['key']) && $row['key'] === 'onair_override') {
                    $overrideRecord = $row;
                    $targetOverrideId = $id;
                    break;
                }
            }

            $isOverride = false;
            $activeModIds = $scheduledModIds;
            
            // Zrušení override, pokud vypršel čas (konec aktuální hodiny)
            if ($overrideRecord) {
                if (isset($overrideRecord['valid_until']) && time() < $overrideRecord['valid_until']) {
                    $activeModIds = $overrideRecord['value']['moderator_ids'] ?? ($overrideRecord['moderator_ids'] ?? []);
                    $isOverride = true;
                } else {
                    // Expirovalo, smažeme
                    $settingsDb->delete($targetOverrideId);
                }
            }

            // 3. Spárovat s daty moderátorů
            $activeMods = [];
            foreach ($activeModIds as $modId) {
                $mod = $modsDb->getById($modId);
                if ($mod) $activeMods[] = $mod;
            }

            // 4. Bod 5 - DJ Autopilot (pokud není nikdo přiřazen)
            $isAutopilot = false;
            if (empty($activeMods)) {
                $activeMods[] = [
                    'id' => 'autopilot',
                    'name' => '🤖 DJ Autopilot',
                    'email' => 'autopilot@radiowebsystem.local',
                    'active' => true,
                    'is_autopilot' => true
                ];
                $isAutopilot = true;
            }

            $response = [
                'status' => 'success',
                'data' => [
                    'mods' => $activeMods,
                    'is_override' => $isOverride,
                    'is_autopilot' => $isAutopilot,
                    'current_hour' => $currentHour
                ]
            ];
        } elseif ($method === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true);
            
            $targetOverrideId = null;
            foreach ($settingsDb->getAll() as $id => $row) {
                if (isset($row['key']) && $row['key'] === 'onair_override') {
                    $targetOverrideId = $id; break;
                }
            }

            if (isset($input['clear']) && $input['clear'] === true) {
                if ($targetOverrideId) $settingsDb->delete($targetOverrideId);
                $response = ['status' => 'success', 'message' => 'Ruční režim zrušen.'];
            } else {
                // Platnost override do konce aktuální celé hodiny
                $validUntil = strtotime(date('Y-m-d H:00:00', strtotime('+1 hour')));
                $data = [
                    'key' => 'onair_override',
                    'value' => [
                        'moderator_ids' => $input['moderator_ids'] ?? []
                    ],
                    'valid_until' => $validUntil
                ];
                $targetOverrideId ? $settingsDb->update($targetOverrideId, $data) : $settingsDb->insert($data);
                $response = ['status' => 'success', 'message' => 'Ruční moderátor nastaven.'];
            }
        }
    }

    // Logika pro Kartu moderátora
    if ($endpoint === 'moderator-profile') {
        $modId = $_GET['id'] ?? '';
        $modsDb = new JsonDB('moderators');
        $shiftsDb = new JsonDB('shifts');
        
        $mod = $modsDb->getById($modId);
        if (!$mod) {
            $response = ['status' => 'error', 'message' => 'Moderátor nenalezen.'];
        } else {
            $allShifts = $shiftsDb->getAll();
            $modShifts = [];
            foreach ($allShifts as $shift) {
                if (isset($shift['moderator_ids']) && in_array($modId, $shift['moderator_ids'])) {
                    $modShifts[] = $shift;
                }
            }
            
            // Seřadit směny chronologicky (od nejstarších po nejnovější)
            usort($modShifts, function($a, $b) {
                $timeA = strtotime($a['date'] . ' ' . $a['hour'] . ':00:00');
                $timeB = strtotime($b['date'] . ' ' . $b['hour'] . ':00:00');
                return $timeA <=> $timeB;
            });
            
            $response = [
                'status' => 'success', 
                'data' => ['moderator' => $mod, 'shifts' => $modShifts]
            ];
        }
    }

    // Univerzální CRUD pro CRM, Reklamy, Menu, Stránky a Přání
    $crudEndpoints = ['customers', 'ad_spaces', 'campaigns', 'menus', 'pages', 'requests', 'podcasts'];
    if (in_array($endpoint, $crudEndpoints)) {
        $db = new JsonDB($endpoint);
        $method = $_SERVER['REQUEST_METHOD'];
        if ($method === 'GET') {
            $response = ['status' => 'success', 'data' => array_values($db->getAll())];
        } elseif ($method === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true);
            if ($input) {
                // Zpracování Base64 obrázku (pro články)
                if (isset($input['image_base64'])) {
                    if (!empty($input['image_base64']) && strpos($input['image_base64'], 'data:image') === 0) {
                        $mediaDir = __DIR__ . '/media';
                        if (!file_exists($mediaDir)) mkdir($mediaDir, 0777, true);
                        list($type, $data) = explode(';', $input['image_base64']);
                        list(, $data)      = explode(',', $data);
                        $data = base64_decode($data);
                        $ext = strpos($type, 'png') !== false ? 'png' : (strpos($type, 'webp') !== false ? 'webp' : 'jpg');
                        $filename = uniqid('img_') . '.' . $ext;
                        file_put_contents($mediaDir . '/' . $filename, $data);
                        $input['image'] = 'media/' . $filename;
                    }
                    unset($input['image_base64']);
                }

                if (isset($input['id']) && !empty($input['id'])) {
                    $id = $input['id']; 
                    unset($input['id']);
                    $db->update($id, $input);
                } else {
                    unset($input['id']);
                    $db->insert($input);
                }
                $response = ['status' => 'success', 'message' => 'Uloženo.'];
            }
        } elseif ($method === 'DELETE') {
            $input = json_decode(file_get_contents('php://input'), true);
            if (isset($input['id']) && $db->delete($input['id'])) {
                $response = ['status' => 'success'];
            }
        }
    }

    // Generování a odesílání PDF reportů (Bod 6 a 16)
    if ($endpoint === 'campaign-report') {
        $campId = $_GET['id'] ?? '';
        $campsDb = new JsonDB('campaigns');
        $customersDb = new JsonDB('customers');
        $spacesDb = new JsonDB('ad_spaces');
        $settingsDb = new JsonDB('settings');
        
        $campaign = $campsDb->getById($campId);
        if (!$campaign) {
            $response = ['status' => 'error', 'message' => 'Kampaň nenalezena.'];
        } else {
            $customer = $customersDb->getById($campaign['customerId']);
            $space = $spacesDb->getById($campaign['spaceId']);
            
            $autoloadPath = __DIR__ . '/vendor/autoload.php';
            if (!file_exists($autoloadPath)) {
                echo json_encode(['status' => 'error', 'message' => 'Závislosti nejsou nainstalovány. Spusťte "composer install".']); exit;
            }
            require_once $autoloadPath;
            
            try {
                // 1. Generování PDF pomocí mPDF
                $mpdf = new \Mpdf\Mpdf(['tempDir' => sys_get_temp_dir() . '/mpdf']);
                $html = "<h1>Report reklamní kampaně</h1>";
                $html .= "<h2>Kampaň: " . htmlspecialchars($campaign['name']) . "</h2>";
                $html .= "<p><strong>Zákazník:</strong> " . htmlspecialchars($customer['name']) . " (" . htmlspecialchars($customer['email']) . ")</p>";
                $html .= "<p><strong>Reklamní prostor:</strong> " . htmlspecialchars($space['name']) . "</p>";
                $html .= "<p><strong>Smluvené období:</strong> {$campaign['start']} až {$campaign['end']}</p>";
                $html .= "<p><strong>Aktuální stav:</strong> " . ($campaign['active'] ? 'Aktivní' : 'Neaktivní/Ukončená') . "</p>";
                $html .= "<hr><p><small>Tento report byl automaticky vygenerován systémem RadioWebSystem.</small></p>";
                $mpdf->WriteHTML($html);
                $pdfContent = $mpdf->Output('', \Mpdf\Output\Destination::STRING_RETURN); // Uložit rovnou do paměti jako string
                
                // 2. Odeslání e-mailu pomocí PHPMailer
                $mail = new \PHPMailer\PHPMailer\PHPMailer(true);
                $mail->CharSet = 'UTF-8';
                
                $smtpConfig = null;
                foreach ($settingsDb->getAll() as $row) {
                    if (isset($row['key']) && $row['key'] === 'smtp') {
                        $smtpConfig = $row['value']; break;
                    }
                }
                
                if ($smtpConfig && !empty($smtpConfig['host'])) {
                    $mail->isSMTP();
                    $mail->Host = $smtpConfig['host'];
                    $mail->SMTPAuth = true;
                    $mail->Username = $smtpConfig['username'] ?? '';
                    $mail->Password = $smtpConfig['password'] ?? '';
                    $mail->SMTPSecure = $smtpConfig['encryption'] === 'tls' ? \PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_STARTTLS : ($smtpConfig['encryption'] === 'ssl' ? \PHPMailer\PHPMailer\PHPMailer::ENCRYPTION_SMTPS : '');
                    $mail->Port = (int)$smtpConfig['port'];
                }
                
                $fromEmail = !empty($smtpConfig['from_email']) ? $smtpConfig['from_email'] : 'info@radiowebsystem.local';
                $fromName = !empty($smtpConfig['from_name']) ? $smtpConfig['from_name'] : 'RadioWebSystem';
                
                $mail->setFrom($fromEmail, $fromName);
                if (empty($customer['email'])) throw new Exception("Zákazník nemá vyplněný e-mail.");
                $mail->addAddress($customer['email'], $customer['name']);
                $mail->isHTML(true);
                $mail->Subject = "Report kampaně: {$campaign['name']}";
                $mail->Body = "Dobrý den,<br><br>v příloze naleznete vygenerovaný report k vaší reklamní kampani <b>" . htmlspecialchars($campaign['name']) . "</b>.<br><br>S pozdravem,<br>Tým RadioWebSystem";
                $mail->addStringAttachment($pdfContent, "Report_Kampane_" . preg_replace('/[^a-zA-Z0-9_-]/', '_', $campaign['name']) . ".pdf");
                $mail->send();
                
                $response = ['status' => 'success', 'message' => 'PDF report byl úspěšně vygenerován a odeslán zákazníkovi.'];
            } catch (Exception $e) {
                $response = ['status' => 'error', 'message' => 'Chyba: ' . $e->getMessage()];
            }
        }
    }

    // API endpoint pro Historii songů (Bod 8)
    if ($endpoint === 'songs') {
        $db = new JsonDB('songs');
        $method = $_SERVER['REQUEST_METHOD'];
        if ($method === 'GET') {
            $songs = array_values($db->getAll());
            usort($songs, function($a, $b) {
                return strtotime($b['played_at']) <=> strtotime($a['played_at']);
            });
            $response = ['status' => 'success', 'data' => $songs];
        } elseif ($method === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true);
            if (!empty($input['artist']) && !empty($input['title'])) {
                $input['played_at'] = date('Y-m-d H:i:s');
                $db->insert($input);
                $response = ['status' => 'success', 'message' => 'Song zaznamenán.'];
            }
        }
    }

    // API pro Vzhled, Šablony a Menu (Body 10 a 11)
    if ($endpoint === 'template-config') {
        $db = new JsonDB('settings');
        $method = $_SERVER['REQUEST_METHOD'];
        if ($method === 'GET') {
            $tpl = ['header' => '', 'footer' => ''];
            foreach ($db->getAll() as $row) {
                if (isset($row['key']) && $row['key'] === 'template') { $tpl = $row['value']; break; }
            }
            $response = ['status' => 'success', 'data' => $tpl];
        } elseif ($method === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true);
            $targetId = null;
            foreach ($db->getAll() as $id => $row) { if (isset($row['key']) && $row['key'] === 'template') { $targetId = $id; break; } }
            $data = ['key' => 'template', 'value' => $input];
            $targetId ? $db->update($targetId, $data) : $db->insert($data);
            $response = ['status' => 'success', 'message' => 'Šablona uložena.'];
        }
    }

    if ($endpoint === 'boxes') {
        $db = new JsonDB('boxes');
        $method = $_SERVER['REQUEST_METHOD'];
        if ($method === 'GET') {
            $all = $db->getAll();
            $hasOnAir = false; $hasNowPlaying = false; $hasContact = false;
            foreach ($all as $b) {
                if (isset($b['system_type']) && $b['system_type'] === 'onair') $hasOnAir = true;
                if (isset($b['system_type']) && $b['system_type'] === 'nowplaying') $hasNowPlaying = true;
                if (isset($b['system_type']) && $b['system_type'] === 'contact') $hasContact = true;
                if (isset($b['system_type']) && $b['system_type'] === 'clock') $hasClock = true;
                if (isset($b['system_type']) && $b['system_type'] === 'weather') $hasWeather = true;
            }
            // Automatické vytvoření systémových boxů, pokud chybí
            if (!$hasOnAir) $db->insert(['title' => '📻 ON-AIR', 'content' => '1', 'position' => 'left', 'order' => 1, 'is_system' => true, 'system_type' => 'onair']);
            if (!$hasNowPlaying) $db->insert(['title' => '🎵 Právě vysíláme', 'content' => '', 'position' => 'right', 'order' => 1, 'is_system' => true, 'system_type' => 'nowplaying']);
            if (!$hasContact) $db->insert(['title' => '✉️ Napište nám', 'content' => '', 'position' => 'right', 'order' => 2, 'is_system' => true, 'system_type' => 'contact']);
            if (!isset($hasClock) || !$hasClock) $db->insert(['title' => '🕒 Aktuální čas', 'content' => 'digital', 'position' => 'left', 'order' => 2, 'is_system' => true, 'system_type' => 'clock']);
            if (!isset($hasWeather) || !$hasWeather) $db->insert(['title' => '⛅ Počasí', 'content' => 'Praha', 'position' => 'left', 'order' => 4, 'is_system' => true, 'system_type' => 'weather']);
            $all = array_values($db->getAll());
            usort($all, function($a, $b) { return (int)($a['order'] ?? 0) <=> (int)($b['order'] ?? 0); });
            $response = ['status' => 'success', 'data' => $all];
        } elseif ($method === 'POST') {
            $input = json_decode(file_get_contents('php://input'), true);
            if (isset($input['id']) && !empty($input['id'])) { $id = $input['id']; unset($input['id']); $db->update($id, $input); } 
            else { unset($input['id']); $db->insert($input); }
            $response = ['status' => 'success', 'message' => 'Box uložen.'];
        } elseif ($method === 'DELETE') {
            $input = json_decode(file_get_contents('php://input'), true);
            if (isset($input['id'])) {
                $box = $db->getById($input['id']);
                if ($box && empty($box['is_system'])) { $db->delete($input['id']); $response = ['status' => 'success']; } 
                else { $response = ['status' => 'error', 'message' => 'Systémový box nelze smazat.']; }
            }
        }
    }

    // API pro Statistiky (Bod 7)
    if ($endpoint === 'stats') {
        $db = new JsonDB('stats');
        $all = array_values($db->getAll());
        usort($all, function($a, $b) { return strtotime($a['timestamp']) <=> strtotime($b['timestamp']); });
        $response = ['status' => 'success', 'data' => $all];
    }

    if ($endpoint === 'stats-sync') {
        $settingsDb = new JsonDB('settings');
        $statsDb = new JsonDB('stats');
        $icecastUrl = '';
        $streamType = 'icecast2';
        $streamUrl = '';
        $streams = [];
        foreach ($settingsDb->getAll() as $row) {
            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]]; }
        
        $listeners = 0; 
        $nowPlaying = '';
        if (!empty($streams)) {
            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'); }
                $parsedUrl = parse_url($sUrl); if (empty($parsedUrl['path']) || $parsedUrl['path'] === '/') { $sUrl = rtrim($sUrl, '/') . ($sType === 'shoutcast2' ? '/stats?json=1' : '/status-json.xsl'); }
                $ctx = stream_context_create([ 'http' => ['timeout' => 3, 'ignore_errors' => true, 'user_agent' => 'Mozilla/5.0 (compatible; RadioWebSystem/Sync)'], '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'] : '';
                    } else {
                        if (isset($data['icestats']['source'])) {
                            $src = $data['icestats']['source'];
                            $mounts = is_array($src) && isset($src[0]) ? $src : [$src];
                            $matchedMount = 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) { $matchedMount = $mount; break; } } }
                            if (!$matchedMount && count($mounts) > 0) $matchedMount = $mounts[0];
                            if ($matchedMount) {
                                if(isset($matchedMount['listeners'])) $sList = (int)$matchedMount['listeners']; 
                                if(isset($matchedMount['title'])) $sNp = $matchedMount['title']; 
                                elseif(isset($matchedMount['server_name'])) $sNp = $matchedMount['server_name'];
                            }
                        }
                    }
                    $listeners += $sList;
                    if (empty($nowPlaying) && !empty($sNp)) { $nowPlaying = $sNp; }
                }
            }
        } else {
            $listeners = rand(10, 150); $nowPlaying = 'Simulovaný Song - RadioWebSystem';
        }
        
        if (!empty($nowPlaying) && $nowPlaying !== 'Simulovaný Song - RadioWebSystem') {
            $nowPlaying = preg_replace('/\.(mp3|wav|ogg|m4a|aac|flac|wma)$/i', '', $nowPlaying);
            $nowPlaying = preg_replace('/\s*-\s*/', ' - ', $nowPlaying);
        }
        
        $statsDb->insert(['timestamp' => date('Y-m-d H:i:s'), 'listeners' => $listeners]);
        
        // Ponechat jen posledních 50 záznamů, ať JSON neomezeně neroste
        $all = $statsDb->getAll();
        if (count($all) > 50) {
            uasort($all, function($a, $b) { return strtotime($a['timestamp']) <=> strtotime($b['timestamp']); });
            foreach(array_slice(array_keys($all), 0, count($all) - 50) as $id) { $statsDb->delete($id); }
        }
        
        // Uložení aktuálních metadat do settings pro systémový box (Právě hraje)
        $targetNpId = null;
        foreach ($settingsDb->getAll() as $id => $row) { if (isset($row['key']) && $row['key'] === 'now_playing') { $targetNpId = $id; break; } }
        $npData = ['key' => 'now_playing', 'value' => $nowPlaying];
        $targetNpId ? $settingsDb->update($targetNpId, $npData) : $settingsDb->insert($npData);

        if (!empty($nowPlaying) && $nowPlaying !== 'Simulovaný Song - RadioWebSystem') {
            $songsDb = new JsonDB('songs');
            $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 = true;
            if ($lastSong) {
                $lastFullName = $lastSong['artist'] . ' - ' . $lastSong['title'];
                if ($lastFullName === $artist . ' - ' . $title || $lastFullName === $nowPlaying) { $isDifferent = false; }
            }
            if ($isDifferent) {
                $songsDb->insert(['artist' => $artist, 'title' => $title, 'played_at' => date('Y-m-d H:i:s')]);
            }
            
            // 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); }
            }
        }

        $response = ['status' => 'success', 'listeners' => $listeners];
    }
    
    echo json_encode($response);
    exit; // Důležité: ukončit běh, ať se nevrací i HTML
}

// --- PŘÍPRAVA DAT PRO FRONTEND ---
    $settingsDb = new JsonDB('settings');
    $menusDb = new JsonDB('menus');
    $boxesDb = new JsonDB('boxes');
    $shiftsDb = new JsonDB('shifts');
    $modsDb = new JsonDB('moderators');
    $pagesDb = new JsonDB('pages');
    $songsDb = new JsonDB('songs');
    $podcastsDb = new JsonDB('podcasts');
    $ignoredDb = new JsonDB('ignored_songs');

    // Aktivní jazyky
    $activeLangs = array_keys($sysLangsAll);
    foreach ($settingsDb->getAll() as $row) {
        if (is_array($row) && isset($row['key']) && $row['key'] === 'active_langs' && is_array($row['value'])) {
            $activeLangs = $row['value']; break;
        }
    }
    $sysLangs = [];
    foreach ($sysLangsAll as $k => $v) {
        if (in_array($k, $activeLangs)) $sysLangs[$k] = $v;
    }
    if (!array_key_exists($currentLang, $sysLangs)) {
        $currentLang = isset($sysLangs['cs']) ? 'cs' : array_key_first($sysLangs);
    }

    // Pomocná funkce pro zajištění velkého prvního písmene na frontendu (rozpozná i pomlčku)
    if (!function_exists('capitalizeSong')) {
        function capitalizeSong($str) {
            if (!$str) return $str;
            $str = preg_replace('/\.(mp3|wav|ogg|m4a|aac|flac|wma)$/i', '', $str);
            $str = str_replace('_', ' ', $str);
            $str = preg_replace('/\s*-\s*/', ' - ', $str);
            return mb_convert_case($str, MB_CASE_TITLE, 'UTF-8');
        }
    }

    // Vzhled
    $tpl = ['header' => '', 'footer' => '', 'color_bg1' => '#1e3c72', 'color_bg2' => '#2a5298', 'color_accent' => '#00d2ff', 'font_family' => "'Segoe UI', Tahoma, Geneva, Verdana, sans-serif", 'bg_image' => '', 'bg_repeat' => 'cover', 'festive_effect' => 'none', 'site_title' => '', 'logo_image' => '', 'logo_size' => '100px', 'logo_position' => 'center', 'title_size' => '2rem', 'title_position' => 'center', 'social_fb' => '', 'social_ig' => '', 'color_btn' => '#00d2ff', 'color_btn_text' => '#000000', 'color_text_muted' => '#cccccc', 'color_panel_bg' => 'rgba(255, 255, 255, 0.15)', 'custom_head' => '', 'custom_body' => '', 'custom_css' => ''];
    $nowPlaying = 'Nic nehraje';
    $nowPlayingArtwork = '';
    $streamUrl = '';
    $streams = [];
    $recaptchaSiteKey = '';
    foreach ($settingsDb->getAll() as $row) {
        if (is_array($row) && isset($row['key']) && $row['key'] === 'streams' && is_array($row['value'])) $streams = $row['value'];
        if (is_array($row) && isset($row['key']) && $row['key'] === 'template' && is_array($row['value'])) $tpl = array_merge($tpl, $row['value']);
        if (is_array($row) && isset($row['key']) && $row['key'] === 'now_playing') $nowPlaying = $row['value'];
        if (is_array($row) && isset($row['key']) && $row['key'] === 'now_playing_artwork') $nowPlayingArtwork = $row['value'];
        if (is_array($row) && isset($row['key']) && $row['key'] === 'stream_url') $streamUrl = $row['value'];
        if (is_array($row) && isset($row['key']) && $row['key'] === 'recaptcha_site_key') $recaptchaSiteKey = $row['value'];
    }
    $nowPlaying = capitalizeSong($nowPlaying);

    $upcomingQueue = [];
    foreach ($settingsDb->getAll() as $row) {
        if (is_array($row) && isset($row['key']) && $row['key'] === 'upcoming_queue' && is_array($row['value'])) { $upcomingQueue = $row['value']; break; }
    }

    $isHttps = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') || (isset($_SERVER['HTTP_X_FORWARDED_PROTO']) && $_SERVER['HTTP_X_FORWARDED_PROTO'] === 'https');
    if (empty($streams) && !empty($streamUrl)) { $streams = [['name' => 'Hlavní', 'listen_url' => $streamUrl]]; }
    
    $playerStreams = [];
    foreach ($streams as $idx => $s) {
        $sUrl = $s['listen_url'] ?? '';
        if (empty($sUrl)) continue;
        if ($isHttps && strpos($sUrl, 'http://') === 0) {
        $sUrl = '/stream-proxy.php?stream=' . urlencode($sUrl);
        }
        $playerStreams[] = ['name' => $s['name'] ?? 'Stream '.($idx+1), 'url' => $sUrl];
    }
    $menus = array_values($menusDb->getAll());
    usort($menus, function($a, $b) { $oA = is_array($a) && isset($a['order']) ? (int)$a['order'] : 0; $oB = is_array($b) && isset($b['order']) ? (int)$b['order'] : 0; return $oA <=> $oB; });
    
    $menuTree = [];
    foreach ($menus as $m) {
        if (empty($m['parent_id'])) {
            $m['children'] = [];
            $menuTree[$m['id']] = $m;
        }
    }
    foreach ($menus as $m) {
        if (!empty($m['parent_id']) && isset($menuTree[$m['parent_id']])) {
            $menuTree[$m['parent_id']]['children'][] = $m;
        }
    }

    $boxes = array_values($boxesDb->getAll());
    usort($boxes, function($a, $b) { $oA = is_array($a) && isset($a['order']) ? (int)$a['order'] : 0; $oB = is_array($b) && isset($b['order']) ? (int)$b['order'] : 0; return $oA <=> $oB; });

    // Kdo právě vysílá (Zjednodušená verze z API)
    $currentDate = date('Y-m-d');
    $currentHour = (int)date('H');
    $activeModIds = [];
    foreach ($shiftsDb->getAll() as $shift) { 
        if ($shift['date'] === $currentDate && (int)$shift['hour'] === $currentHour) { $activeModIds = $shift['moderator_ids'] ?? []; break; } 
    }
    foreach ($settingsDb->getAll() as $row) { 
        if (isset($row['key']) && $row['key'] === 'onair_override' && isset($row['valid_until']) && time() < $row['valid_until']) { 
            $val = $row['value'] ?? [];
            $activeModIds = (is_array($val) ? ($val['moderator_ids'] ?? []) : []) ?: ($row['moderator_ids'] ?? []); break; 
        } 
    }
    $activeMods = [];
    if (!is_array($activeModIds)) $activeModIds = [];
    foreach ($activeModIds as $modId) { $mod = $modsDb->getById($modId); if ($mod) $activeMods[] = $mod; }
    
    if (empty($activeMods)) {
        $autopilot = null;
        foreach ($modsDb->getAll() as $m) { if (!empty($m['is_autopilot'])) { $autopilot = $m; break; } }
        if (!$autopilot) {
            $autoId = $modsDb->insert(['name' => '🤖 DJ Autopilot', 'active' => true, 'is_autopilot' => true, 'short_desc' => 'Automatické vysílání']);
            $autopilot = $modsDb->getById($autoId);
        }
        $activeMods[] = $autopilot;
    }
    
    $onAirHtml = '';
    foreach ($activeMods as $m) {
        if (!is_array($m)) continue;
        $photoHtml = !empty($m['photo']) ? "<img src='/{$m['photo']}' style='width:80px; height:80px; border-radius:50%; object-fit:cover; margin-bottom:10px; border:2px solid var(--accent);'>" : "<div style='font-size:3rem; margin-bottom:10px;'>🎙️</div>";
            $descHtml = !empty($m['short_desc']) ? "<div style='font-size:0.9rem; color:var(--text-muted); margin-top:5px;'>".$m['short_desc']."</div>" : "";
        $onAirHtml .= "<div style='text-align:center; margin-bottom:15px;'><a href='/moderator/{$m['id']}' style='text-decoration:none; color:inherit; display:block; transition:transform 0.2s;' onmouseover=\"this.style.transform='scale(1.05)'\" onmouseout=\"this.style.transform='scale(1)'\">{$photoHtml}<div style='color:var(--accent); font-weight:bold; font-size:1.2rem;'>".htmlspecialchars($m['name'])."</div>{$descHtml}</a></div>";
    }
    $onAirText = $onAirHtml;

    // Stránky
    $pages = array_values($pagesDb->getAll());
    $homePage = null; foreach ($pages as $p) { if (is_array($p) && !empty($p['is_home'])) { $homePage = $p; break; } }

    // Hitparáda data a Historie (Zajištění řazení pro úvodní načtení!)
    $allSongs = array_values($songsDb->getAll());
    $ignoredList = []; 
    foreach ($ignoredDb->getAll() as $ig) { if (!empty($ig['name'])) $ignoredList[] = mb_strtolower(trim($ig['name']), 'UTF-8'); }
    $filteredSongs = array_filter($allSongs, function($s) use ($ignoredList) { 
        if (!is_array($s) || !empty($s['excluded'])) return false;
        $rawName = trim($s['artist'] ?? '') . ' - ' . trim($s['title'] ?? '');
        $songName = mb_strtolower(capitalizeSong($rawName), 'UTF-8');
        foreach ($ignoredList as $igName) {
            if ($songName === mb_strtolower(capitalizeSong($igName), 'UTF-8')) return false;
            if (mb_strtolower($rawName, 'UTF-8') === $igName) return false;
        }
        return true; 
    });
    usort($filteredSongs, function($a, $b) { $tA = is_array($a) && isset($a['played_at']) ? strtotime($a['played_at']) : 0; $tB = is_array($b) && isset($b['played_at']) ? strtotime($b['played_at']) : 0; return $tB <=> $tA; });
    
    // Podcasty
    $podcasts = array_values($podcastsDb->getAll());
    usort($podcasts, function($a, $b) { $tA = is_array($a) && isset($a['created_at']) ? strtotime($a['created_at']) : 0; $tB = is_array($b) && isset($b['created_at']) ? strtotime($b['created_at']) : 0; return $tB <=> $tA; });
    
    $competitionsDb = new JsonDB('competitions'); $competitions = array_values($competitionsDb->getAll());

    // TRACKING NÁVŠTĚVNOSTI (Každé načtení i SPA proklik)
    $wsDb = new JsonDB('web_stats');
    $currentHour = date('Y-m-d H:00:00');
    $statsAll = $wsDb->getAll();
    $targetWsId = null;
    $currentWs = null;
    foreach ($statsAll as $id => $s) {
        if (is_array($s) && isset($s['hour']) && $s['hour'] === $currentHour) {
            $targetWsId = $id; $currentWs = $s; break;
        }
    }
    $isUnique = false;
    $cookieName = 'rws_uniq_' . date('Ymd');
    if (!isset($_COOKIE[$cookieName])) {
        setcookie($cookieName, '1', time() + 86400, '/');
        $isUnique = true;
    }
    if ($currentWs) {
        $wsDb->update($targetWsId, ['views' => ($currentWs['views'] ?? 0) + 1, 'unique' => ($currentWs['unique'] ?? 0) + ($isUnique ? 1 : 0)]);
    } else {
        $wsDb->insert(['hour' => $currentHour, 'views' => 1, 'unique' => $isUnique ? 1 : 0]);
    }

    // Kontrola licence pro veřejný web (Banner)
    $licenseInfo = null;
    foreach ($settingsDb->getAll() as $row) { if (is_array($row) && isset($row['key']) && $row['key'] === 'license_info') { $licenseInfo = $row['value']; break; } }
    $showLicBanner = false;
    if ($licenseInfo && !empty($licenseInfo['valid_until']) && $licenseInfo['valid_until'] !== '-') {
        $parts = explode('.', $licenseInfo['valid_until']);
        if (count($parts) === 3) {
            $expDate = strtotime(trim($parts[2]).'-'.trim($parts[1]).'-'.trim($parts[0]).' 23:59:59');
            if ($expDate && time() > $expDate) { $showLicBanner = true; }
        }
    } elseif ($licenseInfo && isset($licenseInfo['license']) && $licenseInfo['license'] !== 'OK') { $showLicBanner = true; }
?>
<!DOCTYPE html>
<html lang="cs">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Radio Web System | ONAIR</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <link rel="alternate" type="application/rss+xml" title="RadioWebSystem RSS Feed" href="/rss.xml">
    <?php if (!empty($recaptchaSiteKey)): ?>
    <script src="https://www.google.com/recaptcha/api.js?render=<?php echo htmlspecialchars($recaptchaSiteKey); ?>"></script>
    <?php endif; ?>
    <link href="https://fonts.googleapis.com/css2?family=Lora:ital,wght@0,400;0,700;1,400&family=Montserrat:wght@400;700&family=Open+Sans:wght@400;700&family=Oswald:wght@400;700&family=Playfair+Display:ital,wght@0,400;0,700;1,400&family=Roboto:wght@400;700&display=swap" rel="stylesheet">
    <style>
        :root {
            --glass-bg: <?php echo htmlspecialchars($tpl['color_panel_bg']); ?>;
            --glass-border: rgba(255, 255, 255, 0.25);
            --glass-shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.5);
            --text-color: #fff;
            --accent: <?php echo htmlspecialchars($tpl['color_accent']); ?>;
            --btn-bg: <?php echo htmlspecialchars($tpl['color_btn']); ?>;
            --btn-text: <?php echo htmlspecialchars($tpl['color_btn_text']); ?>;
            --text-muted: <?php echo htmlspecialchars($tpl['color_text_muted']); ?>;
        }
        
        body {
            margin: 0;
            padding: 0;
            font-family: <?php echo $tpl['font_family']; ?>;
            <?php if (!empty($tpl['bg_image'])): ?>
                background: url('/<?php echo htmlspecialchars($tpl['bg_image']); ?>') <?php echo $tpl['bg_repeat'] === 'cover' ? 'center center / cover no-repeat' : 'repeat'; ?> fixed;
            <?php else: ?>
                background: linear-gradient(135deg, <?php echo htmlspecialchars($tpl['color_bg1']); ?> 0%, <?php echo htmlspecialchars($tpl['color_bg2']); ?> 100%) fixed;
            <?php endif; ?>
            color: var(--text-color);
            min-height: 100vh;
            display: flex;
            flex-direction: column;
            overflow-y: auto;
        }

        /* Glassmorphism základ */
        .glass {
            background: var(--glass-bg);
            backdrop-filter: blur(20px);
            -webkit-backdrop-filter: blur(20px);
            border: 1px solid var(--glass-border);
            box-shadow: var(--glass-shadow);
            border-radius: 15px;
        }

        /* FRONTEND SPECIFIC STYLES - FLEXBOX LAYOUT */
        .fw-container { max-width: 1200px; margin: 0 auto; padding: 20px; flex: 1; width: 100%; box-sizing: border-box; display: flex; flex-direction: column; }
        .fw-topbar { display: flex; flex-wrap: nowrap; justify-content: flex-start; align-items: center; gap: 20px; padding: 15px 20px; margin-bottom: 30px; position: relative; min-height: 80px; z-index: 1000; }
        .fw-topbar-left { display: flex; flex-direction: column; justify-content: center; align-items: <?php echo htmlspecialchars($tpl['logo_position'] === 'left' ? 'flex-start' : ($tpl['logo_position'] === 'right' ? 'flex-end' : 'center')); ?>; flex: 0 0 auto; max-width: 350px; text-align: left; }
        .fw-nav { display: flex; gap: 10px; justify-content: flex-start; align-items: center; flex-wrap: wrap; flex: 1 1 auto; padding-right: 230px; }
        .fw-topbar-right { position: absolute; right: 20px; top: 15px; display: flex; align-items: center; gap: 15px; z-index: 100; }
        .fw-header { margin-bottom: 30px; text-align: center; }
        .fw-nav a { color: var(--text-color); text-decoration: none; font-size: 1.1rem; font-weight: bold; padding: 8px 15px; border-radius: 8px; transition: 0.3s background; background: rgba(255,255,255, 0.05); }
        .fw-nav a:hover { background: rgba(255,255,255,0.2); }
        .fw-layout { display: grid; grid-template-columns: 250px 1fr 250px; gap: 20px; }
        @media (max-width: 900px) { .fw-layout { display: flex; flex-direction: column; gap: 20px; } .fw-col-left { order: 2; width: 100%; } .fw-content { order: 1; width: 100%; box-sizing:border-box; } .fw-col-right { order: 3; width: 100%; } .fw-topbar { flex-wrap: wrap; justify-content: space-between; height: auto; } .fw-topbar-left { align-items: center !important; margin: 0 auto; } .mobile-menu-toggle { display: block !important; margin: 15px auto; width: 100%; max-width: 300px; text-align: center; } .fw-nav { display: none; width: 100%; flex-direction: column; padding: 15px; margin: 0; background: var(--glass-bg); border: 1px solid var(--glass-border); border-radius: 10px; } .fw-nav.active { display: flex; } .fw-nav a { width: 100%; text-align: center; margin-bottom: 5px; } .fw-topbar-right { position: relative; right: 0; top: 0; justify-content: center; width: 100%; margin-top: 15px; } .menu-dropdown-content { position: static; display: none; width: 100%; background: rgba(0,0,0,0.3); border: none; } .menu-dropdown:hover .menu-dropdown-content, .menu-dropdown:active .menu-dropdown-content { display: block; } }
        .mobile-menu-toggle { display: none; background: var(--accent); color: #000; padding: 10px; border-radius: 8px; font-weight: bold; border: none; font-size: 1.1rem; cursor: pointer; text-transform: uppercase; box-shadow: 0 0 10px rgba(0,0,0,0.3); }
        .fw-box { padding: 15px; margin-bottom: 20px; }
        .fw-box h3 { margin-top: 0; border-bottom: 1px solid var(--glass-border); padding-bottom: 10px; font-size: 1.1rem; }
        .fw-content { padding: 30px; min-height: 400px; }
        .fw-footer { margin-top: 40px; text-align: center; padding: 20px; }
        button { cursor: pointer; background: var(--btn-bg); color: var(--btn-text); border: none; font-weight: bold; transition: transform 0.2s ease; padding: 10px 15px; border-radius: 8px; }
        button:hover { transform: scale(1.05); }
        
        .mod-card { padding: 20px; text-align: center; margin-bottom: 20px; }
        .mod-card h3 { color: var(--accent); margin: 0 0 10px 0; }
        
        .clock-digital { font-family: monospace; font-size: 2.8rem; text-align: center; color: var(--accent); text-shadow: 0 0 10px rgba(0,0,0,0.5); padding: 10px 0; letter-spacing: 2px; font-weight: bold; }
        .clock-analog { position: relative; width: 150px; height: 150px; border: 4px solid var(--accent); border-radius: 50%; margin: 10px auto; background: rgba(0,0,0,0.3); box-shadow: inset 0 0 15px rgba(0,0,0,0.5); }
        .clock-analog::after { content: ''; position: absolute; width: 12px; height: 12px; background: var(--accent); border-radius: 50%; top: 50%; left: 50%; transform: translate(-50%, -50%); z-index: 10; box-shadow: 0 0 5px rgba(0,0,0,0.5); }
        .clock-hand { position: absolute; bottom: 50%; left: 50%; transform-origin: bottom center; border-radius: 4px; z-index: 5; }
        .clock-hand-hour { width: 6px; height: 45px; margin-left: -3px; background: #fff; }
        .clock-hand-minute { width: 4px; height: 60px; margin-left: -2px; background: #ddd; }
        .clock-hand-second { width: 2px; height: 70px; margin-left: -1px; background: #ff4b2b; z-index: 6; }
        
        /* Jazykove menu */
        .lang-dropdown { position: relative; display: inline-block; }
        .lang-btn { background: rgba(0,0,0,0.3); border: 1px solid var(--glass-border); color: #fff; padding: 8px 15px; border-radius: 8px; cursor: pointer; display: flex; align-items: center; gap: 8px; text-decoration: none; font-weight: bold; }
        .lang-dropdown-content { display: none; position: absolute; right: 0; top: 100%; margin-top: 5px; background: rgba(0,0,0,0.8); backdrop-filter: blur(40px); -webkit-backdrop-filter: blur(40px); border: 1px solid var(--glass-border); border-radius: 8px; min-width: 180px; box-shadow: var(--glass-shadow); z-index: 10000; overflow: hidden; }
        .lang-dropdown-content a { color: #fff; padding: 10px 15px; text-decoration: none; display: flex; align-items: center; gap: 10px; border-bottom: 1px solid rgba(255,255,255,0.1); transition: 0.2s background; }
        .lang-dropdown-content a:hover, .lang-dropdown-content a.active { background: rgba(255,255,255,0.2); }
        .lang-dropdown:hover .lang-dropdown-content { display: block; }
        
        .menu-dropdown { position: relative; display: inline-block; }
        .menu-dropdown-content { display: none; position: absolute; top: 100%; left: 0; background: rgba(0,0,0,0.8); backdrop-filter: blur(40px); -webkit-backdrop-filter: blur(40px); border: 1px solid var(--glass-border); border-radius: 8px; min-width: 200px; box-shadow: var(--glass-shadow); z-index: 10000; overflow: hidden; margin-top: 5px; }
        .menu-dropdown-content a { display: block; padding: 10px 15px; border-bottom: 1px solid rgba(255,255,255,0.1); border-radius: 0; }
        .menu-dropdown:hover .menu-dropdown-content { display: block; }
        
        .btn-tune-in { color: lime !important; width: 170px; display: inline-flex !important; align-items: center; justify-content: center; box-shadow: 0 0 10px rgba(0,255,0,0.3); animation: pulse-lime 2s infinite; }
        @keyframes pulse-lime { 0% { box-shadow: 0 0 10px rgba(0,255,0,0.3); } 50% { box-shadow: 0 0 20px rgba(0,255,0,0.6); } 100% { box-shadow: 0 0 10px rgba(0,255,0,0.3); } }
        .tune-text { display: inline-block; width: 100px; text-align: left; margin-left: 5px; white-space: nowrap; overflow: hidden; }
        <?php if (!empty($tpl['custom_css'])) echo $tpl['custom_css'] . "\n"; ?>
    </style>
    <script>
        // Převedení menu předvolby pro soutěže
        if (typeof window !== 'undefined' && window.location.pathname.startsWith('/admin')) {
            document.addEventListener('DOMContentLoaded', () => { const m = document.getElementById('menuPreset'); if (m) { m.innerHTML += '<option value="/souteze">🎁 Soutěže</option>'; } });
        }
    </script>
    <?php if (!empty($tpl['custom_head'])) echo $tpl['custom_head'] . "\n"; ?>
</head>
<body>
    <?php if ($showLicBanner): ?>
        <div style="background: #ff4b2b; color: #fff; text-align: center; padding: 10px; font-weight: bold; position: sticky; top: 0; z-index: 999999; box-shadow: 0 4px 10px rgba(0,0,0,0.5);">Upozornění: Licence systému vypršela. Funkčnost webu může být omezena.</div>
    <?php endif; ?>
    <div class="modal-overlay" id="customAlertModal" style="display:none; position:fixed; top:0; left:0; width:100%; height:100%; background:rgba(0,0,0,0.6); backdrop-filter:blur(25px); -webkit-backdrop-filter:blur(25px); z-index:10000; align-items:center; justify-content:center;">
        <div class="glass" style="padding:30px; width:600px; max-width:95%; text-align:center; display:flex; flex-direction:column; max-height:90vh; box-sizing:border-box;">
            <h3 id="customAlertTitle" style="color:var(--accent); margin-top:0; flex-shrink:0;">Upozornění</h3>
            <div id="customAlertText" style="margin:20px 0; line-height:1.5; overflow-y:auto; text-align:left; word-break:break-word; white-space:pre-wrap; flex:1;"></div>
            <button onclick="document.getElementById('customAlertModal').style.display='none'; if(window.customAlertCallback) window.customAlertCallback();" style="flex-shrink:0;">OK</button>
        </div>
    </div>
<?php if ($isBackend): ?>
    <!-- BACKEND UI -->
    <div class="sidebar glass">
        <h2>📻 Radio Web System</h2>
        <a href="?route=dashboard" class="nav-link <?php echo $mainSection === 'dashboard' ? 'active' : ''; ?>">Dashboard</a>
        <a href="?route=pages" class="nav-link <?php echo $mainSection === 'pages' ? 'active' : ''; ?>">Stránky a Články</a>
        <a href="?route=requests" class="nav-link <?php echo $mainSection === 'requests' ? 'active' : ''; ?>">Písničky na přání</a>
        <a href="?route=moderators" class="nav-link <?php echo $mainSection === 'moderators' ? 'active' : ''; ?>">Správa moderátorů</a>
        <a href="?route=calendar" class="nav-link <?php echo $mainSection === 'calendar' ? 'active' : ''; ?>">Kalendář směn</a>
        <a href="?route=ads" class="nav-link <?php echo $mainSection === 'ads' ? 'active' : ''; ?>">Reklama a Zákazníci</a>
        <a href="?route=songs" class="nav-link <?php echo $mainSection === 'songs' ? 'active' : ''; ?>">Historie songů</a>
        <a href="?route=stats" class="nav-link <?php echo $mainSection === 'stats' ? 'active' : ''; ?>">Statistiky streamu</a>
        <a href="?route=template" class="nav-link <?php echo $mainSection === 'template' ? 'active' : ''; ?>">Vzhled a Menu webu</a>
        <a href="?route=settings" class="nav-link <?php echo $mainSection === 'settings' ? 'active' : ''; ?>">Nastavení systému</a>
    </div>

    <div class="content-area glass">
        <?php if ($mainSection === 'dashboard'): ?>
            <h1>Dashboard - Aktuálně ve vysílání</h1>
            
            <div class="glass" style="padding: 40px 20px; margin-bottom: 20px; text-align: center;">
                <div style="font-size: 1.2rem; color: #aaa; margin-bottom: 10px;">🔴 ON-AIR</div>
                <h2 id="onAirStatus" style="font-size: 2.5rem; color: var(--accent); margin: 0 0 10px 0;">Načítám...</h2>
                <p id="onAirType" style="color: #ccc; margin: 0;">...</p>
            </div>
            
            <div class="glass" style="padding: 20px;">
                <h3>Nečekaná změna? (Ruční přepnutí)</h3>
                <p>Pokud do studia dorazil náhradník mimo kalendář, můžete jej přepnout zde. Toto nastavení platí do konce aktuální hodiny.</p>
                <div class="form-group">
                    <select id="overrideModSelect">
                        <option value="">-- Vyberte moderátora --</option>
                    </select>
                    <button onclick="setOverride()">Nastavit ručně</button>
                    <button onclick="clearOverride()" style="background: rgba(255,255,255,0.2);">Zrušit ruční režim</button>
                </div>
            </div>

            <script>
                async function loadOnAir() {
                    const res = await fetch('/radiowebsystem/api/onair');
                    const json = await res.json();
                    
                    const statusEl = document.getElementById('onAirStatus');
                    const typeEl = document.getElementById('onAirType');
                    
                    if (json.data.is_autopilot) {
                        statusEl.innerText = json.data.mods[0].name;
                        statusEl.style.color = '#b026ff'; // Speciální fialová pro robota
                        typeEl.innerText = '⚙️ Vysílá automat (žádný moderátor v kalendáři)';
                    } else {
                        statusEl.innerText = json.data.mods.map(m => m.name).join(', ');
                        statusEl.style.color = 'var(--accent)';
                        typeEl.innerText = json.data.is_override ? '⚠️ Vysílá v ručním režimu (mimo kalendář)' : '📅 Vysílá podle kalendáře';
                    }
                }

                async function loadActiveModeratorsForSelect() {
                    const res = await fetch('/radiowebsystem/api/moderators');
                    const json = await res.json();
                    const select = document.getElementById('overrideModSelect');
                    json.data.forEach(m => {
                        if (m.active) {
                            select.innerHTML += `<option value="${m.id}">${m.name}</option>`;
                        }
                    });
                }

                async function setOverride() {
                    const modId = document.getElementById('overrideModSelect').value;
                    if (!modId) return alert('Nejprve vyberte moderátora.');
                    await fetch('/radiowebsystem/api/onair', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ moderator_ids: [modId] })
                    });
                    loadOnAir();
                }

                async function clearOverride() {
                    await fetch('/radiowebsystem/api/onair', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ clear: true })
                    });
                    loadOnAir();
                    document.getElementById('overrideModSelect').value = '';
                }

                // Prvotní spuštění a interval
                loadActiveModeratorsForSelect();
                loadOnAir();
                setInterval(loadOnAir, 10000); // Aktualizace každých 10 vteřin bez refreshe
            </script>
        
        <?php elseif ($mainSection === 'moderators'): ?>
            <h1>Správa moderátorů</h1>
            
            <div class="glass" style="padding: 20px; margin-bottom: 20px;">
                <h3>Přidat / Upravit moderátora</h3>
                <form id="moderatorForm" class="form-group">
                    <input type="hidden" id="modId">
                    <input type="text" id="modName" placeholder="Jméno moderátora" required>
                    <input type="email" id="modEmail" placeholder="E-mail">
                    <label>
                        <input type="checkbox" id="modActive" checked> Aktivní
                    </label>
                    <button type="submit">Uložit moderátora</button>
                    <button type="button" onclick="resetForm()" style="background: rgba(255,255,255,0.2);">Zrušit</button>
                </form>
            </div>

            <div class="glass" style="padding: 20px;">
                <h3>Seznam moderátorů</h3>
                <table>
                    <thead>
                        <tr>
                            <th>Jméno</th>
                            <th>E-mail</th>
                            <th>Stav</th>
                            <th>Akce</th>
                        </tr>
                    </thead>
                    <tbody id="moderatorsTableBody">
                        <tr><td colspan="4">Načítám data...</td></tr>
                    </tbody>
                </table>
            </div>

            <script>
                // AJAX logika pro moderátory
                async function loadModerators() {
                    const res = await fetch('/radiowebsystem/api/moderators');
                    const json = await res.json();
                    const tbody = document.getElementById('moderatorsTableBody');
                    tbody.innerHTML = '';

                    if(json.data.length === 0) {
                        tbody.innerHTML = '<tr><td colspan="4">Žádní moderátoři k dispozici.</td></tr>';
                        return;
                    }

                    json.data.forEach(mod => {
                        const tr = document.createElement('tr');
                        tr.innerHTML = `
                            <td>${mod.name}</td>
                            <td>${mod.email || '-'}</td>
                            <td>${mod.active ? '🟢 Aktivní' : '🔴 Neaktivní'}</td>
                            <td>
                                <a href="?route=moderator-profile/${mod.id}" class="action-btn btn-info">Karta</a>
                                <button class="action-btn" onclick='editModerator(${JSON.stringify(mod)})'>Upravit</button>
                                <button class="action-btn btn-delete" onclick="deleteModerator('${mod.id}')">Smazat</button>
                            </td>
                        `;
                        tbody.appendChild(tr);
                    });
                }

                document.getElementById('moderatorForm').addEventListener('submit', async (e) => {
                    e.preventDefault();
                    const data = {
                        id: document.getElementById('modId').value,
                        name: document.getElementById('modName').value,
                        email: document.getElementById('modEmail').value,
                        active: document.getElementById('modActive').checked
                    };

                    await fetch('/radiowebsystem/api/moderators', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify(data)
                    });
                    
                    resetForm();
                    loadModerators();
                });

                async function deleteModerator(id) {
                    if(!confirm('Opravdu smazat tohoto moderátora?')) return;
                    await fetch('/radiowebsystem/api/moderators', {
                        method: 'DELETE',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ id: id })
                    });
                    loadModerators();
                }

                function editModerator(mod) {
                    document.getElementById('modId').value = mod.id;
                    document.getElementById('modName').value = mod.name;
                    document.getElementById('modEmail').value = mod.email;
                    document.getElementById('modActive').checked = mod.active;
                }

                function resetForm() {
                    document.getElementById('modId').value = '';
                    document.getElementById('moderatorForm').reset();
                }

                // Prvotní načtení
                loadModerators();
            </script>
            
        <?php elseif ($mainSection === 'calendar'): ?>
            <h1>Kalendář a plánovač směn</h1>
            
            <div class="glass" style="padding: 20px; margin-bottom: 20px; display: flex; align-items: center; gap: 15px;">
                <label for="datePicker" style="font-weight:bold;">Zvolte den:</label>
                <input type="date" id="datePicker">
                <button onclick="loadCalendar()">Načíst směny</button>
            </div>
            
            <div class="glass" style="padding: 20px;">
                <table>
                    <thead>
                        <tr>
                            <th style="width: 100px;">Hodina</th>
                            <th>Moderátoři (ON-AIR)</th>
                            <th style="width: 150px;">Akce</th>
                        </tr>
                    </thead>
                    <tbody id="calendarTableBody">
                        <!-- Generováno přes JS -->
                    </tbody>
                </table>
            </div>
            
            <!-- Modální okno pro přiřazení moderátorů -->
            <div class="modal-overlay" id="shiftModal">
                <div class="modal-content">
                    <h3 id="modalTitle">Přiřadit moderátory</h3>
                    <p>Vyberte moderátory pro vybranou hodinu:</p>
                    <input type="hidden" id="modalHour">
                    <div class="checkbox-group" id="modalModeratorsList">
                        <!-- Seznam checkboxů -->
                    </div>
                    <div style="display:flex; gap:10px; justify-content: flex-end;">
                        <button type="button" onclick="closeModal()" style="background: rgba(255,255,255,0.2);">Zrušit</button>
                        <button type="button" onclick="saveShift()">Uložit směnu</button>
                    </div>
                </div>
            </div>

            <script>
                let allModerators = [];
                let currentShifts = [];
                
                // Nastavení dnešního data po načtení
                document.getElementById('datePicker').valueAsDate = new Date();

                async function initCalendar() {
                    // Nejdříve stáhneme všechny moderátory pro spárování jmen
                    const resMod = await fetch('/radiowebsystem/api/moderators');
                    const jsonMod = await resMod.json();
                    allModerators = jsonMod.data || [];
                    loadCalendar();
                }

                async function loadCalendar() {
                    const date = document.getElementById('datePicker').value;
                    if(!date) return;
                    
                    const resShifts = await fetch('/radiowebsystem/api/calendar');
                    const jsonShifts = await resShifts.json();
                    
                    // Filtrovat směny jen pro vybraný den
                    currentShifts = (jsonShifts.data || []).filter(s => s.date === date);
                    
                    const tbody = document.getElementById('calendarTableBody');
                    tbody.innerHTML = '';
                    
                    // Vykreslit 24 hodin
                    for(let h = 0; h < 24; h++) {
                        const hourFormatted = h.toString().padStart(2, '0') + ':00 - ' + (h+1).toString().padStart(2, '0') + ':00';
                        
                        // Najít směnu pro tuto hodinu
                        const shift = currentShifts.find(s => parseInt(s.hour) === h);
                        let modNames = '<span style="color:#b026ff; font-weight: bold;">🤖 DJ Autopilot</span>';
                        
                        if (shift && shift.moderator_ids && shift.moderator_ids.length > 0) {
                            const names = shift.moderator_ids.map(id => {
                                const m = allModerators.find(x => x.id === id);
                                return m ? m.name : 'Neznámý';
                            });
                            modNames = names.join(', ');
                        }

                        const tr = document.createElement('tr');
                        tr.innerHTML = `
                            <td style="font-weight:bold;">${hourFormatted}</td>
                            <td>${modNames}</td>
                            <td><button class="action-btn" onclick="openModal(${h})">Spravovat</button></td>
                        `;
                        tbody.appendChild(tr);
                    }
                }

                function openModal(hour) {
                    const date = document.getElementById('datePicker').value;
                    document.getElementById('modalTitle').innerText = `Směna ${date} v ${hour}:00`;
                    document.getElementById('modalHour').value = hour;
                    
                    const shift = currentShifts.find(s => parseInt(s.hour) === hour);
                    const selectedIds = shift ? shift.moderator_ids : [];
                    
                    const list = document.getElementById('modalModeratorsList');
                    list.innerHTML = '';
                    
                    allModerators.forEach(mod => {
                        if(!mod.active) return; // Ukazovat jen aktivní moderátory
                        const checked = selectedIds.includes(mod.id) ? 'checked' : '';
                        list.innerHTML += `<label><input type="checkbox" value="${mod.id}" ${checked}> ${mod.name}</label>`;
                    });
                    
                    if(list.innerHTML === '') list.innerHTML = 'Žádný aktivní moderátor k dispozici.';
                    
                    document.getElementById('shiftModal').style.display = 'flex';
                }

                function closeModal() {
                    document.getElementById('shiftModal').style.display = 'none';
                }

                async function saveShift() {
                    const date = document.getElementById('datePicker').value;
                    const hour = document.getElementById('modalHour').value;
                    
                    // Získat zaškrtnutá ID
                    const checkboxes = document.querySelectorAll('#modalModeratorsList input[type="checkbox"]:checked');
                    const moderator_ids = Array.from(checkboxes).map(cb => cb.value);
                    
                    await fetch('/radiowebsystem/api/calendar', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ date, hour, moderator_ids })
                    });
                    
                    closeModal();
                    loadCalendar();
                }

                // Prvotní načtení
                initCalendar();
            </script>
            
        <?php elseif ($mainSection === 'moderator-profile'): 
            $modId = $routeParts[1] ?? '';
        ?>
            <a href="?route=moderators" style="color:var(--accent); text-decoration:none;">&larr; Zpět na seznam moderátorů</a>
            <h1>Karta moderátora</h1>
            
            <div class="glass" style="padding: 20px; margin-bottom: 20px;" id="profileHeader">
                <h2>Načítám...</h2>
            </div>
            
            <div class="glass" style="padding: 20px;">
                <h3>Naplánované / Odehrané směny</h3>
                <table>
                    <thead>
                        <tr>
                            <th>Datum</th>
                            <th>Čas</th>
                            <th>Stav</th>
                        </tr>
                    </thead>
                    <tbody id="profileShiftsTable">
                        <tr><td colspan="3">Načítám data...</td></tr>
                    </tbody>
                </table>
            </div>

            <script>
                async function loadProfile() {
                    const modId = '<?php echo htmlspecialchars($modId); ?>';
                    if (!modId) return document.getElementById('profileHeader').innerHTML = '<h2>Chyba: Nebyl zadán moderátor</h2>';
                    
                    const res = await fetch(`/radiowebsystem/api/moderator-profile?id=${modId}`);
                    const json = await res.json();
                    
                    if (json.status === 'error') return document.getElementById('profileHeader').innerHTML = `<h2>${json.message}</h2>`;

                    const mod = json.data.moderator;
                    document.getElementById('profileHeader').innerHTML = `
                        <h2>${mod.name}</h2>
                        <p><strong>E-mail:</strong> ${mod.email || '-'}</p>
                        <p><strong>Stav:</strong> ${mod.active ? '🟢 Aktivní' : '🔴 Neaktivní'}</p>
                    `;

                    const tbody = document.getElementById('profileShiftsTable');
                    if (json.data.shifts.length === 0) return tbody.innerHTML = '<tr><td colspan="3">Žádné směny v kalendáři.</td></tr>';
                    
                    tbody.innerHTML = '';
                    const nowStr = new Date().toISOString().split('T')[0] + ' ' + new Date().getHours().toString().padStart(2, '0');

                    json.data.shifts.forEach(shift => {
                        const shiftStr = shift.date + ' ' + shift.hour.toString().padStart(2, '0');
                        const state = shiftStr < nowStr ? 'Odehráno' : (shiftStr === nowStr ? '🔴 ON-AIR' : 'Čeká');
                        const color = shiftStr < nowStr ? '#aaa' : (shiftStr === nowStr ? 'var(--accent)' : 'white');

                        tbody.innerHTML += `<tr style="color: ${color}"><td>${shift.date}</td><td>${shift.hour.toString().padStart(2, '0')}:00 - ${(parseInt(shift.hour)+1).toString().padStart(2, '0')}:00</td><td>${state}</td></tr>`;
                    });
                }
                loadProfile();
            </script>
            
        <?php elseif ($mainSection === 'ads'): ?>
            <h1>Systém pro zákazníky a obchodníky</h1>
            
            <div style="display:flex; gap: 10px; margin-bottom: 20px;">
                <button onclick="showAdsTab('customers')">Zákazníci a Obchodníci</button>
                <button onclick="showAdsTab('spaces')">Reklamní prostory</button>
                <button onclick="showAdsTab('campaigns')">Správa kampaní</button>
            </div>

            <!-- CUSTOMERS -->
            <div id="tab-customers" class="ads-tab glass" style="padding: 20px; display:block;">
                <h3>Přidat / Upravit osobu</h3>
                <form id="form-customers" class="form-group" style="flex-wrap: wrap;">
                    <input type="hidden" id="custId">
                    <input type="text" id="custName" placeholder="Jméno / Název firmy" required>
                    <select id="custType">
                        <option value="customer">Zákazník</option>
                        <option value="sales">Obchodník</option>
                    </select>
                    <input type="email" id="custEmail" placeholder="E-mail">
                    <input type="text" id="custPhone" placeholder="Telefon">
                    <button type="submit">Uložit</button>
                    <button type="button" onclick="document.getElementById('form-customers').reset(); document.getElementById('custId').value='';" style="background: rgba(255,255,255,0.2);">Zrušit</button>
                </form>
                <table>
                    <thead><tr><th>Název</th><th>Typ</th><th>E-mail</th><th>Telefon</th><th>Akce</th></tr></thead>
                    <tbody id="tbody-customers"></tbody>
                </table>
            </div>

            <!-- SPACES -->
            <div id="tab-spaces" class="ads-tab glass" style="padding: 20px; display:none;">
                <h3>Přidat / Upravit reklamní prostor</h3>
                <form id="form-spaces" class="form-group">
                    <input type="hidden" id="spaceId">
                    <input type="text" id="spaceName" placeholder="Název prostoru (např. Ranní show)" required>
                    <input type="number" id="spaceMaxSpots" placeholder="Max. spotů za hodinu" required min="1">
                    <button type="submit">Uložit</button>
                    <button type="button" onclick="document.getElementById('form-spaces').reset(); document.getElementById('spaceId').value='';" style="background: rgba(255,255,255,0.2);">Zrušit</button>
                </form>
                <table>
                    <thead><tr><th>Název prostoru</th><th>Max. spotů</th><th>Akce</th></tr></thead>
                    <tbody id="tbody-spaces"></tbody>
                </table>
            </div>

            <!-- CAMPAIGNS -->
            <div id="tab-campaigns" class="ads-tab glass" style="padding: 20px; display:none;">
                <h3>Přidat / Upravit kampaň</h3>
                <form id="form-campaigns" class="form-group" style="flex-wrap: wrap;">
                    <input type="hidden" id="campId">
                    <input type="text" id="campName" placeholder="Název kampaně" required>
                    <select id="campCustomer" required><option value="">-- Zákazník --</option></select>
                    <select id="campSpace" required><option value="">-- Prostor --</option></select>
                    <div style="display:flex; align-items:center; gap:10px;">Období: <input type="date" id="campStart" required> až <input type="date" id="campEnd" required></div>
                    <label><input type="checkbox" id="campActive" checked> Aktivní</label>
                    <button type="submit">Uložit</button>
                    <button type="button" onclick="document.getElementById('form-campaigns').reset(); document.getElementById('campId').value='';" style="background: rgba(255,255,255,0.2);">Zrušit</button>
                </form>
                <table>
                    <thead><tr><th>Název</th><th>Zákazník</th><th>Prostor</th><th>Od - Do</th><th>Stav</th><th>Akce</th></tr></thead>
                    <tbody id="tbody-campaigns"></tbody>
                </table>
            </div>

            <script>
                function showAdsTab(tab) {
                    document.querySelectorAll('.ads-tab').forEach(el => el.style.display = 'none');
                    document.getElementById('tab-' + tab).style.display = 'block';
                    loadAdsData();
                }

                let allCustomers = [];
                let allSpaces = [];

                async function apiReq(endpoint, method='GET', body=null) {
                    const opts = { method, headers: {'Content-Type': 'application/json'} };
                    if(body) opts.body = JSON.stringify(body);
                    const res = await fetch('/radiowebsystem/api/' + endpoint, opts);
                    return await res.json();
                }

                async function loadAdsData() {
                    // Zákazníci
                    allCustomers = (await apiReq('customers')).data || [];
                    document.getElementById('tbody-customers').innerHTML = allCustomers.map(c => `
                        <tr><td>${c.name}</td><td>${c.type==='sales'?'💼 Obchodník':'🛒 Zákazník'}</td><td>${c.email}</td><td>${c.phone}</td>
                        <td><button class="action-btn" onclick='editData("customers", ${JSON.stringify(c)})'>Upravit</button>
                        <button class="action-btn btn-delete" onclick="delItem('customers', '${c.id}')">Smazat</button></td></tr>`).join('');

                    // Prostory
                    allSpaces = (await apiReq('ad_spaces')).data || [];
                    document.getElementById('tbody-spaces').innerHTML = allSpaces.map(s => `
                        <tr><td>${s.name}</td><td>${s.maxSpots}</td>
                        <td><button class="action-btn" onclick='editData("spaces", ${JSON.stringify(s)})'>Upravit</button>
                        <button class="action-btn btn-delete" onclick="delItem('ad_spaces', '${s.id}')">Smazat</button></td></tr>`).join('');

                    // Kampaně
                    const allCamps = (await apiReq('campaigns')).data || [];
                    
                    // Plnění selectů pro formulář kampaní
                    document.getElementById('campCustomer').innerHTML = '<option value="">-- Zákazník --</option>' + allCustomers.filter(c => c.type === 'customer').map(c => `<option value="${c.id}">${c.name}</option>`).join('');
                    document.getElementById('campSpace').innerHTML = '<option value="">-- Prostor --</option>' + allSpaces.map(s => `<option value="${s.id}">${s.name}</option>`).join('');

                    document.getElementById('tbody-campaigns').innerHTML = allCamps.map(c => {
                        const custName = allCustomers.find(x => x.id === c.customerId)?.name || '?';
                        const spaceName = allSpaces.find(x => x.id === c.spaceId)?.name || '?';
                        return `<tr><td>${c.name}</td><td>${custName}</td><td>${spaceName}</td><td>${c.start} až ${c.end}</td><td>${c.active?'🟢':'🔴'}</td>
                        <td>
                        <button class="action-btn btn-info" onclick="sendReport('${c.id}')">Report</button>
                        <button class="action-btn" onclick='editData("campaigns", ${JSON.stringify(c)})'>Upravit</button>
                        <button class="action-btn btn-delete" onclick="delItem('campaigns', '${c.id}')">Smazat</button></td></tr>`;
                    }).join('');
                }

                function editData(type, data) {
                    if(type === 'customers') { document.getElementById('custId').value = data.id; document.getElementById('custName').value = data.name; document.getElementById('custType').value = data.type; document.getElementById('custEmail').value = data.email; document.getElementById('custPhone').value = data.phone; }
                    if(type === 'spaces') { document.getElementById('spaceId').value = data.id; document.getElementById('spaceName').value = data.name; document.getElementById('spaceMaxSpots').value = data.maxSpots; }
                    if(type === 'campaigns') { document.getElementById('campId').value = data.id; document.getElementById('campName').value = data.name; document.getElementById('campCustomer').value = data.customerId; document.getElementById('campSpace').value = data.spaceId; document.getElementById('campStart').value = data.start; document.getElementById('campEnd').value = data.end; document.getElementById('campActive').checked = data.active; }
                }

                async function delItem(endpoint, id) {
                    if(!confirm('Smazat položku?')) return;
                    await apiReq(endpoint, 'DELETE', {id});
                    loadAdsData();
                }

                async function sendReport(id) {
                    if(!confirm('Vygenerovat PDF report a odeslat jej zákazníkovi na e-mail?')) return;
                    const res = await fetch('/radiowebsystem/api/campaign-report?id=' + id);
                    const json = await res.json();
                    alert(json.message);
                }

                // Ukládání
                document.getElementById('form-customers').addEventListener('submit', async(e)=>{ e.preventDefault(); await apiReq('customers', 'POST', { id: document.getElementById('custId').value, name: document.getElementById('custName').value, type: document.getElementById('custType').value, email: document.getElementById('custEmail').value, phone: document.getElementById('custPhone').value }); document.getElementById('form-customers').reset(); document.getElementById('custId').value=''; loadAdsData(); });
                document.getElementById('form-spaces').addEventListener('submit', async(e)=>{ e.preventDefault(); await apiReq('ad_spaces', 'POST', { id: document.getElementById('spaceId').value, name: document.getElementById('spaceName').value, maxSpots: document.getElementById('spaceMaxSpots').value }); document.getElementById('form-spaces').reset(); document.getElementById('spaceId').value=''; loadAdsData(); });
                document.getElementById('form-campaigns').addEventListener('submit', async(e)=>{ e.preventDefault(); await apiReq('campaigns', 'POST', { id: document.getElementById('campId').value, name: document.getElementById('campName').value, customerId: document.getElementById('campCustomer').value, spaceId: document.getElementById('campSpace').value, start: document.getElementById('campStart').value, end: document.getElementById('campEnd').value, active: document.getElementById('campActive').checked }); document.getElementById('form-campaigns').reset(); document.getElementById('campId').value=''; loadAdsData(); });

                loadAdsData();
            </script>
            
        <?php elseif ($mainSection === 'pages'): ?>
            <h1>Stránky a Články (Obsah webu)</h1>
            
            <div class="glass" style="padding: 20px; margin-bottom: 20px;">
                <h3>Přidat / Upravit článek</h3>
                <form id="form-pages" class="form-group" style="flex-wrap: wrap;">
                    <input type="hidden" id="pageId">
                    <input type="text" id="pageTitle" placeholder="Titulek článku" required style="width:48%;">
                    <input type="text" id="pageSlug" placeholder="URL slug (např. muj-clanek)" required style="width:48%;">
                    <label style="width:100%; margin-top: 10px;">Ilustrační obrázek: <input type="file" id="pageImage" accept="image/*" style="width:100%; border: 1px solid var(--glass-border); padding: 8px; border-radius: 8px; background: rgba(0,0,0,0.2);"></label>
                    <div id="pageImagePreview" style="width:100%; margin-bottom:10px;"></div>
                    <textarea id="pageContent" rows="8" placeholder="Obsah článku (HTML povoleno)" style="width:100%; background: rgba(0,0,0,0.2); color:#fff; border:1px solid var(--glass-border); padding:10px; border-radius:8px;"></textarea>
                    <button type="submit">Uložit článek</button>
                    <button type="button" onclick="document.getElementById('form-pages').reset(); document.getElementById('pageId').value=''; document.getElementById('pageImagePreview').innerHTML='';" style="background: rgba(255,255,255,0.2);">Zrušit</button>
                </form>
            </div>
            
            <div class="glass" style="padding: 20px;">
                <table>
                    <thead><tr><th>Titulek</th><th>Odkaz na webu</th><th>Akce</th></tr></thead>
                    <tbody id="tbody-pages"></tbody>
                </table>
            </div>

            <script>
                async function loadPages() {
                    const res = await fetch('/radiowebsystem/api/pages');
                    const json = await res.json();
                    document.getElementById('tbody-pages').innerHTML = (json.data || []).map(p => `<tr><td>${p.title}</td><td>/clanek/${p.slug}</td><td><button class="action-btn" onclick='editPage(${JSON.stringify(p).replace(/'/g, "\\'")})'>Upravit</button><button class="action-btn btn-delete" onclick="delPage('${p.id}')">Smazat</button></td></tr>`).join('');
                }
                function editPage(p) { document.getElementById('pageId').value = p.id; document.getElementById('pageTitle').value = p.title; document.getElementById('pageSlug').value = p.slug; document.getElementById('pageContent').value = p.content; document.getElementById('pageImagePreview').innerHTML = p.image ? `<img src="/radiowebsystem/${p.image}" style="max-height:100px; border-radius:8px;">` : ''; }
                async function delPage(id) { if(!confirm('Smazat?')) return; await fetch('/radiowebsystem/api/pages', { method: 'DELETE', headers: {'Content-Type':'application/json'}, body: JSON.stringify({id}) }); loadPages(); }
                
                document.getElementById('form-pages').addEventListener('submit', async (e) => {
                    e.preventDefault();
                    const fileInput = document.getElementById('pageImage');
                    let base64 = null;
                    if (fileInput.files.length > 0) {
                        base64 = await new Promise(resolve => {
                            const reader = new FileReader();
                            reader.onload = e => resolve(e.target.result);
                            reader.readAsDataURL(fileInput.files[0]);
                        });
                    }
                    const payload = { id: document.getElementById('pageId').value, title: document.getElementById('pageTitle').value, slug: document.getElementById('pageSlug').value, content: document.getElementById('pageContent').value };
                    if (base64) payload.image_base64 = base64;
                    
                    await fetch('/radiowebsystem/api/pages', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) });
                    document.getElementById('form-pages').reset(); document.getElementById('pageId').value=''; document.getElementById('pageImagePreview').innerHTML=''; loadPages();
                });
                loadPages();
            </script>
            
        <?php elseif ($mainSection === 'requests'): ?>
            <h1>Písničky na přání</h1>
            
            <div class="glass" style="padding: 20px;">
                <table>
                    <thead><tr><th>Datum přijetí</th><th>Od koho</th><th>Písnička</th><th>Vzkaz</th><th>Akce</th></tr></thead>
                    <tbody id="tbody-requests"></tbody>
                </table>
            </div>

            <script>
                async function loadRequests() {
                    const res = await fetch('/radiowebsystem/api/requests');
                    const json = await res.json();
                    const reqs = json.data || [];
                    reqs.sort((a,b) => new Date(b.created_at) - new Date(a.created_at));
                    document.getElementById('tbody-requests').innerHTML = reqs.map(r => `<tr><td>${r.created_at}</td><td>${r.name}</td><td><strong>${r.song}</strong></td><td>${r.message || '-'}</td><td><button class="action-btn btn-delete" onclick="delReq('${r.id}')">Smazat</button></td></tr>`).join('');
                }
                async function delReq(id) { if(!confirm('Opravdu smazat toto přání?')) return; await fetch('/radiowebsystem/api/requests', { method: 'DELETE', headers: {'Content-Type':'application/json'}, body: JSON.stringify({id}) }); loadRequests(); }
                loadRequests();
            </script>
            
        <?php elseif ($mainSection === 'songs'): ?>
            <h1>Historie odehraných songů</h1>
            
            <div class="glass" style="padding: 20px; margin-bottom: 20px;">
                <h3>Simulátor přehrání songu (Bod 8)</h3>
                <p>Jelikož zatím není napojen reálný stream poslechovosti, můžete historii plnit ručně zde:</p>
                <form id="form-songs" class="form-group">
                    <input type="text" id="songArtist" placeholder="Interpret (např. Queen)" required>
                    <input type="text" id="songTitle" placeholder="Název songu (např. Radio Ga Ga)" required>
                    <button type="submit">Zaznamenat do historie</button>
                </form>
            </div>
            
            <div class="glass" style="padding: 20px;">
                <table>
                    <thead><tr><th style="width:180px;">Čas odehrání</th><th>Interpret</th><th>Název songu</th></tr></thead>
                    <tbody id="tbody-songs"></tbody>
                </table>
            </div>

            <script>
                async function loadSongs() {
                    const res = await fetch('/radiowebsystem/api/songs');
                    const json = await res.json();
                    document.getElementById('tbody-songs').innerHTML = (json.data || []).map(s => `<tr><td>${s.played_at}</td><td>${s.artist}</td><td style="font-weight:bold;">${s.title}</td></tr>`).join('');
                }
                
                document.getElementById('form-songs').addEventListener('submit', async (e) => {
                    e.preventDefault();
                    await fetch('/radiowebsystem/api/songs', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ artist: document.getElementById('songArtist').value, title: document.getElementById('songTitle').value })
                    });
                    document.getElementById('form-songs').reset();
                    loadSongs();
                });
                
                loadSongs();
            </script>
            
        <?php elseif ($mainSection === 'template'): ?>
            <h1>Vzhled, Šablona a Boxy webu</h1>
            
            <div style="display:flex; gap: 10px; margin-bottom: 20px;">
                <button onclick="showTplTab('layout')">Šablona a Hlavička</button>
                <button onclick="showTplTab('menu')">Menu webu</button>
                <button onclick="showTplTab('boxes')">Správa boxíků</button>
            </div>

            <!-- LAYOUT (Hlavička / Patička) -->
            <div id="tpl-layout" class="tpl-tab glass" style="padding: 20px; display:block;">
                <h3>Základní HTML šablona</h3>
                <form id="form-layout">
                    <label style="display:block; margin-bottom:5px;">Hlavička (Header HTML)</label>
                    <textarea id="tplHeader" rows="6" placeholder="<header>...</header>" style="width:100%; margin-bottom:15px; background: rgba(0,0,0,0.2); color:#fff; border:1px solid var(--glass-border); padding: 10px; border-radius: 8px; font-family: monospace;"></textarea>
                    <label style="display:block; margin-bottom:5px;">Patička (Footer HTML)</label>
                    <textarea id="tplFooter" rows="6" placeholder="<footer>...</footer>" style="width:100%; margin-bottom:15px; background: rgba(0,0,0,0.2); color:#fff; border:1px solid var(--glass-border); padding: 10px; border-radius: 8px; font-family: monospace;"></textarea>
                    <button type="submit">Uložit šablonu</button>
                </form>
            </div>

            <!-- MENU WEBU -->
            <div id="tpl-menu" class="tpl-tab glass" style="padding: 20px; display:none;">
                <h3>Položky hlavního menu</h3>
                <form id="form-menu" class="form-group" style="flex-wrap: wrap;">
                    <input type="hidden" id="menuId">
                    <input type="text" id="menuLabel" placeholder="Název položky (např. O nás)" required>
                    <input type="text" id="menuUrl" placeholder="URL odkaz (např. /o-nas)" required>
                    <input type="number" id="menuOrder" placeholder="Pořadí" required value="1" style="width:100px;">
                    <button type="submit">Uložit položku</button>
                    <button type="button" onclick="document.getElementById('form-menu').reset(); document.getElementById('menuId').value='';" style="background: rgba(255,255,255,0.2);">Zrušit</button>
                </form>
                <table>
                    <thead><tr><th>Pořadí</th><th>Název</th><th>URL</th><th>Akce</th></tr></thead>
                    <tbody id="tbody-menu"></tbody>
                </table>
            </div>

            <!-- BOXY -->
            <div id="tpl-boxes" class="tpl-tab glass" style="padding: 20px; display:none;">
                <h3>Postranní boxy (Widgety)</h3>
                <form id="form-boxes" class="form-group" style="flex-wrap: wrap; align-items:flex-start;">
                    <input type="hidden" id="boxId">
                    <input type="hidden" id="boxIsSystem">
                    <input type="hidden" id="boxSystemType">
                    <div style="display:flex; gap:10px; width: 100%;">
                        <input type="text" id="boxTitle" placeholder="Titulek boxu" required style="flex:1;">
                        <select id="boxPosition"><option value="left">Levý panel</option><option value="right">Pravý panel</option></select>
                        <input type="number" id="boxOrder" placeholder="Pořadí" required value="1" style="width:100px;">
                    </div>
                    <div style="width: 100%; margin-top:10px;" id="boxContentWrapper">
                        <textarea id="boxContent" rows="4" placeholder="Vlastní HTML obsah boxu (např. reklama, text...)" style="width:100%; background: rgba(0,0,0,0.2); color:#fff; border:1px solid var(--glass-border); padding:10px; border-radius:8px; font-family: monospace;"></textarea>
                    </div>
                    <div style="width: 100%; margin-top: 10px;">
                        <button type="submit">Uložit box</button>
                        <button type="button" onclick="resetBoxForm();" style="background: rgba(255,255,255,0.2);">Zrušit</button>
                    </div>
                </form>
                <table>
                    <thead><tr><th>Pořadí</th><th>Titulek</th><th>Panel</th><th>Typ</th><th>Akce</th></tr></thead>
                    <tbody id="tbody-boxes"></tbody>
                </table>
            </div>

            <script>
                function showTplTab(tab) {
                    document.querySelectorAll('.tpl-tab').forEach(el => el.style.display = 'none');
                    document.getElementById('tpl-' + tab).style.display = 'block';
                    loadTplData();
                }
                
                function resetBoxForm() {
                    document.getElementById('form-boxes').reset();
                    document.getElementById('boxId').value = '';
                    document.getElementById('boxIsSystem').value = '';
                    document.getElementById('boxSystemType').value = '';
                    document.getElementById('boxContentWrapper').style.display = 'block';
                }

                async function loadTplData() {
                    // Načtení šablony
                    const resTpl = await fetch('/radiowebsystem/api/template-config');
                    const jsonTpl = await resTpl.json();
                    document.getElementById('tplHeader').value = jsonTpl.data.header || '';
                    document.getElementById('tplFooter').value = jsonTpl.data.footer || '';

                    // Načtení menu
                    const resMenu = await fetch('/radiowebsystem/api/menus');
                    const jsonMenu = await resMenu.json();
                    const menus = jsonMenu.data || [];
                    menus.sort((a,b) => parseInt(a.order) - parseInt(b.order));
                    document.getElementById('tbody-menu').innerHTML = menus.map(m => `<tr><td>${m.order}</td><td>${m.label}</td><td>${m.url}</td><td><button class="action-btn" onclick='editMenu(${JSON.stringify(m)})'>Upravit</button><button class="action-btn btn-delete" onclick="delItem('menus', '${m.id}', loadTplData)">Smazat</button></td></tr>`).join('');

                    // Načtení boxů
                    const resBoxes = await fetch('/radiowebsystem/api/boxes');
                    const jsonBoxes = await resBoxes.json();
                    document.getElementById('tbody-boxes').innerHTML = (jsonBoxes.data || []).map(b => `<tr><td>${b.order}</td><td>${b.title}</td><td>${b.position==='left'?'Levý':'Pravý'}</td><td>${b.is_system?'🔒 Systémový':'✎ Vlastní'}</td><td><button class="action-btn" onclick='editBox(${JSON.stringify(b).replace(/'/g, "\\'")})'>Upravit</button>${!b.is_system ? `<button class="action-btn btn-delete" onclick="delItem('boxes', '${b.id}', loadTplData)">Smazat</button>` : ''}</td></tr>`).join('');
                }

                function editMenu(m) { document.getElementById('menuId').value = m.id; document.getElementById('menuLabel').value = m.label; document.getElementById('menuUrl').value = m.url; document.getElementById('menuOrder').value = m.order; }
                function editBox(b) { document.getElementById('boxId').value = b.id; document.getElementById('boxTitle').value = b.title; document.getElementById('boxPosition').value = b.position; document.getElementById('boxOrder').value = b.order; document.getElementById('boxContent').value = b.content || ''; document.getElementById('boxIsSystem').value = b.is_system ? '1' : ''; document.getElementById('boxSystemType').value = b.system_type || ''; document.getElementById('boxContentWrapper').style.display = b.is_system ? 'none' : 'block'; }
                
                async function delItem(endpoint, id, callback) {
                    if(!confirm('Opravdu smazat?')) return;
                    const res = await fetch('/radiowebsystem/api/' + endpoint, { method: 'DELETE', headers: {'Content-Type':'application/json'}, body: JSON.stringify({id}) });
                    const json = await res.json();
                    if(json.status === 'error') alert(json.message);
                    callback();
                }

                document.getElementById('form-layout').addEventListener('submit', async(e)=>{ e.preventDefault(); await fetch('/radiowebsystem/api/template-config', {method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({header: document.getElementById('tplHeader').value, footer: document.getElementById('tplFooter').value})}); alert('Šablona uložena.'); });
                document.getElementById('form-menu').addEventListener('submit', async(e)=>{ e.preventDefault(); await fetch('/radiowebsystem/api/menus', {method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({id: document.getElementById('menuId').value, label: document.getElementById('menuLabel').value, url: document.getElementById('menuUrl').value, order: document.getElementById('menuOrder').value})}); document.getElementById('form-menu').reset(); document.getElementById('menuId').value=''; loadTplData(); });
                document.getElementById('form-boxes').addEventListener('submit', async(e)=>{ e.preventDefault(); await fetch('/radiowebsystem/api/boxes', {method:'POST', headers:{'Content-Type':'application/json'}, body: JSON.stringify({id: document.getElementById('boxId').value, title: document.getElementById('boxTitle').value, position: document.getElementById('boxPosition').value, order: document.getElementById('boxOrder').value, content: document.getElementById('boxContent').value, is_system: document.getElementById('boxIsSystem').value === '1', system_type: document.getElementById('boxSystemType').value})}); resetBoxForm(); loadTplData(); });

                loadTplData();
            </script>

        <?php elseif ($mainSection === 'stats'): ?>
            <h1>Statistika poslechovosti streamu</h1>
            
            <div class="glass" style="padding: 20px; margin-bottom: 20px;">
                <canvas id="listenersChart" height="100"></canvas>
            </div>
            <div style="text-align: right;">
                <button onclick="syncIceCast()">Aktualizovat nyní</button>
            </div>
            
            <script>
                let chartInstance = null;
                async function loadStats() {
                    const res = await fetch('/radiowebsystem/api/stats');
                    const json = await res.json();
                    const labels = json.data.map(d => {
                        const date = new Date(d.timestamp);
                        return date.getHours().toString().padStart(2,'0') + ':' + date.getMinutes().toString().padStart(2,'0') + ':' + date.getSeconds().toString().padStart(2,'0');
                    });
                    const data = json.data.map(d => d.listeners);
                    
                    if (chartInstance) chartInstance.destroy();
                    const ctx = document.getElementById('listenersChart').getContext('2d');
                    chartInstance = new Chart(ctx, {
                        type: 'line',
                        data: {
                            labels: labels,
                            datasets: [{ label: 'Počet posluchačů', data: data, borderColor: '#00d2ff', backgroundColor: 'rgba(0, 210, 255, 0.2)', borderWidth: 2, fill: true, tension: 0.4 }]
                        },
                        options: {
                            scales: { y: { beginAtZero: true, grid: { color: 'rgba(255,255,255,0.1)' }, ticks: { color: '#fff' } }, x: { grid: { color: 'rgba(255,255,255,0.1)' }, ticks: { color: '#fff' } } },
                            plugins: { legend: { labels: { color: '#fff' } } }
                        }
                    });
                }
                
                async function syncIceCast() {
                    await fetch('/radiowebsystem/api/stats-sync');
                    loadStats();
                }
                
                loadStats();
                // Autorefresh každých 30 vteřin
                setInterval(syncIceCast, 30000);
            </script>
            
        <?php elseif ($mainSection === 'settings'): ?>
            <h1>Nastavení systému</h1>
            
            <div class="glass" style="padding: 20px; margin-bottom: 20px; max-width: 600px;">
                <h3>SMTP Nastavení (Odesílání e-mailů)</h3>
                <form id="form-settings">
                    <div style="display:grid; grid-template-columns: 1fr 1fr; gap: 15px; margin-bottom: 15px;">
                        <div><label style="display:block; margin-bottom:5px;">SMTP Server (Host)</label><input type="text" id="smtpHost" style="width:100%; box-sizing:border-box;"></div>
                        <div><label style="display:block; margin-bottom:5px;">SMTP Port</label><input type="number" id="smtpPort" style="width:100%; box-sizing:border-box;"></div>
                        <div><label style="display:block; margin-bottom:5px;">Uživatelské jméno</label><input type="text" id="smtpUser" style="width:100%; box-sizing:border-box;"></div>
                        <div><label style="display:block; margin-bottom:5px;">Heslo</label><input type="password" id="smtpPass" style="width:100%; box-sizing:border-box;"></div>
                        <div>
                            <label style="display:block; margin-bottom:5px;">Šifrování</label>
                            <select id="smtpEnc" style="width:100%; box-sizing:border-box;">
                                <option value="">Žádné</option>
                                <option value="tls">STARTTLS</option>
                                <option value="ssl">SSL/SMTPS</option>
                            </select>
                        </div>
                        <div><label style="display:block; margin-bottom:5px;">Odesílatel (E-mail)</label><input type="email" id="smtpFromEmail" placeholder="info@radiowebsystem.cz" style="width:100%; box-sizing:border-box;"></div>
                        <div style="grid-column: span 2;"><label style="display:block; margin-bottom:5px;">Odesílatel (Zobrazené jméno)</label><input type="text" id="smtpFromName" placeholder="RadioWebSystem" style="width:100%; box-sizing:border-box;"></div>
                    </div>
                    
                    <hr style="border-color: rgba(255,255,255,0.2); margin: 20px 0;">
                    <h3>Nastavení streamu (IceCast2)</h3>
                    <div style="margin-bottom: 15px;">
                        <label style="display:block; margin-bottom:5px;">IceCast Status JSON URL (např. http://server:8000/status-json.xsl)</label>
                        <input type="text" id="icecastUrl" placeholder="http://..." style="width:100%; box-sizing:border-box;">
                        <small style="color:#ccc;">Pokud nevyplníte, bude systém pro testovací účely generovat náhodná data do grafu.</small>
                    </div>
                    <div style="margin-bottom: 15px;">
                        <label style="display:block; margin-bottom:5px;">Audio Stream URL pro Přehrávač (např. http://server:8000/stream)</label>
                        <input type="text" id="streamUrl" placeholder="http://..." style="width:100%; box-sizing:border-box;">
                    </div>
                    
                    <button type="submit" style="width: 100%;">Uložit veškeré nastavení</button>
                    <div id="settingsSuccess" style="display:none; color:#38ef7d; font-weight:bold; margin-top:15px; padding:10px; background:rgba(56, 239, 125, 0.1); border:1px solid rgba(56, 239, 125, 0.3); border-radius:8px;"></div>
                </form>
            </div>

            <script>
                async function loadSettings() {
                    const res = await fetch('/radiowebsystem/api/settings-config');
                    const json = await res.json();
                    if(json.data && json.data.smtp) {
                        const s = json.data.smtp;
                        document.getElementById('smtpHost').value = s.host || '';
                        document.getElementById('smtpPort').value = s.port || '';
                        document.getElementById('smtpUser').value = s.username || '';
                        document.getElementById('smtpPass').value = s.password || '';
                        document.getElementById('smtpEnc').value = s.encryption || '';
                        document.getElementById('smtpFromEmail').value = s.from_email || '';
                        document.getElementById('smtpFromName').value = s.from_name || '';
                    }
                    if(json.data && json.data.icecast_url !== undefined) document.getElementById('icecastUrl').value = json.data.icecast_url;
                    if(json.data && json.data.stream_url !== undefined) document.getElementById('streamUrl').value = json.data.stream_url;
                }
                
                document.getElementById('form-settings').addEventListener('submit', async (e) => {
                    e.preventDefault();
                    const smtpData = {
                        host: document.getElementById('smtpHost').value, port: document.getElementById('smtpPort').value,
                        username: document.getElementById('smtpUser').value, password: document.getElementById('smtpPass').value,
                        encryption: document.getElementById('smtpEnc').value, from_email: document.getElementById('smtpFromEmail').value,
                        from_name: document.getElementById('smtpFromName').value
                    };
                    const icecastUrl = document.getElementById('icecastUrl').value;
                    const streamUrl = document.getElementById('streamUrl').value;
                    const res = await fetch('/radiowebsystem/api/settings-config', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({smtp: smtpData, icecast_url: icecastUrl, stream_url: streamUrl}) });
                    const json = await res.json();
                    
                    const successMsg = document.getElementById('settingsSuccess');
                    successMsg.innerText = json.message;
                    successMsg.style.display = 'block';
                    setTimeout(() => successMsg.style.display = 'none', 4000);
                    loadSettings(); // Ihned znovu načte čerstvá data
                });
                loadSettings();
            </script>
        <?php endif; ?>
    </div>
<?php else: ?>
    <!-- FRONTEND UI (Veřejný web) -->
    <div class="fw-container">
        
        <!-- HORNÍ PANEL (Logo + Menu + Titulek) -->
        <div class="fw-topbar glass">
            <div class="fw-topbar-left">
                <a href="/" style="text-decoration:none; color:inherit; display:flex; flex-direction:column; align-items:inherit;">
                <?php if (!empty($tpl['logo_image'])): ?>
                    <img src="/<?php echo htmlspecialchars($tpl['logo_image']); ?>" style="max-height: <?php echo htmlspecialchars($tpl['logo_size']); ?>; max-width: 100%; object-fit: contain;">
                <?php endif; ?>
                <?php if (!empty($tpl['site_title'])): ?>
                    <div style="width: 100%; font-size: <?php echo htmlspecialchars($tpl['title_size']); ?>; color: var(--text-color); text-shadow: 0 2px 4px rgba(0,0,0,0.5); margin-top: 10px; font-weight: bold; text-align: <?php echo htmlspecialchars($tpl['title_position']); ?>;"><?php echo htmlspecialchars($tpl['site_title']); ?></div>
                <?php endif; ?>
                </a>
            </div>
            
            <button class="mobile-menu-toggle" onclick="document.querySelector('.fw-nav').classList.toggle('active')">☰ Zobrazit Menu</button>

            <div class="fw-nav">
                <a href="/" title="Domů">🏠</a>
                <?php foreach ($menuTree as $m) {
                    if (empty($m['children'])) {
                        if ($m['url'] === '#play') {
                            echo "<a href=\"#\" class=\"btn-tune-in\" onclick=\"event.preventDefault(); const a=document.getElementById('radioAudio'); if(a&&a.paused) togglePlay();\">🎧 <span class=\"tune-text\" style=\"transition: opacity 0.3s;\">" . htmlspecialchars($m['label']) . "</span></a>";
                        } else {
                            echo "<a href=\"{$m['url']}\">" . htmlspecialchars($m['label']) . "</a>";
                        }
                    } else {
                        echo "<div class=\"menu-dropdown\">";
                        echo "<a href=\"{$m['url']}\">" . htmlspecialchars($m['label']) . " ▼</a>";
                        echo "<div class=\"menu-dropdown-content\">";
                        foreach ($m['children'] as $child) {
                            echo "<a href=\"{$child['url']}\">" . htmlspecialchars($child['label']) . "</a>";
                        }
                        echo "</div></div>";
                    }
                } ?>
            </div>
            
            <div class="fw-topbar-right">
                <div style="display: flex; gap: 15px; align-items: center;">
                        <?php if (!empty($tpl['social_fb'])): ?>
                            <a href="<?php echo htmlspecialchars($tpl['social_fb']); ?>" target="_blank" style="color: var(--accent); text-decoration: none; font-size: 1.5rem; transition: transform 0.2s;" onmouseover="this.style.transform='scale(1.2)'" onmouseout="this.style.transform='scale(1)'">
                                <svg width="24" height="24" fill="currentColor" viewBox="0 0 24 24"><path d="M22.675 0h-21.35c-.732 0-1.325.593-1.325 1.325v21.351c0 .731.593 1.324 1.325 1.324h11.495v-9.294h-3.128v-3.622h3.128v-2.671c0-3.1 1.893-4.788 4.659-4.788 1.325 0 2.463.099 2.795.143v3.24l-1.918.001c-1.504 0-1.795.715-1.795 1.763v2.313h3.587l-.467 3.622h-3.12v9.293h6.116c.73 0 1.323-.593 1.323-1.325v-21.35c0-.732-.593-1.325-1.325-1.325z"/></svg>
                            </a>
                        <?php endif; ?>
                        <?php if (!empty($tpl['social_ig'])): ?>
                            <a href="<?php echo htmlspecialchars($tpl['social_ig']); ?>" target="_blank" style="color: var(--accent); text-decoration: none; font-size: 1.5rem; transition: transform 0.2s;" onmouseover="this.style.transform='scale(1.2)'" onmouseout="this.style.transform='scale(1)'">
                                <svg width="24" height="24" fill="currentColor" viewBox="0 0 24 24"><path d="M12 2.163c3.204 0 3.584.012 4.85.07 3.252.148 4.771 1.691 4.919 4.919.058 1.265.069 1.645.069 4.849 0 3.205-.012 3.584-.069 4.849-.149 3.225-1.664 4.771-4.919 4.919-1.266.058-1.644.07-4.85.07-3.204 0-3.584-.012-4.849-.07-3.26-.149-4.771-1.699-4.919-4.92-.058-1.265-.07-1.644-.07-4.849 0-3.204.013-3.583.07-4.849.149-3.227 1.664-4.771 4.919-4.919 1.266-.057 1.645-.069 4.849-.069zm0-2.163c-3.259 0-3.667.014-4.947.072-4.358.2-6.78 1.72-6.98 6.002-.059 1.281-.073 1.689-.073 4.948 0 3.259.014 3.668.072 4.948.2 4.28 1.721 6.782 6.002 6.98 1.282.058 1.689.072 4.948.072 3.259 0 3.668-.014 4.948-.072 4.281-.2 6.8-1.721 7-6.002.058-1.28.072-1.689.072-4.948 0-3.259-.014-3.667-.072-4.947-.2-4.281-1.721-6.781-6.002-6.98-1.281-.058-1.689-.072-4.948-.072zm0 5.838c-3.403 0-6.162 2.759-6.162 6.162s2.759 6.163 6.162 6.163 6.162-2.759 6.162-6.163c0-3.403-2.759-6.162-6.162-6.162zm0 10.162c-2.209 0-4-1.79-4-4 0-2.209 1.791-4 4-4s4 1.791 4 4c0 2.21-1.791 4-4 4zm6.406-11.845c-.796 0-1.441.645-1.441 1.44s.645 1.44 1.441 1.44c.795 0 1.439-.645 1.439-1.44s-.644-1.44-1.439-1.44z"/></svg>
                            </a>
                        <?php endif; ?>
                    
                    <form action="/" method="GET" style="display:flex; align-items:center; margin-right: 5px;">
                        <input type="text" name="q" placeholder="Hledat na webu..." value="<?php echo htmlspecialchars($_GET['q'] ?? ''); ?>" style="padding: 6px 15px; border-radius: 20px; border: 1px solid var(--glass-border); background: rgba(0,0,0,0.3); color: #fff; outline: none; width: 140px; font-size: 0.9rem;">
                    </form>

                    <!-- Jazykové menu -->
                    <div class="lang-dropdown">
                        <div class="lang-btn"><img src="https://flagcdn.com/w20/<?php echo $flagCodes[$currentLang]; ?>.png" style="width:20px; border-radius:2px;"> <?php echo strtoupper($currentLang); ?> ▼</div>
                        <div class="lang-dropdown-content">
                            <?php foreach ($sysLangs as $code => $name): ?>
                                <a href="?lang=<?php echo $code; ?>" class="<?php echo $currentLang === $code ? 'active' : ''; ?>"><img src="https://flagcdn.com/w20/<?php echo $flagCodes[$code]; ?>.png" style="width:20px; border-radius:2px;"> <?php echo $name; ?></a>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <?php if (!empty($tpl['header'])) echo "<div class='fw-header'>{$tpl['header']}</div>"; ?>
        
        <div class="fw-layout">
            <!-- LEVÉ BOXY -->
            <div class="fw-col-left">
                <?php foreach ($boxes as $b): 
                    if (!is_array($b) || !isset($b['position']) || $b['position'] !== 'left' || (isset($b['active']) && $b['active'] === false)) continue; ?>
                    <div class="fw-box glass">
                        <h3 style="display: flex; justify-content: space-between; align-items: center;">
                            <span><?php echo htmlspecialchars($b['title']); ?></span>
                            <?php if (!empty($b['is_system']) && $b['system_type'] === 'onair' && (!isset($b['content']) || $b['content'] !== '0')): ?>
                                <span style="display:flex; align-items:center; gap:6px; font-family: monospace; color: inherit; background: rgba(0,0,0,0.3); padding: 4px 10px; border-radius: 8px; font-size: 0.85em; box-shadow: inset 0 0 5px rgba(0,0,0,0.5);"><span class="live-indicator" style="width:8px; height:8px; background:lime; border-radius:50%; box-shadow: 0 0 5px lime; transition: opacity 0.2s;"></span><span class="live-clock">--:--:--</span></span>
                            <?php endif; ?>
                        </h3>
                        <?php 
                            if (!empty($b['is_system'])) { 
                                if ($b['system_type'] === 'onair') { echo "<div class='ajax-box-onair'>$onAirText</div>"; }
                                elseif ($b['system_type'] === 'nowplaying') { $artworkHtml = $nowPlayingArtwork ? "<img src='".htmlspecialchars($nowPlayingArtwork)."' style='width:60px; height:60px; border-radius:8px; object-fit:cover; box-shadow:var(--glass-shadow);'>" : "<div style='width:60px; height:60px; background:rgba(0,0,0,0.2); border-radius:8px; display:inline-flex; align-items:center; justify-content:center; font-size:2.5rem; margin:0 auto;'>🎵</div>"; echo "<div class='ajax-box-nowplaying' style='text-align:center;'><a href='/historie' style='text-decoration:none; color:inherit; font-weight:bold; transition:transform 0.2s; display:inline-block; margin-top:5px;' onmouseover=\"this.style.transform='scale(1.05)'\" onmouseout=\"this.style.transform='scale(1)'\" title='Zobrazit historii songů'>{$artworkHtml}<br>{$nowPlaying}</a></div>"; }
                                elseif ($b['system_type'] === 'contact') {
                                    $cHtml = "<form class='form-widget-contact' style='display:flex; flex-direction:column; gap:10px;'><input type='text' name='cwName' placeholder='Jméno (volitelné)' style='width:100%; box-sizing:border-box; background: rgba(0,0,0,0.2); color:white; border: 1px solid var(--glass-border); border-radius:8px; padding:10px;'><input type='email' name='cwEmail' placeholder='Váš e-mail' required style='width:100%; box-sizing:border-box; background: rgba(0,0,0,0.2); color:white; border: 1px solid var(--glass-border); border-radius:8px; padding:10px;'><textarea name='cwMsg' placeholder='Zpráva...' required rows='3' style='width:100%; box-sizing:border-box; background: rgba(0,0,0,0.2); color:white; border: 1px solid var(--glass-border); border-radius:8px; padding:10px;'></textarea>";
                                    if (empty($recaptchaSiteKey)) {
                                        $cHtml .= "<div class='math-captcha-container' style='display:flex; align-items:center; gap:10px; font-size: 0.9rem;'><span>Ochrana: <span class='math1'></span>+<span class='math2'></span>=</span><input type='number' name='cwMath' required style='width:60px; box-sizing:border-box; background: rgba(0,0,0,0.2); color:white; border: 1px solid var(--glass-border); border-radius:8px; padding:5px;'></div>";
                                    } else {
                                        $cHtml .= "<small style='color:var(--text-muted); font-size:0.8rem;'>Chráněno reCAPTCHA</small>";
                                    }
                                    echo $cHtml . "<button type='submit'>Odeslat zprávu</button><div class='cwSuccess' style='display:none; color:var(--accent); font-weight:bold; font-size:0.9rem; text-align:center;'>Zpráva odeslána!</div></form>";
                                }
                                elseif ($b['system_type'] === 'newsletter') {
                                    $nHtml = "<form class='form-widget-newsletter' style='display:flex; flex-direction:column; gap:10px;'><input type='email' name='nwEmail' placeholder='Váš e-mail' required style='width:100%; box-sizing:border-box; background: rgba(0,0,0,0.2); color:white; border: 1px solid var(--glass-border); border-radius:8px; padding:10px;'>";
                                    if (empty($recaptchaSiteKey)) {
                                        $nHtml .= "<div class='math-captcha-container' style='display:flex; align-items:center; gap:10px; font-size: 0.9rem;'><span>Ochrana: <span class='math1'></span>+<span class='math2'></span>=</span><input type='number' name='nwMath' required style='width:60px; box-sizing:border-box; background: rgba(0,0,0,0.2); color:white; border: 1px solid var(--glass-border); border-radius:8px; padding:5px;'></div>";
                                    } else {
                                        $nHtml .= "<small style='color:var(--text-muted); font-size:0.8rem;'>Chráněno reCAPTCHA</small>";
                                    }
                                    echo $nHtml . "<button type='submit'>Přihlásit k odběru</button><div class='nwSuccess' style='display:none; color:var(--accent); font-weight:bold; font-size:0.9rem; text-align:center;'>Potvrzení odesláno!</div></form>";
                                }
                                elseif ($b['system_type'] === 'queue') {
                                    $qHtml = "<ul class='ajax-box-queue' style='list-style:none; padding:0; margin:0;'>";
                                    if (empty($upcomingQueue)) { $qHtml .= "<li style='color:var(--text-muted);'>Playlist není k dispozici</li>"; }
                                    else { foreach (array_slice($upcomingQueue, 0, 5) as $qs) { $txt = is_array($qs) ? (($qs['artist']??'').' - '.($qs['title']??'')) : $qs; $qHtml .= "<li style='padding:5px 0; border-bottom:1px solid rgba(255,255,255,0.1);'>".htmlspecialchars(capitalizeSong($txt))."</li>"; } }
                                    $qHtml .= "</ul>"; echo $qHtml;
                                }
                            elseif ($b['system_type'] === 'clock') {
                                $cType = empty($b['content']) ? 'digital' : $b['content'];
                                echo "<div class='ajax-box-clock' data-type='".htmlspecialchars($cType)."'></div>";
                            }
                            elseif ($b['system_type'] === 'weather') {
                                $city = empty($b['content']) ? 'Praha' : htmlspecialchars($b['content']);
                                echo "<div class='ajax-box-weather' data-city='{$city}' style='text-align:center; padding:10px 0;'><div style='color:var(--text-muted); font-size:0.9rem;'>Načítám počasí pro {$city}...</div></div>";
                            }
                            } 
                            else { echo $b['content']; } 
                        ?>
                    </div>
                <?php endforeach; ?>
            </div>
            
            <!-- HLAVNÍ OBSAH (Tématické stránky / Články / Hitparáda) -->
            <div class="fw-content glass">
                <?php if ($mainSection === 'home' || $mainSection === ''): ?>
                    <?php 
                    $searchQuery = $_GET['q'] ?? '';
                    if (!empty($searchQuery)):
                        $results = [];
                        foreach ($pages as $p) {
                            if (is_array($p)) {
                                $pTitle = $p['translations'][$currentLang]['title'] ?? $p['title'] ?? '';
                                $pContent = $p['translations'][$currentLang]['content'] ?? $p['content'] ?? '';
                                if (stripos($pTitle, $searchQuery) !== false || stripos(strip_tags($pContent), $searchQuery) !== false) {
                                    $results[] = ['url' => "/clanek/{$p['slug']}", 'title' => "📄 " . $pTitle];
                                }
                            }
                        }
                        foreach ($modsDb->getAll() as $m) {
                            if (is_array($m) && !empty($m['active'])) {
                                if (stripos($m['name'] ?? '', $searchQuery) !== false || stripos(strip_tags($m['long_desc'] ?? ''), $searchQuery) !== false) {
                                    $results[] = ['url' => "/moderator/{$m['id']}", 'title' => "🎙️ " . $m['name']];
                                }
                            }
                        }
                        $foundSongs = [];
                        foreach ($filteredSongs as $s) {
                            if (is_array($s)) {
                                $songName = capitalizeSong(($s['artist']??'') . ' - ' . ($s['title']??''));
                                if (stripos($songName, $searchQuery) !== false && !isset($foundSongs[$songName])) {
                                    $foundSongs[$songName] = true;
                                    $results[] = ['url' => "/historie", 'title' => "🎵 " . $songName];
                                }
                            }
                        }
                    ?>
                        <h1>Výsledky vyhledávání pro "<?php echo htmlspecialchars($searchQuery); ?>"</h1>
                        <?php if (empty($results)): ?>
                            <p>Nebyly nalezeny žádné výsledky.</p>
                        <?php else: ?>
                            <ul style="list-style: none; padding: 0; font-size: 1.2rem; line-height: 1.8;">
                                <?php foreach ($results as $r) { echo "<li style='margin-bottom:10px;'><a href='{$r['url']}' style='color:var(--accent); text-decoration:none; font-weight:bold;'>".htmlspecialchars($r['title'])."</a></li>"; } ?>
                            </ul>
                        <?php endif; ?>
                    <?php else: ?>

                    <?php if ($homePage): 
                        $hpTitle = $homePage['translations'][$currentLang]['title'] ?? $homePage['title'];
                        $hpContent = $homePage['translations'][$currentLang]['content'] ?? $homePage['content'];
                    ?>
                        <h1 style="color:var(--accent);"><?php echo htmlspecialchars($hpTitle); ?></h1>
                        <?php if (!empty($homePage['image'])): ?>
                            <img src="/<?php echo htmlspecialchars($homePage['image']); ?>" style="max-width:100%; border-radius:15px; margin-bottom:20px; box-shadow: var(--glass-shadow);">
                        <?php endif; ?>
                        <div><?php echo $hpContent; ?></div>
                    <?php else: ?>
                    <h1>Vítejte na našem rádiu!</h1>
                    <p>Nejnovější články:</p>
                    <ul style="list-style: none; padding: 0;">
                        <?php foreach (array_slice(array_reverse($pages), 0, 5) as $p) {
                            if (!is_array($p)) continue;
                            $pTitle = $p['translations'][$currentLang]['title'] ?? $p['title'];
                            $img = !empty($p['image']) ? "<img src='/{$p['image']}' style='width:50px; height:50px; object-fit:cover; border-radius:5px; vertical-align:middle; margin-right:10px;'>" : "";
                            echo "<li style='margin-bottom:10px; display:flex; align-items:center;'>{$img}<a href='/clanek/{$p['slug']}' style='color:var(--accent); text-decoration:none; font-size:1.1rem;'>".htmlspecialchars($pTitle)."</a></li>"; 
                        } ?>
                    </ul>
                    <?php endif; ?>
                    <?php endif; ?>
                
                <?php elseif ($mainSection === 'clanek'): 
                    $slug = $routeParts[1] ?? '';
                    $page = null;
                    foreach ($pages as $p) { 
                        if (is_array($p) && isset($p['slug']) && $p['slug'] === $slug) { $page = $p; break; } 
                        if (is_array($p) && isset($p['translations']) && is_array($p['translations'])) {
                            foreach ($p['translations'] as $t) {
                                if (isset($t['slug']) && $t['slug'] === $slug) {
                                    $page = $p; break 2;
                                }
                            }
                        }
                    }
                    if ($page && is_array($page)): 
                        $pTitle = $page['translations'][$currentLang]['title'] ?? $page['title'];
                        $pContent = $page['translations'][$currentLang]['content'] ?? $page['content'];
                    ?>
                        <h1 style="color:var(--accent);"><?php echo htmlspecialchars($pTitle); ?></h1>
                        <?php if (!empty($page['image'])): ?>
                            <img src="/<?php echo $page['image']; ?>" style="max-width:100%; border-radius:15px; margin-bottom:20px; box-shadow: var(--glass-shadow);">
                        <?php endif; ?>
                        <div><?php echo $pContent; ?></div>
                        <?php 
                        if (!empty($page['form_id'])) {
                            $formsDb = new JsonDB('forms');
                            $attachedForm = null; foreach ($formsDb->getAll() as $f) { if ($f['id'] === $page['form_id']) { $attachedForm = $f; break; } }
                            if ($attachedForm) {
                                ?>
                                <h3 style="color:var(--accent); margin-top: 40px; border-top: 1px solid var(--glass-border); padding-top: 20px;"><?php echo htmlspecialchars($attachedForm['name']); ?></h3>
                                <form class='form-widget-custom' data-action='custom_form' data-notify='<?php echo htmlspecialchars($attachedForm['notify']??''); ?>' data-name='<?php echo htmlspecialchars($attachedForm['name']); ?>' style='display:flex; flex-direction:column; gap:15px; margin-top:20px;'>
                                    <?php foreach ($attachedForm['fields'] as $idx => $fld): ?>
                                        <div>
                                            <label style="display:block; margin-bottom:5px; font-weight:bold;"><?php echo htmlspecialchars($fld['label']); ?><?php if(!empty($fld['required'])) echo ' <span style="color:#ff4b2b;">*</span>'; ?></label>
                                            <?php if ($fld['type'] === 'text'): ?> <input type="text" name="fld_<?php echo $idx; ?>" <?php if(!empty($fld['required'])) echo 'required'; ?> style="width:100%; padding:10px; border-radius:8px; border:1px solid var(--glass-border); background:rgba(0,0,0,0.2); color:#fff; box-sizing:border-box;">
                                            <?php elseif ($fld['type'] === 'email'): ?> <input type="email" name="fld_<?php echo $idx; ?>" <?php if(!empty($fld['required'])) echo 'required'; ?> style="width:100%; padding:10px; border-radius:8px; border:1px solid var(--glass-border); background:rgba(0,0,0,0.2); color:#fff; box-sizing:border-box;">
                                            <?php elseif ($fld['type'] === 'phone'): ?> <div style="display:flex; gap:10px;"><select name="fld_<?php echo $idx; ?>_code" style="padding:10px; border-radius:8px; border:1px solid var(--glass-border); background:rgba(0,0,0,0.2); color:#fff;"><option value="+420">🇨🇿 +420</option><option value="+421">🇸🇰 +421</option></select><input type="tel" name="fld_<?php echo $idx; ?>" <?php if(!empty($fld['required'])) echo 'required'; ?> style="flex:1; padding:10px; border-radius:8px; border:1px solid var(--glass-border); background:rgba(0,0,0,0.2); color:#fff; box-sizing:border-box;"></div>
                                            <?php elseif ($fld['type'] === 'textarea' || $fld['type'] === 'wysiwyg'): ?> <textarea name="fld_<?php echo $idx; ?>" rows="5" <?php if(!empty($fld['required'])) echo 'required'; ?> style="width:100%; padding:10px; border-radius:8px; border:1px solid var(--glass-border); background:rgba(0,0,0,0.2); color:#fff; box-sizing:border-box;"></textarea>
                                            <?php endif; ?>
                                        </div>
                                    <?php endforeach; ?>
                                    <?php if (empty($recaptchaSiteKey)): ?> <div class='math-captcha-container' style='display:flex; align-items:center; gap:10px; font-size: 1rem;'><span>Ochrana proti spamu: <span class='math1'></span> + <span class='math2'></span> =</span><input type='number' name='cwMath' required style='width:80px; box-sizing:border-box; background: rgba(0,0,0,0.2); color:white; border: 1px solid var(--glass-border); border-radius:8px; padding:10px;'></div> <?php else: ?> <small style='color:var(--text-muted); font-size:0.9rem;'>Chráněno Google reCAPTCHA</small> <?php endif; ?>
                                    <button type='submit' style='padding: 15px; font-size: 1.1rem; margin-top:10px;'>Odeslat formulář</button>
                                    <div class='cwSuccess' style='display:none; color:#38ef7d; font-weight:bold; font-size:1.1rem; text-align:center; padding: 10px; background: rgba(0,255,0,0.1); border-radius: 8px;'>Odesláno! Děkujeme.</div>
                                </form>
                                <?php
                            }
                        }
                        ?>
                    <?php else: echo "<h1>Článek nenalezen.</h1>"; endif; ?>
                
                <?php elseif ($mainSection === 'podcasty'): ?>
                    <h1>Podcasty a Záznamy pořadů</h1>
                    <div style="display: flex; flex-direction: column; gap: 20px;">
                        <?php if (empty($podcasts)): ?>
                            <p>Zatím nebyly přidány žádné záznamy.</p>
                        <?php else: ?>
                            <?php foreach ($podcasts as $pod): if (!is_array($pod)) continue; ?>
                                <div class="glass" style="padding: 20px; display: flex; gap: 20px; flex-wrap: wrap; align-items: flex-start;">
                                    <?php if (!empty($pod['image'])): ?>
                                        <img src="/<?php echo htmlspecialchars($pod['image']); ?>" style="width: 150px; height: 150px; object-fit: cover; border-radius: 10px; box-shadow: var(--glass-shadow);">
                                    <?php endif; ?>
                                    <div style="flex: 1; min-width: 250px;">
                                        <h3 style="margin-top: 0; color: var(--accent);"><?php echo htmlspecialchars($pod['title']); ?></h3>
                                        <div style="margin-bottom: 15px; font-size: 0.9rem; color: var(--text-muted);">Přidáno: <?php echo date('d. m. Y', strtotime($pod['created_at'])); ?></div>
                                        <?php $audioUrl = strpos($pod['audio_url'], 'http') === 0 ? $pod['audio_url'] : '/' . ltrim($pod['audio_url'], '/'); ?>
                                        <audio controls src="<?php echo htmlspecialchars($audioUrl); ?>" style="width: 100%; height: 40px; margin-bottom: 15px; outline: none; border-radius: 20px;"></audio>
                                        <div style="line-height: 1.6;"><?php echo $pod['description'] ?? ''; ?></div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                
                <?php elseif ($mainSection === 'moderatori'): ?>
                    <h1>Naši Moderátoři</h1>
                    <div style="display:flex; flex-wrap:wrap; gap:20px;">
                        <?php foreach ($modsDb->getAll() as $m): if (!is_array($m) || empty($m['active'])) continue; ?>
                            <div class="mod-card glass" style="flex: 1 1 200px;">
                                <?php if (!empty($m['photo'])): ?>
                                    <img src="/<?php echo htmlspecialchars($m['photo']); ?>" style="width:120px; height:120px; border-radius:50%; object-fit:cover; margin-bottom:15px; border:2px solid var(--accent); box-shadow: var(--glass-shadow);">
                                <?php else: ?>
                                    <div style="font-size:4rem; margin-bottom:15px; text-shadow: 0 2px 5px rgba(0,0,0,0.5);"><?php echo !empty($m['is_autopilot']) ? '🤖' : '🎙️'; ?></div>
                                <?php endif; ?>
                                <h3><?php echo htmlspecialchars($m['name']); ?></h3>
                                <a href="/moderator/<?php echo $m['id']; ?>" style="color:#fff;">Profil moderátora</a>
                            </div>
                        <?php endforeach; ?>
                    </div>
                    
                <?php elseif ($mainSection === 'moderator'): 
                    $modId = $routeParts[1] ?? '';
                    $mod = $modsDb->getById($modId);
                    if ($mod && is_array($mod)): ?>
                        <div style="display:flex; gap:20px; align-items:flex-start; flex-wrap:wrap;">
                            <?php if (!empty($mod['photo'])): ?>
                                <img src="/<?php echo htmlspecialchars($mod['photo']); ?>" style="width:200px; height:200px; border-radius:15px; object-fit:cover; box-shadow: var(--glass-shadow);">
                            <?php endif; ?>
                            <div style="flex:1; min-width:300px;">
                                <h1 style="margin-top:0; color:var(--accent);">Moderátor: <?php echo htmlspecialchars($mod['name']); ?></h1>
                                <?php if (!empty($mod['short_desc'])): ?>
                                    <div style="font-size:1.2rem; font-weight:bold; color:#ddd; margin-bottom: 20px;"><?php echo $mod['short_desc']; ?></div>
                                <?php endif; ?>
                                <div style="margin-top:20px; line-height:1.6;"><?php echo !empty($mod['long_desc']) ? $mod['long_desc'] : '<i>Žádný podrobný popis nebyl zadán.</i>'; ?></div>
                            </div>
                        </div>
                    <?php else: echo "<h1>Moderátor nenalezen.</h1>"; endif; ?>
                    
                <?php elseif ($mainSection === 'hitparada'): ?>
                    <h1>📻 Hitparáda nejhranějších songů</h1>
                    <ol id="ajax-hitparada" style="font-size: 1.2rem; line-height: 2; margin-bottom: 10px;"></ol>
                    <div id="hitparada-pagination" style="margin-top: 15px; display: flex; flex-wrap: wrap; justify-content: center; gap: 5px;"></div>
                    <?php
                        $counts = [];
                        foreach ($filteredSongs as $s) { $key = capitalizeSong($s['artist']) . ' - ' . capitalizeSong($s['title']); if (!isset($counts[$key])) { $counts[$key] = ['plays' => 0, 'artwork' => $s['artwork'] ?? '']; } $counts[$key]['plays']++; }
                        uasort($counts, function($a, $b) { return $b['plays'] <=> $a['plays']; });
                        $hitparadaArray = []; foreach (array_slice($counts, 0, 200) as $songName => $data) { $hitparadaArray[] = ['song' => $songName, 'plays' => $data['plays'], 'artwork' => $data['artwork']]; }
                    ?>
                    <script>
                        window.allHitparadaData = <?php echo json_encode($hitparadaArray, JSON_UNESCAPED_UNICODE); ?>;
                        window.currentHitparadaPage = 1;
                        window.hitparadaPerPage = 15;
                        window.renderHitparadaPage = function(page) {
                            const totalPages = Math.ceil(window.allHitparadaData.length / window.hitparadaPerPage) || 1;
                            if (page > totalPages) page = totalPages; window.currentHitparadaPage = page;
                            const start = (page - 1) * window.hitparadaPerPage; const end = start + window.hitparadaPerPage; const paginated = window.allHitparadaData.slice(start, end);
                            const el = document.getElementById('ajax-hitparada');
                            if (el) { el.innerHTML = paginated.map((s, idx) => {
                                const artworkHtml = s.artwork ? `<img src="${s.artwork}" style="width:40px; height:40px; border-radius:4px; object-fit:cover;">` : `<div style="width:40px; height:40px; background:rgba(0,0,0,0.2); border-radius:4px; display:flex; align-items:center; justify-content:center; font-size:1.5rem;">🎵</div>`;
                                return `<li value="${start + idx + 1}" style="display:flex; align-items:center; gap:15px; margin-bottom:10px;">${artworkHtml}<span><strong>${s.song}</strong> <span style='font-size:0.9rem; color:var(--text-muted);'>(${s.plays}x)</span></span></li>`;
                            }).join(''); }
                            const pagEl = document.getElementById('hitparada-pagination');
                            if (pagEl) {
                                let html = ''; let sPage = Math.max(1, page - 4); let ePage = Math.min(totalPages, page + 4);
                                if (sPage > 1) { html += `<button onclick="window.renderHitparadaPage(1)" style="padding: 5px 10px; border: 1px solid var(--glass-border); border-radius: 5px; background: rgba(0,0,0,0.2); color: #fff; cursor: pointer;">1</button>`; if (sPage > 2) html += `<span style="color:#fff; align-self:center;">...</span>`; }
                                for (let i = sPage; i <= ePage; i++) { html += `<button onclick="window.renderHitparadaPage(${i})" style="padding: 5px 10px; border: 1px solid var(--glass-border); border-radius: 5px; background: ${i === page ? 'var(--accent)' : 'rgba(0,0,0,0.2)'}; color: ${i === page ? '#000' : '#fff'}; cursor: pointer;">${i}</button>`; }
                                if (ePage < totalPages) { if (ePage < totalPages - 1) html += `<span style="color:#fff; align-self:center;">...</span>`; html += `<button onclick="window.renderHitparadaPage(${totalPages})" style="padding: 5px 10px; border: 1px solid var(--glass-border); border-radius: 5px; background: rgba(0,0,0,0.2); color: #fff; cursor: pointer;">${totalPages}</button>`; }
                                pagEl.innerHTML = html;
                            }
                        }
                        if (document.getElementById('ajax-hitparada')) window.renderHitparadaPage(1);
                    </script>
                    
                <?php elseif ($mainSection === 'historie'): ?>
                    <h1>🎵 Historie odehraných songů</h1>
                    <div class="glass" style="padding: 20px;">
                        <table style="width: 100%; text-align: left; border-collapse: collapse;">
                            <thead>
                                <tr><th style="border-bottom: 1px solid var(--glass-border); padding-bottom: 10px; width: 100px;">Čas</th><th style="border-bottom: 1px solid var(--glass-border); padding-bottom: 10px; width: 60px;"></th><th style="border-bottom: 1px solid var(--glass-border); padding-bottom: 10px;">Interpret a Název</th></tr>
                            </thead>
                            <tbody id="ajax-history">
                            </tbody>
                        </table>
                        <div id="history-pagination" style="margin-top: 15px; text-align: center; display: flex; justify-content: center; gap: 5px; flex-wrap: wrap;"></div>
                        <script>
                            window.allHistoryData = <?php echo json_encode(array_values($filteredSongs), JSON_UNESCAPED_UNICODE); ?>;
                            window.currentHistoryPage = 1;
                            window.historyPerPage = 20;
                            window.renderHistoryPage = function(page) {
                                const totalPages = Math.ceil(window.allHistoryData.length / window.historyPerPage) || 1;
                                if (page > totalPages) page = totalPages; window.currentHistoryPage = page;
                                const start = (page - 1) * window.historyPerPage; const end = start + window.historyPerPage; const paginated = window.allHistoryData.slice(start, end);
                                const tbody = document.getElementById('ajax-history');
                                if (tbody) {
                                    tbody.innerHTML = paginated.map(s => {
                                        const d = new Date(s.played_at.replace(' ', 'T'));
                                        const timeStr = d.getHours().toString().padStart(2,'0') + ':' + d.getMinutes().toString().padStart(2,'0');
                                        const artwork = s.artwork ? `<img src="${s.artwork}" style="width:40px; height:40px; border-radius:4px; object-fit:cover;">` : `<div style="width:40px; height:40px; background:rgba(0,0,0,0.2); border-radius:4px; display:flex; align-items:center; justify-content:center; font-size:1.5rem;">🎵</div>`;
                                        return `<tr><td style='padding: 10px 0; border-bottom: 1px solid rgba(255,255,255,0.1);'><span style='color: var(--accent); font-weight: bold; font-size: 1.1rem; background: rgba(0,0,0,0.2); padding: 4px 8px; border-radius: 6px;'>${timeStr}</span></td><td style='padding: 10px; border-bottom: 1px solid rgba(255,255,255,0.1);'>${artwork}</td><td style='padding: 10px 0; border-bottom: 1px solid rgba(255,255,255,0.1); font-weight:bold; font-size: 1.1rem;'>${capitalizeSongJs(s.artist)} - ${capitalizeSongJs(s.title)}</td></tr>`;
                                    }).join('');
                                }
                                const pagEl = document.getElementById('history-pagination');
                                if (pagEl) {
                                    let html = '';
                                    let sPage = Math.max(1, page - 4); let ePage = Math.min(totalPages, page + 4);
                                    if (sPage > 1) { html += `<button onclick="window.renderHistoryPage(1)" style="padding: 5px 10px; border: 1px solid var(--glass-border); border-radius: 5px; background: rgba(0,0,0,0.2); color: #fff; cursor: pointer;">1</button>`; if (sPage > 2) html += `<span style="color:#fff; align-self:center;">...</span>`; }
                                    for (let i = sPage; i <= ePage; i++) { html += `<button onclick="window.renderHistoryPage(${i})" style="padding: 5px 10px; border: 1px solid var(--glass-border); border-radius: 5px; background: ${i === page ? 'var(--accent)' : 'rgba(0,0,0,0.2)'}; color: ${i === page ? '#000' : '#fff'}; cursor: pointer;">${i}</button>`; }
                                    if (ePage < totalPages) { if (ePage < totalPages - 1) html += `<span style="color:#fff; align-self:center;">...</span>`; html += `<button onclick="window.renderHistoryPage(${totalPages})" style="padding: 5px 10px; border: 1px solid var(--glass-border); border-radius: 5px; background: rgba(0,0,0,0.2); color: #fff; cursor: pointer;">${totalPages}</button>`; }
                                    pagEl.innerHTML = html;
                                }
                            }
                            if (document.getElementById('ajax-history')) window.renderHistoryPage(1);
                        </script>
                    </div>
                    
                <?php elseif ($mainSection === 'porady'): ?>
                    <h1>Program vysílání</h1>
                    <div class="glass" style="padding: 20px;">
                        <?php
                            $allShiftsList = array_values($shiftsDb->getAll());
                            usort($allShiftsList, function($a, $b) {
                                $aTime = is_array($a) && isset($a['date'], $a['hour']) ? strtotime($a['date'] . ' ' . $a['hour'] . ':00:00') : 0;
                                $bTime = is_array($b) && isset($b['date'], $b['hour']) ? strtotime($b['date'] . ' ' . $b['hour'] . ':00:00') : 0;
                                return $aTime <=> $bTime;
                            });
                            $todayStr = date('Y-m-d');
                            $upcomingShifts = array_filter($allShiftsList, function($s) use ($todayStr) { return is_array($s) && isset($s['date']) && $s['date'] >= $todayStr; });
                            
                            $groupedShifts = [];
                            foreach ($upcomingShifts as $s) { if (is_array($s) && isset($s['date'])) $groupedShifts[$s['date']][] = $s; }
                            
                            if (empty($groupedShifts)) {
                                echo "<p>Aktuálně není naplánován žádný program.</p>";
                            } else {
                                foreach ($groupedShifts as $date => $shiftsOfDay) {
                                    $isToday = ($date === $todayStr);
                                    $dateLabel = date('d. m. Y', strtotime($date));
                                    if ($isToday) $dateLabel = "Dnes ($dateLabel)";
                                    elseif ($date === date('Y-m-d', strtotime('+1 day'))) $dateLabel = "Zítra ($dateLabel)";
                                    
                                    echo "<h3 style='margin-top:20px; border-bottom: 1px solid var(--glass-border); padding-bottom:10px; color:var(--accent);'>$dateLabel</h3>";
                                    echo "<table>";
                                    foreach ($shiftsOfDay as $shift) {
                                        if (!is_array($shift)) continue;
                                        $hourFrom = str_pad($shift['hour'], 2, '0', STR_PAD_LEFT) . ':00';
                                        $hourTo = str_pad($shift['hour'] + 1, 2, '0', STR_PAD_LEFT) . ':00';
                                        $modNames = [];
                                        if (isset($shift['moderator_ids']) && is_array($shift['moderator_ids'])) {
                                            foreach ($shift['moderator_ids'] as $mId) { $m = $modsDb->getById($mId); if ($m && is_array($m)) $modNames[] = "<a href='/moderator/{$m['id']}' style='color:inherit; text-decoration:none;'>".htmlspecialchars($m['name'])."</a>"; }
                                        }
                                        if (empty($modNames)) {
                                            $autopilot = null; foreach ($modsDb->getAll() as $m) { if (!empty($m['is_autopilot'])) { $autopilot = $m; break; } }
                                            $modStr = $autopilot ? "<a href='/moderator/{$autopilot['id']}' style='color:inherit; text-decoration:none;'>".htmlspecialchars($autopilot['name'])."</a>" : "🤖 DJ Autopilot";
                                        } else {
                                            $modStr = implode(', ', $modNames);
                                        }
                                        $isCurrentHour = ($isToday && (int)$shift['hour'] === (int)date('H'));
                                        $rowStyle = $isCurrentHour ? "color: var(--accent); font-weight: bold; background: rgba(0, 210, 255, 0.1);" : "";
                                        echo "<tr style='$rowStyle'><td style='width: 120px;'>$hourFrom - $hourTo</td><td>$modStr</td></tr>";
                                    }
                                    echo "</table>";
                                }
                            }
                        ?>
                    </div>
                    
                <?php elseif ($mainSection === 'prani'): ?>
                    <h1 style="color:var(--accent);">🎵 Písnička na přání</h1>
                    <div class="glass" style="padding: 30px;">
                        <p>Chcete zahrát oblíbenou písničku nebo někomu poslat vzkaz? Napište nám rovnou do studia!</p>
                        <form class='form-widget-custom' data-action='request' style='display:flex; flex-direction:column; gap:15px;'>
                            <input type="text" name="reqName" placeholder="Vaše jméno" required style="width:100%; box-sizing:border-box; background: rgba(0,0,0,0.2); color:white; border: 1px solid var(--glass-border); border-radius:8px; padding:15px;">
                            <input type="email" name="reqEmail" placeholder="Váš e-mail (pro odpověď)" required style="width:100%; box-sizing:border-box; background: rgba(0,0,0,0.2); color:white; border: 1px solid var(--glass-border); border-radius:8px; padding:15px;">
                            <input type="text" name="reqSong" placeholder="Interpret a název" required style="width:100%; box-sizing:border-box; background: rgba(0,0,0,0.2); color:white; border: 1px solid var(--glass-border); border-radius:8px; padding:15px;">
                            <textarea name="reqMessage" rows="4" placeholder="Váš vzkaz moderátorovi..." style="width:100%; box-sizing:border-box; background: rgba(0,0,0,0.2); color:white; border: 1px solid var(--glass-border); border-radius:8px; padding:15px;"></textarea>
                            <?php if (empty($recaptchaSiteKey)): ?>
                                <div class='math-captcha-container' style='display:flex; align-items:center; gap:10px; font-size: 1rem;'><span>Ochrana: <span class='math1'></span> + <span class='math2'></span> =</span><input type='number' name='cwMath' required style='width:80px; box-sizing:border-box; background: rgba(0,0,0,0.2); color:white; border: 1px solid var(--glass-border); border-radius:8px; padding:10px;'></div>
                            <?php else: ?>
                                <small style='color:var(--text-muted); font-size:0.9rem;'>Chráněno Google reCAPTCHA</small>
                            <?php endif; ?>
                            <button type='submit' style='padding: 15px; font-size: 1.1rem;'>Odeslat přání</button>
                            <div class='cwSuccess' style='display:none; color:#38ef7d; font-weight:bold; font-size:1.1rem; text-align:center; padding: 10px; background: rgba(0,255,0,0.1); border-radius: 8px;'>Odesláno! Děkujeme.</div>
                        </form>
                    </div>
                    
                <?php elseif ($mainSection === 'newsletter-overeni' || $mainSection === 'newsletter-odhlaseni-potvrzeni'): ?>
                    <h1 style="color:var(--accent);">Newsletter</h1>
                    <div class="glass" style="padding: 30px; text-align:center;">
                        <h3 id="nlVerifyMsg">Probíhá ověřování vašeho požadavku...</h3>
                    </div>
                    <script>
                        (async function() {
                            const params = new URLSearchParams(window.location.search); const token = params.get('token'); const act = '<?php echo $mainSection === 'newsletter-overeni' ? (isset($_GET['action']) && $_GET['action']==='unsubscribe' ? 'unsubscribe' : 'subscribe') : 'unsubscribe'; ?>';
                            try { const res = await fetch('/admin/api/newsletter-verify', { method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify({token: token, action: act}) }); const json = await res.json(); document.getElementById('nlVerifyMsg').innerHTML = `<span style="color:${json.status === 'success' ? '#38ef7d' : '#ff4b2b'}">${json.message}</span>`; } 
                            catch(e) { document.getElementById('nlVerifyMsg').innerText = 'Chyba sítě. Zkuste to prosím znovu.'; }
                        })();
                    </script>
                    
                <?php elseif ($mainSection === 'formular'): 
                    $formId = $routeParts[1] ?? ''; $formsDb = new JsonDB('forms'); $form = null; foreach ($formsDb->getAll() as $f) { if (($f['slug']??'') === $formId) { $form = $f; break; } }
                    if ($form): ?>
                    <h1 style="color:var(--accent);"><?php echo htmlspecialchars($form['name']); ?></h1>
                    <div class="glass" style="padding: 30px;">
                        <form class='form-widget-custom' data-action='custom_form' data-notify='<?php echo htmlspecialchars($form['notify']??''); ?>' data-name='<?php echo htmlspecialchars($form['name']); ?>' style='display:flex; flex-direction:column; gap:15px;'>
                            <?php foreach ($form['fields'] as $idx => $fld): ?>
                                <div>
                                    <label style="display:block; margin-bottom:5px; font-weight:bold;"><?php echo htmlspecialchars($fld['label']); ?><?php if(!empty($fld['required'])) echo ' <span style="color:#ff4b2b;">*</span>'; ?></label>
                                    <?php if ($fld['type'] === 'text'): ?> <input type="text" name="fld_<?php echo $idx; ?>" <?php if(!empty($fld['required'])) echo 'required'; ?> style="width:100%; padding:10px; border-radius:8px; border:1px solid var(--glass-border); background:rgba(0,0,0,0.2); color:#fff; box-sizing:border-box;">
                                    <?php elseif ($fld['type'] === 'email'): ?> <input type="email" name="fld_<?php echo $idx; ?>" <?php if(!empty($fld['required'])) echo 'required'; ?> style="width:100%; padding:10px; border-radius:8px; border:1px solid var(--glass-border); background:rgba(0,0,0,0.2); color:#fff; box-sizing:border-box;">
                                    <?php elseif ($fld['type'] === 'phone'): ?> <div style="display:flex; gap:10px;"><select name="fld_<?php echo $idx; ?>_code" style="padding:10px; border-radius:8px; border:1px solid var(--glass-border); background:rgba(0,0,0,0.2); color:#fff;"><option value="+420">🇨🇿 +420</option><option value="+421">🇸🇰 +421</option></select><input type="tel" name="fld_<?php echo $idx; ?>" <?php if(!empty($fld['required'])) echo 'required'; ?> style="flex:1; padding:10px; border-radius:8px; border:1px solid var(--glass-border); background:rgba(0,0,0,0.2); color:#fff; box-sizing:border-box;"></div>
                                    <?php elseif ($fld['type'] === 'textarea' || $fld['type'] === 'wysiwyg'): ?> <textarea name="fld_<?php echo $idx; ?>" rows="5" <?php if(!empty($fld['required'])) echo 'required'; ?> style="width:100%; padding:10px; border-radius:8px; border:1px solid var(--glass-border); background:rgba(0,0,0,0.2); color:#fff; box-sizing:border-box;"></textarea>
                                    <?php endif; ?>
                                </div>
                            <?php endforeach; ?>
                            <?php if (empty($recaptchaSiteKey)): ?> <div class='math-captcha-container' style='display:flex; align-items:center; gap:10px; font-size: 1rem;'><span>Ochrana proti spamu: <span class='math1'></span> + <span class='math2'></span> =</span><input type='number' name='cwMath' required style='width:80px; box-sizing:border-box; background: rgba(0,0,0,0.2); color:white; border: 1px solid var(--glass-border); border-radius:8px; padding:10px;'></div> <?php else: ?> <small style='color:var(--text-muted); font-size:0.9rem;'>Chráněno Google reCAPTCHA</small> <?php endif; ?>
                            <button type='submit' style='padding: 15px; font-size: 1.1rem; margin-top:10px;'>Odeslat formulář</button>
                            <div class='cwSuccess' style='display:none; color:#38ef7d; font-weight:bold; font-size:1.1rem; text-align:center; padding: 10px; background: rgba(0,255,0,0.1); border-radius: 8px;'>Odesláno! Děkujeme.</div>
                        </form>
                    </div>
                <?php else: echo "<h1>Formulář nenalezen (404).</h1>"; endif; ?>
                    
                <?php elseif ($mainSection === 'souteze'): ?>
                    <h1 style="color:var(--accent);">🎁 Soutěže na našem rádiu</h1>
                    <p>Zapojte se do aktuálních soutěží a vyhrajte skvělé ceny!</p>
                    <div style="display: flex; flex-direction: column; gap: 20px;">
                        <?php $activeComps = array_filter($competitions, function($c) { return !empty($c['active']) || !empty($c['finished']); }); 
                        if (empty($activeComps)): ?>
                            <p>Zatím neprobíhají žádné soutěže.</p>
                        <?php else: foreach ($activeComps as $c): ?>
                            <div class="glass" style="padding: 20px; display: flex; gap: 20px; flex-wrap: wrap; align-items: flex-start; border-left: 5px solid <?php echo !empty($c['finished']) ? '#ff4b2b' : 'var(--accent)'; ?>;">
                                <?php if (!empty($c['image'])): ?><img src="/<?php echo htmlspecialchars($c['image']); ?>" style="width: 150px; height: 150px; object-fit: cover; border-radius: 10px; box-shadow: var(--glass-shadow);"><?php endif; ?>
                                <div style="flex: 1; min-width: 250px;">
                                    <h3 style="margin-top: 0; color: var(--accent);"><?php echo htmlspecialchars($c['title']); ?></h3>
                                    <div style="margin-bottom: 15px;">
                                        <?php if (!empty($c['finished'])): ?><span style="background:#ff4b2b; color:#fff; padding:5px 10px; border-radius:5px; font-weight:bold; font-size:0.9rem;">Soutěž byla ukončena</span>
                                        <?php else: ?><span style="background:lime; color:#000; padding:5px 10px; border-radius:5px; font-weight:bold; font-size:0.9rem;">Probíhá! Zapojte se nyní</span><?php endif; ?>
                                    </div>
                                    <a href="/soutez/<?php echo $c['slug']; ?>" style="display:inline-block; margin-top:10px; padding:10px 15px; background:var(--accent); color:#000; text-decoration:none; border-radius:8px; font-weight:bold;">Zobrazit detaily a pravidla</a>
                                </div>
                            </div>
                        <?php endforeach; endif; ?>
                    </div>
                    
                <?php elseif ($mainSection === 'soutez'): 
                    $slug = $routeParts[1] ?? ''; $comp = null; foreach ($competitions as $c) { if (($c['slug']??'') === $slug) { $comp = $c; break; } }
                    if ($comp): ?>
                    <h1 style="color:var(--accent);"><?php echo htmlspecialchars($comp['title']); ?></h1>
                    <div class="glass" style="padding: 30px;">
                        <?php if (!empty($comp['image'])): ?><img src="/<?php echo htmlspecialchars($comp['image']); ?>" style="max-width:100%; border-radius:15px; margin-bottom:20px; box-shadow: var(--glass-shadow);"><?php endif; ?>
                        <div style="line-height:1.6; margin-bottom:30px;"><?php echo $comp['description'] ?? ''; ?></div>
                        
                        <?php if (!empty($comp['finished'])): ?>
                            <div style="padding:20px; background:rgba(255, 75, 43, 0.2); border:1px solid #ff4b2b; border-radius:10px; text-align:center;">
                                <h3 style="color:#ff4b2b; margin-top:0;">Soutěž je již ukončena</h3>
                                <p>Do této soutěže se již nelze zapojit. Děkujeme všem zúčastněným!</p>
                            </div>
                        <?php elseif (!empty($comp['active'])): ?>
                            <h3 style="border-top: 1px solid var(--glass-border); padding-top: 20px; color:var(--accent);">Zapojte se do soutěže</h3>
                            <form class='form-widget-custom' data-action='competition_entry' data-compid='<?php echo $comp['id']; ?>' style='display:flex; flex-direction:column; gap:15px;'>
                                <input type='text' name='fld_name' placeholder='Vaše jméno a příjmení' required style='width:100%; box-sizing:border-box; background: rgba(0,0,0,0.2); color:white; border: 1px solid var(--glass-border); border-radius:8px; padding:15px; font-size:1rem;'>
                                <input type='email' name='fld_email' placeholder='Váš e-mail' required style='width:100%; box-sizing:border-box; background: rgba(0,0,0,0.2); color:white; border: 1px solid var(--glass-border); border-radius:8px; padding:15px; font-size:1rem;'>
                                <textarea name='fld_message' placeholder='Soutěžní odpověď / Zpráva...' rows='4' style='width:100%; box-sizing:border-box; background: rgba(0,0,0,0.2); color:white; border: 1px solid var(--glass-border); border-radius:8px; padding:15px; font-size:1rem;'></textarea>
                                <?php if (empty($recaptchaSiteKey)): ?> <div class='math-captcha-container' style='display:flex; align-items:center; gap:10px; font-size: 1rem;'><span>Ochrana proti spamu: <span class='math1'></span> + <span class='math2'></span> =</span><input type='number' name='cwMath' required style='width:80px; box-sizing:border-box; background: rgba(0,0,0,0.2); color:white; border: 1px solid var(--glass-border); border-radius:8px; padding:10px;'></div> <?php else: ?> <small style='color:var(--text-muted); font-size:0.9rem;'>Chráněno Google reCAPTCHA</small> <?php endif; ?>
                                <button type='submit' style='padding: 15px; font-size: 1.1rem;'>Odeslat soutěžní odpověď</button>
                            </form>
                        <?php endif; ?>
                    </div>
                <?php else: echo "<h1>Soutěž nenalezena.</h1>"; endif; ?>
                    
                <?php elseif ($mainSection === 'objednavka'): ?>
                    <h1 style="color:var(--accent);">Objednávkový formulář</h1>
                    <div class="glass" style="padding: 30px;">
                        <p style="font-size: 1.1rem; margin-bottom: 20px;">Máte zájem o reklamní kampaň, rádio spot, moderování vaší akce nebo jiné mediální služby? Neváhejte nás kontaktovat prostřednictvím formuláře níže.</p>
                        <form class='form-widget-contact' style='display:flex; flex-direction:column; gap:15px;'>
                            <input type='text' name='cwName' placeholder='Vaše jméno nebo název firmy' required style='width:100%; box-sizing:border-box; background: rgba(0,0,0,0.2); color:white; border: 1px solid var(--glass-border); border-radius:8px; padding:15px; font-size:1rem;'>
                            <input type='email' name='cwEmail' placeholder='Váš e-mail' required style='width:100%; box-sizing:border-box; background: rgba(0,0,0,0.2); color:white; border: 1px solid var(--glass-border); border-radius:8px; padding:15px; font-size:1rem;'>
                            <input type='text' name='cwPhone' placeholder='Telefonní číslo' style='width:100%; box-sizing:border-box; background: rgba(0,0,0,0.2); color:white; border: 1px solid var(--glass-border); border-radius:8px; padding:15px; font-size:1rem;'>
                            <textarea name='cwMsg' placeholder='Předmět vaší poptávky nebo specifikace objednávky...' required rows='6' style='width:100%; box-sizing:border-box; background: rgba(0,0,0,0.2); color:white; border: 1px solid var(--glass-border); border-radius:8px; padding:15px; font-size:1rem;'></textarea>
                            <?php if (empty($recaptchaSiteKey)): ?>
                                <div class='math-captcha-container' style='display:flex; align-items:center; gap:10px; font-size: 1rem;'>
                                    <span>Ochrana proti spamu: <span class='math1'></span> + <span class='math2'></span> =</span>
                                    <input type='number' name='cwMath' required style='width:80px; box-sizing:border-box; background: rgba(0,0,0,0.2); color:white; border: 1px solid var(--glass-border); border-radius:8px; padding:10px;'>
                                </div>
                            <?php else: ?>
                                <small style='color:var(--text-muted); font-size:0.9rem;'>Chráněno Google reCAPTCHA</small>
                            <?php endif; ?>
                            <button type='submit' style='padding: 15px; font-size: 1.1rem;'>Odeslat nezávaznou objednávku</button>
                            <div class='cwSuccess' style='display:none; color:var(--accent); font-weight:bold; font-size:1.1rem; text-align:center; padding: 10px; background: rgba(0,255,0,0.1); border-radius: 8px;'>Objednávka byla úspěšně odeslána! Brzy se Vám ozveme.</div>
                        </form>
                    </div>
                <?php else: ?>
                    <h1>Stránka nenalezena (404)</h1>
                <?php endif; ?>
            </div>
            
            <!-- PRAVÉ BOXY -->
            <div class="fw-col-right">
                <?php foreach ($boxes as $b): 
                    if (!is_array($b) || !isset($b['position']) || $b['position'] !== 'right' || (isset($b['active']) && $b['active'] === false)) continue; ?>
                    <div class="fw-box glass">
                        <h3 style="display: flex; justify-content: space-between; align-items: center;">
                            <span><?php echo htmlspecialchars($b['title']); ?></span>
                            <?php if (!empty($b['is_system']) && $b['system_type'] === 'onair' && (!isset($b['content']) || $b['content'] !== '0')): ?>
                                <span style="display:flex; align-items:center; gap:6px; font-family: monospace; color: inherit; background: rgba(0,0,0,0.3); padding: 4px 10px; border-radius: 8px; font-size: 0.85em; box-shadow: inset 0 0 5px rgba(0,0,0,0.5);"><span class="live-indicator" style="width:8px; height:8px; background:lime; border-radius:50%; box-shadow: 0 0 5px lime; transition: opacity 0.2s;"></span><span class="live-clock">--:--:--</span></span>
                            <?php endif; ?>
                        </h3>
                        <?php 
                            if (!empty($b['is_system'])) { 
                                if ($b['system_type'] === 'onair') { echo "<div class='ajax-box-onair'>$onAirText</div>"; } elseif ($b['system_type'] === 'nowplaying') { $artworkHtml = $nowPlayingArtwork ? "<img src='".htmlspecialchars($nowPlayingArtwork)."' style='width:60px; height:60px; border-radius:8px; object-fit:cover; box-shadow:var(--glass-shadow);'>" : "<div style='width:60px; height:60px; background:rgba(0,0,0,0.2); border-radius:8px; display:inline-flex; align-items:center; justify-content:center; font-size:2.5rem; margin:0 auto;'>🎵</div>"; echo "<div class='ajax-box-nowplaying' style='text-align:center;'><a href='/historie' style='text-decoration:none; color:inherit; font-weight:bold; transition:transform 0.2s; display:inline-block; margin-top:5px;' onmouseover=\"this.style.transform='scale(1.05)'\" onmouseout=\"this.style.transform='scale(1)'\" title='Zobrazit historii songů'>{$artworkHtml}<br>{$nowPlaying}</a></div>"; }
                                elseif ($b['system_type'] === 'contact') {
                                    $cHtml = "<form class='form-widget-contact' style='display:flex; flex-direction:column; gap:10px;'><input type='text' name='cwName' placeholder='Jméno (volitelné)' style='width:100%; box-sizing:border-box; background: rgba(0,0,0,0.2); color:white; border: 1px solid var(--glass-border); border-radius:8px; padding:10px;'><input type='email' name='cwEmail' placeholder='Váš e-mail' required style='width:100%; box-sizing:border-box; background: rgba(0,0,0,0.2); color:white; border: 1px solid var(--glass-border); border-radius:8px; padding:10px;'><textarea name='cwMsg' placeholder='Zpráva...' required rows='3' style='width:100%; box-sizing:border-box; background: rgba(0,0,0,0.2); color:white; border: 1px solid var(--glass-border); border-radius:8px; padding:10px;'></textarea>";
                                    if (empty($recaptchaSiteKey)) {
                                        $cHtml .= "<div class='math-captcha-container' style='display:flex; align-items:center; gap:10px; font-size: 0.9rem;'><span>Ochrana: <span class='math1'></span>+<span class='math2'></span>=</span><input type='number' name='cwMath' required style='width:60px; box-sizing:border-box; background: rgba(0,0,0,0.2); color:white; border: 1px solid var(--glass-border); border-radius:8px; padding:5px;'></div>";
                                    } else {
                                        $cHtml .= "<small style='color:var(--text-muted); font-size:0.8rem;'>Chráněno reCAPTCHA</small>";
                                    }
                                    echo $cHtml . "<button type='submit'>Odeslat zprávu</button><div class='cwSuccess' style='display:none; color:var(--accent); font-weight:bold; font-size:0.9rem; text-align:center;'>Zpráva odeslána!</div></form>";
                                }
                                elseif ($b['system_type'] === 'newsletter') {
                                    $nHtml = "<form class='form-widget-newsletter' style='display:flex; flex-direction:column; gap:10px;'><input type='email' name='nwEmail' placeholder='Váš e-mail' required style='width:100%; box-sizing:border-box; background: rgba(0,0,0,0.2); color:white; border: 1px solid var(--glass-border); border-radius:8px; padding:10px;'>";
                                    if (empty($recaptchaSiteKey)) {
                                        $nHtml .= "<div class='math-captcha-container' style='display:flex; align-items:center; gap:10px; font-size: 0.9rem;'><span>Ochrana: <span class='math1'></span>+<span class='math2'></span>=</span><input type='number' name='nwMath' required style='width:60px; box-sizing:border-box; background: rgba(0,0,0,0.2); color:white; border: 1px solid var(--glass-border); border-radius:8px; padding:5px;'></div>";
                                    } else {
                                        $nHtml .= "<small style='color:var(--text-muted); font-size:0.8rem;'>Chráněno reCAPTCHA</small>";
                                    }
                                    echo $nHtml . "<button type='submit'>Přihlásit k odběru</button><div class='nwSuccess' style='display:none; color:var(--accent); font-weight:bold; font-size:0.9rem; text-align:center;'>Potvrzení odesláno!</div></form>";
                                }
                                elseif ($b['system_type'] === 'queue') {
                                    $qHtml = "<ul class='ajax-box-queue' style='list-style:none; padding:0; margin:0;'>";
                                    if (empty($upcomingQueue)) { $qHtml .= "<li style='color:var(--text-muted);'>Playlist není k dispozici</li>"; }
                                    else { foreach (array_slice($upcomingQueue, 0, 5) as $qs) { $txt = is_array($qs) ? (($qs['artist']??'').' - '.($qs['title']??'')) : $qs; $qHtml .= "<li style='padding:5px 0; border-bottom:1px solid rgba(255,255,255,0.1);'>".htmlspecialchars(capitalizeSong($txt))."</li>"; } }
                                    $qHtml .= "</ul>"; echo $qHtml;
                                }
                            elseif ($b['system_type'] === 'clock') {
                                $cType = empty($b['content']) ? 'digital' : $b['content'];
                                echo "<div class='ajax-box-clock' data-type='".htmlspecialchars($cType)."'></div>";
                            }
                            elseif ($b['system_type'] === 'weather') {
                                $city = empty($b['content']) ? 'Praha' : htmlspecialchars($b['content']);
                                echo "<div class='ajax-box-weather' data-city='{$city}' style='text-align:center; padding:10px 0;'><div style='color:var(--text-muted); font-size:0.9rem;'>Načítám počasí pro {$city}...</div></div>";
                            }
                            } 
                            else { echo $b['content']; } 
                        ?>
                    </div>
                <?php endforeach; ?>
            </div>
        </div>
        
        <div class="fw-footer glass" style="padding: 20px; margin-top: 40px; text-align: center; margin-bottom: 100px;">
            <?php if (!empty($tpl['footer'])) echo "<div>{$tpl['footer']}</div>"; ?>
            <div style="margin-top: 20px; display: flex; justify-content: center; gap: 15px;">
                <a href="/rss.xml" target="_blank" style="color: var(--accent); text-decoration: none; font-size: 1.5rem; transition: transform 0.2s;" onmouseover="this.style.transform='scale(1.2)'" onmouseout="this.style.transform='scale(1)'" title="RSS Feed"><svg width="24" height="24" fill="currentColor" viewBox="0 0 24 24"><path d="M4.094 17.585a2.825 2.825 0 1 0 0 5.65 2.825 2.825 0 0 0 0-5.65zm-.05-9.176c5.82 0 10.537 4.717 10.537 10.537h3.914c0-7.98-6.471-14.451-14.451-14.451v3.914zm0-7.481c9.953 0 18.018 8.066 18.018 18.019h3.914C25.976 6.88 17.094-2 4.044-2v3.928z"/></svg></a>
            </div>
            <div style="margin-top: 20px; font-size: 0.9rem; color: var(--text-color);">
                Vyrobeno pomocí systému <a href="https://api.mysoft.cz/redir.php?from=radiowebsystem" target="_blank" style="color: inherit; text-decoration: none; font-weight: bold;">Radio Web System</a> od BroadCaster, s.r.o. &copy; <?php echo date('Y'); ?>
            </div>
        </div>

        <!-- WEBOVÝ PŘEHRÁVAČ -->
        <?php if (!empty($playerStreams)): ?>
            <div class="fw-player glass" style="position: fixed; bottom: 20px; left: 50%; transform: translateX(-50%); width: 90%; max-width: 700px; padding: 15px 25px; display: flex; align-items: center; justify-content: space-between; z-index: 1000; box-sizing: border-box;">
                <div style="display: flex; align-items: center; gap: 15px;">
                    <button id="playBtn" onclick="togglePlay()" style="border-radius: 50%; width: 50px; height: 50px; font-size: 1.5rem; display: flex; align-items: center; justify-content: center; padding: 0;">▶</button>
                    <div id="playerArtworkWrapper" style="width:40px; height:40px; position:relative;">
                        <img id="playerArtwork" <?php if($nowPlayingArtwork) echo 'src="'.htmlspecialchars($nowPlayingArtwork).'"'; ?> style="width:40px; height:40px; border-radius:4px; object-fit:cover; <?php if(!$nowPlayingArtwork) echo 'display:none;'; ?>">
                        <div id="playerArtworkPlaceholder" style="width:40px; height:40px; background:rgba(0,0,0,0.2); border-radius:4px; display:flex; align-items:center; justify-content:center; font-size:1.5rem; <?php if($nowPlayingArtwork) echo 'display:none;'; ?>">🎵</div>
                    </div>
                    <div>
                        <div style="font-size: 0.8rem; color: var(--text-muted); text-transform: uppercase;">PRÁVĚ HRAJE</div>
                        <a href="/historie" style="text-decoration:none; display:block; font-weight: bold; color: var(--accent); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 250px; transition: opacity 0.2s;" onmouseover="this.style.opacity='0.8'" onmouseout="this.style.opacity='1'" id="playerNowPlaying" title="Zobrazit historii songů"><?php echo htmlspecialchars($nowPlaying); ?></a>
                    </div>
                </div>
                <audio id="radioAudio" data-base-url="<?php echo htmlspecialchars($playerStreams[0]['url']); ?>" preload="none"></audio>
                <div style="display:flex; align-items:center; gap: 10px;">
                    <?php if (count($playerStreams) > 1): ?>
                        <select onchange="changeStream(this.value)" style="background: rgba(0,0,0,0.3); border: 1px solid var(--glass-border); color: #fff; padding: 5px 10px; border-radius: 8px; outline: none; cursor: pointer;">
                            <option value="">Vybrat kvalitu</option>
                            <?php foreach ($playerStreams as $ps): ?>
                                <option value="<?php echo htmlspecialchars($ps['url']); ?>"><?php echo htmlspecialchars($ps['name']); ?></option>
                            <?php endforeach; ?>
                        </select>
                    <?php endif; ?>
                    <span style="font-size: 1.2rem;">🔉</span>
                    <input id="volumeSlider" type="range" min="0" max="1" step="0.01" value="0.5" oninput="document.getElementById('radioAudio').volume = this.value; localStorage.setItem('rws_player_volume', this.value);" style="width: 100px; cursor: pointer;">
                </div>
            </div>
            <script>
                function togglePlay(isAutoPlay = false) {
                    const audio = document.getElementById('radioAudio');
                    const btn = document.getElementById('playBtn');
                    if (audio.paused) {
                        let stream = audio.dataset.baseUrl;
                        if (window.location.protocol === 'https:' && stream.startsWith('http://')) {
                            stream = '/stream-proxy.php?stream=' + encodeURIComponent(stream);
                        }
                        let sep = stream.includes('?') ? '&' : '?';
                        audio.src = stream + sep + 't=' + new Date().getTime();
                        let playPromise = audio.play();
                        if (playPromise !== undefined) {
                            playPromise.catch(error => {
                                console.error('Chyba přehrávání:', error);
                                if (!isAutoPlay) {
                                    if (error.name === 'NotAllowedError') {
                                        customAlert('Prohlížeč zablokoval automatické spuštění zvuku bez interakce. Prosím, klikněte na tlačítko Play pro spuštění.', 'Přehrávání zablokováno');
                                    } else {
                                        customAlert('Přehrávač byl zablokován prohlížečem.\n\nDůvodem může být Mixed Content (vložení HTTP streamu na zabezpečený HTTPS web) nebo restrikce prohlížeče.\n\nDetail: ' + error.message, 'Chyba přehrávání');
                                    }
                                }
                                btn.innerText = '▶';
                                localStorage.setItem('rws_player_was_playing', 'false');
                            });
                        }
                        btn.innerText = '⏸';
                        localStorage.setItem('rws_player_was_playing', 'true');
                    } else { 
                        audio.pause(); 
                        audio.removeAttribute('src'); // Úplné uvolnění streamového spojení a zahození dat z paměti
                        audio.load();
                        btn.innerText = '▶'; 
                        localStorage.setItem('rws_player_was_playing', 'false');
                    }
                }

                function changeStream(url) {
                    const audio = document.getElementById('radioAudio');
                    const btn = document.getElementById('playBtn');
                    const wasPlaying = !audio.paused;
                    audio.pause(); audio.removeAttribute('src'); audio.load();
                    audio.dataset.baseUrl = url;
                    localStorage.setItem('rws_player_stream_url', url);
                    if (wasPlaying) {
                        let stream = url;
                        if (window.location.protocol === 'https:' && stream.startsWith('http://')) {
                            stream = '/stream-proxy.php?stream=' + encodeURIComponent(stream);
                        }
                        let sep = stream.includes('?') ? '&' : '?';
                        audio.src = stream + sep + 't=' + new Date().getTime();
                        let playPromise = audio.play();
                        if (playPromise !== undefined) playPromise.catch(e => console.error(e));
                    } else { audio.src = url; }
                }

                // Sledování stavu přehrávače a automatická obnova
                const audio = document.getElementById('radioAudio');
                if (audio) {
                    const checkAndReconnect = () => {
                        const btn = document.getElementById('playBtn');
                        if (btn && btn.innerText === '⏸' && audio.paused) {
                            console.warn("Spojení se streamem přerušeno. Pokouším se obnovit...");
                            let stream = audio.dataset.baseUrl || "<?php echo addslashes($playerStreams[0]['url'] ?? ''); ?>";
                            if (window.location.protocol === 'https:' && stream.startsWith('http://')) {
                                stream = '/stream-proxy.php?stream=' + encodeURIComponent(stream);
                            }
                            let sep = stream.includes('?') ? '&' : '?';
                            audio.src = stream + sep + 't=' + new Date().getTime();
                            audio.play().catch(e => console.error("Obnova selhala:", e));
                        }
                    };
                    audio.addEventListener('stalled', () => setTimeout(checkAndReconnect, 4000));
                    audio.addEventListener('error', () => setTimeout(checkAndReconnect, 2000));
                    audio.addEventListener('ended', () => setTimeout(checkAndReconnect, 1000));
                    setInterval(checkAndReconnect, 5000);
                }
            </script>
            <script>
                document.addEventListener('DOMContentLoaded', () => {
                    const audio = document.getElementById('radioAudio');
                    const volumeSlider = document.getElementById('volumeSlider');
                    const streamSelector = document.querySelector('.fw-player select');

                    const savedVolume = localStorage.getItem('rws_player_volume');
                    if (savedVolume) { audio.volume = savedVolume; volumeSlider.value = savedVolume; }

                    const savedStreamUrl = localStorage.getItem('rws_player_stream_url');
                    if (savedStreamUrl && streamSelector) { audio.dataset.baseUrl = savedStreamUrl; streamSelector.value = savedStreamUrl; }

                    const wasPlaying = localStorage.getItem('rws_player_was_playing');
                    if (wasPlaying === 'true') { togglePlay(true); }
                });
            </script>
        <?php endif; ?>
    </div>
    
    <script>
        // Živé hodiny v ON-AIR boxu s indikátorem
        setInterval(() => {
            const now = new Date();
            const timeStr = now.getHours().toString().padStart(2, '0') + ':' + now.getMinutes().toString().padStart(2, '0') + ':' + now.getSeconds().toString().padStart(2, '0');
            document.querySelectorAll('.live-clock').forEach(el => el.innerText = timeStr);
            document.querySelectorAll('.live-indicator').forEach(el => el.style.opacity = now.getSeconds() % 2 === 0 ? '1' : '0.2');

            // Widget hodiny
            document.querySelectorAll('.ajax-box-clock').forEach(el => {
                const type = el.dataset.type;
                if (type === 'analog') {
                    if (!el.querySelector('.clock-analog')) {
                        let marks = '';
                        for(let i=0; i<12; i++) {
                            let isBold = i % 3 === 0;
                            marks += `<div style="position:absolute; top:4px; left:50%; width:${isBold?4:2}px; height:${isBold?12:8}px; background:${isBold?'var(--accent)':'rgba(255,255,255,0.5)'}; margin-left:-${isBold?2:1}px; transform-origin: 50% 71px; transform: rotate(${i*30}deg); border-radius:2px;"></div>`;
                        }
                        el.innerHTML = `<div class="clock-analog">${marks}<div class="clock-hand clock-hand-hour"></div><div class="clock-hand clock-hand-minute"></div><div class="clock-hand clock-hand-second"></div></div>`;
                    }
                    const hr = now.getHours(); const mn = now.getMinutes(); const sc = now.getSeconds();
                    el.querySelector('.clock-hand-hour').style.transform = `rotate(${(hr % 12) * 30 + mn * 0.5}deg)`;
                    el.querySelector('.clock-hand-minute').style.transform = `rotate(${mn * 6}deg)`;
                    el.querySelector('.clock-hand-second').style.transform = `rotate(${sc * 6}deg)`;
                } else {
                    el.innerHTML = `<div class="clock-digital">${timeStr}</div>`;
                }
            });
        }, 1000);

        // Animovaný Widget Počasí s podporou rotace více měst
        window.weatherCache = window.weatherCache || {};
        const weatherCodes = {
            0: '☀️ Jasno', 1: '🌤️ Skoro jasno', 2: '⛅ Polojasno', 3: '☁️ Zataženo',
            45: '🌫️ Mlha', 48: '🌫️ Mrznoucí mlha', 51: '🌧️ Mrholení', 53: '🌧️ Mrholení', 55: '🌧️ Silné mrholení',
            61: '🌧️ Slabý déšť', 63: '🌧️ Déšť', 65: '🌧️ Silný déšť', 71: '🌨️ Slabé sněžení', 73: '🌨️ Sněžení',
            75: '❄️ Silné sněžení', 80: '🌧️ Přeháňky', 81: '🌧️ Silné přeháňky', 82: '🌧️ Průtrž mračen',
            85: '🌨️ Sněhové přeháňky', 86: '❄️ Silné sněhové přeháňky', 95: '⛈️ Bouřka', 96: '⛈️ Silná bouřka', 99: '⛈️ Bouřka s kroupami'
        };
        async function rotateWeather() {
            document.querySelectorAll('.ajax-box-weather').forEach(async (box) => {
                const cities = box.dataset.city.split(',').map(c => c.trim()).filter(c => c);
                if (cities.length === 0) return;
                if (typeof box.dataset.cIndex === 'undefined') box.dataset.cIndex = -1;
                let nextIndex = parseInt(box.dataset.cIndex) + 1;
                if (nextIndex >= cities.length) nextIndex = 0;
                const city = cities[nextIndex];
                const now = Date.now();
                let weatherData = null; let needsFetch = false;
                if (window.weatherCache[city] && (now - window.weatherCache[city].ts < 1800000)) { weatherData = window.weatherCache[city].data; } else { needsFetch = true; }
                if (needsFetch) {
                    try {
                        const geoRes = await fetch(`https://geocoding-api.open-meteo.com/v1/search?name=${encodeURIComponent(city)}&count=1&language=cs&format=json`);
                        const geoJson = await geoRes.json();
                        if (geoJson.results && geoJson.results.length > 0) {
                            const loc = geoJson.results[0];
                            const weatherRes = await fetch(`https://api.open-meteo.com/v1/forecast?latitude=${loc.latitude}&longitude=${loc.longitude}&current=temperature_2m,weather_code,wind_speed_10m&timezone=auto`);
                            const weatherJson = await weatherRes.json();
                            weatherData = { loc, current: weatherJson.current }; window.weatherCache[city] = { ts: now, data: weatherData };
                        } else { window.weatherCache[city] = { ts: now, data: null }; }
                    } catch (e) { console.error(e); }
                } else if (cities.length === 1 && box.dataset.cIndex !== '-1') return; // Neanimuj a nestahuj zbytečně, pokud je to jediné město
                box.dataset.cIndex = nextIndex;
                const doAnimate = cities.length > 1 && box.innerHTML !== '' && !box.innerHTML.includes('Načítám počasí');
                if (doAnimate) { box.style.transition = 'opacity 0.5s'; box.style.opacity = 0; }
                setTimeout(() => {
                    if (weatherData) {
                        const { loc, current } = weatherData; const desc = weatherCodes[current.weather_code] || 'Měnlivo';
                        const emoji = desc.split(' ')[0]; const textDesc = desc.substring(desc.indexOf(' ')+1);
                        box.innerHTML = `<div style="font-size: 3.5rem; line-height: 1; margin-bottom: 10px; text-shadow: 0 0 15px rgba(255,255,255,0.2);">${emoji}</div><div style="font-size: 2.2rem; font-weight: bold; color: var(--accent); text-shadow: 0 2px 5px rgba(0,0,0,0.5);">${Math.round(current.temperature_2m)} °C</div><div style="font-size: 1.2rem; font-weight: bold; margin-top: 5px;">${loc.name}</div><div style="font-size: 0.95rem; color: var(--text-muted); margin-top: 5px;">${textDesc} • Vítr: ${Math.round(current.wind_speed_10m)} km/h</div>`;
                    } else { box.innerHTML = `<div style="color:#ff4b2b; font-size:0.9rem; padding: 20px;">Počasí pro ${city} nenalezeno.</div>`; }
                    if (doAnimate) box.style.opacity = 1;
                }, doAnimate ? 500 : 0);
            });
        }
        rotateWeather(); setInterval(rotateWeather, 8000);

        function initContactCaptchas() {
            document.querySelectorAll('.form-widget-contact, .form-widget-newsletter, .form-widget-custom').forEach(form => {
                if (!form.dataset.captchaInit && !'<?php echo $recaptchaSiteKey; ?>') {
                    const n1 = Math.floor(Math.random() * 10) + 1; const n2 = Math.floor(Math.random() * 10) + 1; form.dataset.n1 = n1; form.dataset.n2 = n2;
                    const el1 = form.querySelector('.math1'); const el2 = form.querySelector('.math2'); if(el1 && el2) { el1.innerText = n1; el2.innerText = n2; }
                    form.dataset.captchaInit = 'true';
                }
            });
        }
        initContactCaptchas(); setInterval(initContactCaptchas, 2000);

        // Střídání jazyků pro tlačítko NALADIT (čistý text bez vlaječek)
        const tuneBtnText = document.querySelector('.tune-text');
        if (tuneBtnText) {
            const origText = tuneBtnText.innerText;
            const langs = [origText, "TUNE IN"];
            let lIdx = 0;
            setInterval(() => {
                lIdx = (lIdx + 1) % langs.length;
                tuneBtnText.style.opacity = 0;
                setTimeout(() => {
                    tuneBtnText.innerText = langs[lIdx];
                    tuneBtnText.style.opacity = 1;
                }, 300);
            }, 3000);
        }

        window.alert = function(text, title='Upozornění', callback=null) {
            document.getElementById('customAlertTitle').innerText = title;
            document.getElementById('customAlertText').innerText = text;
            window.customAlertCallback = callback;
            document.getElementById('customAlertModal').style.display = 'flex';
        };

        // Pomocná funkce pro formátování názvů (Velké první písmeno)
        function capitalizeSongJs(str) {
            if (!str) return str;
            str = str.replace(/\.(mp3|wav|ogg|m4a|aac|flac|wma)$/i, '').replace(/_/g, ' ').replace(/\s*-\s*/g, ' - ');
            return str.split(' ').map(w => w ? w.charAt(0).toUpperCase() + w.slice(1).toLowerCase() : '').join(' ');
        }

        // SPA Navigace (Nepřeruší přehrávač)
        document.addEventListener('click', async (e) => {
            const link = e.target.closest('a');
            if (link && link.href.startsWith(window.location.origin + '/') && !link.hasAttribute('target') && !link.hasAttribute('onclick')) {
                const url = link.href;
                if (url.includes('/admin')) return;
                e.preventDefault();
                const nav = document.querySelector('.fw-nav');
                if (nav && nav.classList.contains('active')) nav.classList.remove('active');
                if (url === window.location.href) return;
                loadPage(url);
                window.history.pushState({url}, '', url);
            }
        });

        window.addEventListener('popstate', (e) => {
            if (e.state && e.state.url) loadPage(e.state.url);
            else loadPage(window.location.href);
        });

        document.addEventListener('submit', async (e) => {
            if (e.target.classList.contains('form-widget-contact') || e.target.classList.contains('form-widget-newsletter') || e.target.classList.contains('form-widget-custom')) {
                e.preventDefault();
                const form = e.target;
                const btn = form.querySelector('button');
                if (!'<?php echo $recaptchaSiteKey; ?>') {
                    const input = form.querySelector('[name="cwMath"]') || form.querySelector('[name="nwMath"]');
                    if (input && parseInt(input.value) !== (parseInt(form.dataset.n1) + parseInt(form.dataset.n2))) { alert('Chybný výsledek matematické ochrany.'); return; }
                }
                const origText = btn.innerText;
                btn.innerText = 'Odesílám...';
                let recaptchaToken = '';
                if ('<?php echo $recaptchaSiteKey; ?>' && typeof grecaptcha !== 'undefined') {
                    try { recaptchaToken = await new Promise((resolve) => { grecaptcha.ready(function() { grecaptcha.execute('<?php echo $recaptchaSiteKey; ?>', {action: 'submit'}).then(function(token) { resolve(token); }); }); }); } catch (e) {}
                }
                try {
                    if (form.classList.contains('form-widget-newsletter')) {
                        const res = await fetch('/admin/api/newsletter-public', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ email: form.querySelector('[name="nwEmail"]').value, action: 'subscribe', recaptcha_token: recaptchaToken }) });
                        const json = await res.json(); if(json.status !== 'success') { alert(json.message); btn.innerText = origText; return; }
                        customAlert(json.message || 'Děkujeme za přihlášení k odběru.', 'Úspěšně přihlášeno');
                    } else if (form.classList.contains('form-widget-custom')) {
                        if (form.dataset.action === 'request') {
                            await fetch('/admin/api/requests', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: form.querySelector('[name="reqName"]').value, email: form.querySelector('[name="reqEmail"]').value, song: form.querySelector('[name="reqSong"]').value, message: form.querySelector('[name="reqMessage"]').value, recaptcha_token: recaptchaToken }) });
                            customAlert('Vaše písnička na přání byla úspěšně odeslána do studia!', 'Odesláno');
                        } else if (form.dataset.action === 'competition_entry') {
                            await fetch('/admin/api/competition_entries', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ comp_id: form.dataset.compid, name: form.querySelector('[name="fld_name"]').value, email: form.querySelector('[name="fld_email"]').value, message: form.querySelector('[name="fld_message"]').value, recaptcha_token: recaptchaToken }) });
                            customAlert('Vaše soutěžní odpověď byla zaznamenána! Přejeme hodně štěstí.', 'Úspěšně odesláno');
                        } else {
                            let msgBody = '';
                            Array.from(form.elements).forEach(el => {
                                if (el.name && el.name.startsWith('fld_') && !el.name.endsWith('_code')) {
                                    const label = el.previousElementSibling ? el.previousElementSibling.innerText.replace('*', '').trim() : el.name;
                                    let val = el.value; if (form.querySelector(`[name="${el.name}_code"]`)) val = form.querySelector(`[name="${el.name}_code"]`).value + ' ' + val;
                                    msgBody += `<strong>${label}:</strong><br>${val}<br><br>`;
                                }
                            });
                            await fetch('/admin/api/send-email', { method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded' }, body: new URLSearchParams({ to: form.dataset.notify, subject: 'Odpověď z formuláře: ' + form.dataset.name, message: msgBody }) });
                            customAlert('Váš formulář byl úspěšně odeslán. Děkujeme.', 'Odesláno');
                        }
                    } else {
                        let msg = form.querySelector('[name="cwMsg"]').value; const phone = form.querySelector('[name="cwPhone"]'); if (phone && phone.value) msg = "Telefon: " + phone.value + "\n\n" + msg;
                        await fetch('/admin/api/contact', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: form.querySelector('[name="cwName"]').value, email: form.querySelector('[name="cwEmail"]').value, message: msg, recaptcha_token: recaptchaToken }) });
                        if (window.location.pathname === '/objednavka') { customAlert('Objednávka byla úspěšně odeslána! Brzy se Vám ozveme.', 'Hotovo'); } else { customAlert('Vaše zpráva byla úspěšně odeslána. Brzy se Vám ozveme.', 'Odesláno'); }
                    }
                    form.reset();
                    form.dataset.captchaInit = ''; initContactCaptchas();
                } catch(err) { console.error(err); customAlert('Při odesílání došlo k síťové chybě. Zkuste to prosím znovu.', 'Chyba připojení'); }
                btn.innerText = origText;
            }
        });

        async function loadPage(url) {
            try {
                const currentContent = document.querySelector('.fw-content');
                currentContent.innerHTML = '<div style="text-align:center; padding: 50px; font-size: 1.5rem; color: var(--accent);">Načítám obsah...</div>';
                const res = await fetch(url); const html = await res.text();
                const parser = new DOMParser(); const doc = parser.parseFromString(html, 'text/html');
                const newContent = doc.querySelector('.fw-content');
                if (newContent) {
                    currentContent.innerHTML = newContent.innerHTML;
                    document.title = doc.title;
                    const scripts = currentContent.querySelectorAll('script');
                    scripts.forEach(oldScript => {
                        const newScript = document.createElement('script');
                        Array.from(oldScript.attributes).forEach(attr => newScript.setAttribute(attr.name, attr.value));
                        newScript.appendChild(document.createTextNode(oldScript.innerHTML));
                        oldScript.parentNode.replaceChild(newScript, oldScript);
                    });
                } else { window.location.href = url; }
            } catch (err) { window.location.href = url; }
        }

        // Globální AJAX aktualizace frontendu
        setInterval(async () => {
            try {
                // 1. Aktualizace Právě hraje (Přehrávač + Postranní boxy)
                const resSet = await fetch('/admin/api/settings-config'); const jsonSet = await resSet.json();
                if (jsonSet.data && jsonSet.data.now_playing) {
                    const np = capitalizeSongJs(jsonSet.data.now_playing);
                    const artwork = jsonSet.data.now_playing_artwork || '';
                    const playerNp = document.getElementById('playerNowPlaying');
                    if (playerNp) playerNp.innerText = np;
                    const playerArt = document.getElementById('playerArtwork');
                    const playerArtPl = document.getElementById('playerArtworkPlaceholder');
                    if (artwork) {
                        if (playerArt) { playerArt.src = artwork; playerArt.style.display = 'block'; }
                        if (playerArtPl) playerArtPl.style.display = 'none';
                    } else {
                        if (playerArt) playerArt.style.display = 'none';
                        if (playerArtPl) playerArtPl.style.display = 'flex';
                    }
                    const boxArtworkHtml = artwork ? `<img src="${artwork}" style="width:60px; height:60px; border-radius:8px; object-fit:cover; box-shadow:var(--glass-shadow);">` : `<div style="width:60px; height:60px; background:rgba(0,0,0,0.2); border-radius:8px; display:inline-flex; align-items:center; justify-content:center; font-size:2.5rem; margin:0 auto;">🎵</div>`;
                    document.querySelectorAll('.ajax-box-nowplaying').forEach(el => el.innerHTML = `<div style="text-align:center;"><a href="/historie" style="text-decoration:none; color:inherit; font-weight:bold; transition:transform 0.2s; display:inline-block; margin-top:5px;" onmouseover="this.style.transform='scale(1.05)'" onmouseout="this.style.transform='scale(1)'" title="Zobrazit historii songů">${boxArtworkHtml}<br>${np}</a></div>`);
                    
                    if (jsonSet.data.upcoming_queue) {
                        let qHtml = '';
                        if (!jsonSet.data.upcoming_queue.length) { qHtml = "<li style='color:var(--text-muted);'>Playlist není k dispozici</li>"; }
                        else { jsonSet.data.upcoming_queue.slice(0,5).forEach(qs => {
                            const txt = typeof qs === 'object' ? (qs.artist || '') + ' - ' + (qs.title || '') : qs;
                            qHtml += `<li style='padding:5px 0; border-bottom:1px solid rgba(255,255,255,0.1);'>${capitalizeSongJs(txt)}</li>`;
                        }); }
                        document.querySelectorAll('.ajax-box-queue').forEach(el => el.innerHTML = qHtml);
                    }
                }

                // 2. Aktualizace Kdo vysílá (ON-AIR Boxy)
                const resOnAir = await fetch('/admin/api/onair');
                const jsonOnAir = await resOnAir.json();
                if (jsonOnAir.status === 'success') {
                    if (jsonOnAir.data.mods && jsonOnAir.data.mods.length > 0) {
                        const onAirTxt = jsonOnAir.data.mods.map(m => {
                        let photo = m.photo ? `<img src="/${m.photo}" style="width:80px; height:80px; border-radius:50%; object-fit:cover; margin-bottom:10px; border:2px solid var(--accent);">` : `<div style="font-size:3rem; margin-bottom:10px;">${m.is_autopilot ? '🤖' : '🎙️'}</div>`;
                            let desc = m.short_desc ? `<div style="font-size:0.9rem; color:var(--text-muted); margin-top:5px;">${m.short_desc}</div>` : '';
                        return `<div style="text-align:center; margin-bottom:15px;"><a href="/moderator/${m.id}" style="text-decoration:none; color:inherit; display:block; transition:transform 0.2s;" onmouseover="this.style.transform='scale(1.05)'" onmouseout="this.style.transform='scale(1)'">${photo}<div style="color:var(--accent); font-weight:bold; font-size:1.2rem;">${m.name}</div>${desc}</a></div>`;
                        }).join('');
                        document.querySelectorAll('.ajax-box-onair').forEach(el => el.innerHTML = onAirTxt);
                    }
                }

                // 3. Aktualizace Historie a Hitparády
                const hitparadaEl = document.getElementById('ajax-hitparada');
                const historyEl = document.getElementById('ajax-history');
                if (hitparadaEl || historyEl) {
                    const resSongs = await fetch('/admin/api/songs');
                    const jsonSongs = await resSongs.json();
                    if (jsonSongs.status === 'success') {
                        const validSongs = jsonSongs.data.filter(s => !s.excluded);
                        if (typeof window.allHistoryData !== 'undefined' && window.renderHistoryPage) { window.allHistoryData = validSongs; window.renderHistoryPage(window.currentHistoryPage); }
                        if (hitparadaEl && window.renderHitparadaPage) {
                            const counts = {}; validSongs.forEach(s => { const key = capitalizeSongJs(s.artist) + ' - ' + capitalizeSongJs(s.title); const igMatch = window.allHistoryData.some(xh => capitalizeSongJs(xh.artist)+' - '+capitalizeSongJs(xh.title) === key); if(!igMatch) return; if (!counts[key]) { counts[key] = { plays: 0, artwork: s.artwork || '' }; } counts[key].plays++; });
                            let sortedCounts = Object.entries(counts).sort((a, b) => b[1].plays - a[1].plays);
                            window.allHitparadaData = sortedCounts.slice(0, 200).map(item => ({ song: item[0], plays: item[1].plays, artwork: item[1].artwork }));
                            window.renderHitparadaPage(window.currentHitparadaPage);
                        }
                    }
                }
            } catch (e) { console.error('AJAX sync failed', e); }
        }, 5000);
    </script>
    <?php if (!empty($tpl['festive_effect']) && $tpl['festive_effect'] !== 'none'): ?>
    <script>
        document.addEventListener('DOMContentLoaded', () => {
            const effect = '<?php echo htmlspecialchars($tpl['festive_effect']); ?>';
            if (effect === 'fireworks') {
                const canvas = document.createElement('canvas');
                canvas.style.position = 'fixed'; canvas.style.top = '0'; canvas.style.left = '0';
                canvas.style.width = '100vw'; canvas.style.height = '100vh';
                canvas.style.pointerEvents = 'none'; canvas.style.zIndex = '99999';
                document.body.appendChild(canvas);
                const ctx = canvas.getContext('2d');
                let w = canvas.width = window.innerWidth; let h = canvas.height = window.innerHeight;
                window.addEventListener('resize', () => { w = canvas.width = window.innerWidth; h = canvas.height = window.innerHeight; });
                const particles = [];
                function createFirework(x, y) {
                    const count = 30 + Math.random() * 20; const color = `hsl(${Math.random() * 360}, 100%, 60%)`;
                    for(let i=0; i<count; i++) {
                        const angle = Math.random() * Math.PI * 2; const speed = Math.random() * 4 + 1;
                        particles.push({x, y, vx: Math.cos(angle)*speed, vy: Math.sin(angle)*speed, life: 1, color, size: Math.random()*3+1});
                    }
                }
                setInterval(() => { if(Math.random()<0.4) createFirework(Math.random()*w, Math.random()*h/2); }, 800);
                function animate() {
                    ctx.clearRect(0, 0, w, h);
                    for(let i=particles.length-1; i>=0; i--) {
                        const p = particles[i];
                        p.x += p.vx; p.y += p.vy; p.vy += 0.05; p.life -= 0.015;
                        if(p.life <= 0) { particles.splice(i, 1); continue; }
                        ctx.globalAlpha = p.life; ctx.fillStyle = p.color;
                        ctx.beginPath(); ctx.arc(p.x, p.y, p.size, 0, Math.PI*2); ctx.fill();
                    }
                    ctx.globalAlpha = 1; requestAnimationFrame(animate);
                }
                animate();
            } else {
                const symbols = { 'snow': ['❄️', '❅', '❆', '•'], 'easter': ['🥚', '🐰', '🌷', '🐥'], 'summer': ['☀️', '🌸', '🌻', '🦋'] }[effect] || ['❄️'];
                const container = document.createElement('div');
                container.style.position = 'fixed'; container.style.top = '0'; container.style.left = '0';
                container.style.width = '100vw'; container.style.height = '100vh';
                container.style.pointerEvents = 'none'; container.style.zIndex = '99998'; container.style.overflow = 'hidden';
                document.body.appendChild(container);
                setInterval(() => {
                    const p = document.createElement('div');
                    p.innerText = symbols[Math.floor(Math.random() * symbols.length)];
                    p.style.position = 'absolute'; p.style.left = Math.random() * 100 + 'vw'; p.style.top = '-5vh';
                    p.style.fontSize = (Math.random() * 1.2 + 0.8) + 'rem'; p.style.opacity = Math.random() * 0.6 + 0.2;
                    const duration = Math.random() * 4 + 5;
                    p.style.transition = `transform ${duration}s linear, top ${duration}s linear`;
                    container.appendChild(p);
                    setTimeout(() => { p.style.top = '105vh'; p.style.transform = `translateX(${(Math.random() - 0.5) * 150}px) rotate(${Math.random() * 360}deg)`; }, 50);
                    setTimeout(() => p.remove(), duration * 1000);
                }, 300);
            }
        });
    </script>
    <?php endif; ?>
<?php if (!empty($tpl['custom_body'])) echo $tpl['custom_body'] . "\n"; ?>
<?php endif; ?>
</body>
</html>