<?php
session_start();
require __DIR__ . '/config.php';
ensure_data_files();

if (isset($_GET['logout'])) {
    unset($_SESSION['admin']);
    header('Location: ' . site_url('admin.php'));
    exit;
}

$loginError = '';
if (isset($_POST['login'])) {
    if (($_POST['username'] ?? '') === ADMIN_USER && ($_POST['password'] ?? '') === ADMIN_PASS) {
        $_SESSION['admin'] = true;
        header('Location: ' . site_url('admin.php'));
        exit;
    }
    $loginError = 'Wrong username or password.';
}

if (empty($_SESSION['admin'])) {
?>
<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>Admin Login</title>
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Oswald:wght@400;600;700&family=Inter:wght@400;500;700&display=swap" rel="stylesheet">
<style>body{margin:0;font-family:Inter,Arial,sans-serif;background:linear-gradient(180deg,#050608,#0b0d12);color:#eef6ff;display:grid;place-items:center;min-height:100vh;padding:18px}.box{width:min(92vw,460px);background:rgba(10,11,16,.9);border:1px solid rgba(255,170,68,.22);padding:28px;border-radius:28px;box-shadow:0 28px 70px rgba(0,0,0,.45)}h1{font-family:Oswald,Arial,sans-serif;margin:0 0 10px}input,button{width:100%;max-width:100%;padding:13px 14px;margin:8px 0;border-radius:14px}input{border:1px solid rgba(255,255,255,.1);background:rgba(255,255,255,.06);color:#eef6ff}button{background:linear-gradient(180deg,#ffb347,#ff7f11);font-weight:800;border:0;cursor:pointer;color:#210d00}.err{color:#ff9f9f;margin-bottom:6px}a{color:#ffd391}</style></head><body>
<div class="box"><h1>BroadcastUrSelf Admin</h1><p>Manage the main site, active event, stations, winners, and submission form.</p>
<?php if ($loginError): ?><div class="err"><?= e($loginError) ?></div><?php endif; ?>
<form method="post"><input type="text" name="username" placeholder="Username" required><input type="password" name="password" placeholder="Password" required><button type="submit" name="login">Log In</button></form>
<p><a href="<?= e(site_url('index.php')) ?>">Back to site</a></p></div></body></html>
<?php exit; }

$settings = get_settings();
$submissions = get_submissions();
$message = '';
$filters = [
    'q' => trim((string)($_GET['q'] ?? '')),
    'entry_type' => trim((string)($_GET['entry_type'] ?? '')),
    'platform' => trim((string)($_GET['platform'] ?? '')),
];

function textarea_to_array(string $value): array {
    $lines = preg_split('/\r\n|\r|\n/', trim($value)) ?: [];
    return array_values(array_filter(array_map('trim', $lines)));
}

function station_assets_dir(): string { return __DIR__ . '/assets/stations'; }
function station_assets_url_dir(): string { return 'assets/stations'; }
function ensure_station_assets_dir(): void { if (!is_dir(station_assets_dir())) mkdir(station_assets_dir(), 0775, true); }

function absolutize_url(string $baseUrl, string $maybeRelative): string {
    $maybeRelative = trim($maybeRelative);
    if ($maybeRelative === '') return '';
    if (preg_match('~^https?://~i', $maybeRelative)) return $maybeRelative;
    $base = parse_url($baseUrl);
    if (!$base || empty($base['scheme']) || empty($base['host'])) return $maybeRelative;
    $scheme = $base['scheme']; $host = $base['host']; $port = isset($base['port']) ? ':' . $base['port'] : '';
    if (strpos($maybeRelative, '//') === 0) return $scheme . ':' . $maybeRelative;
    if (strpos($maybeRelative, '/') === 0) return $scheme . '://' . $host . $port . $maybeRelative;
    $path = $base['path'] ?? '/'; $path = preg_replace('~/[^/]*$~', '/', $path);
    return $scheme . '://' . $host . $port . $path . $maybeRelative;
}

function fetch_remote_text(string $url): array {
    $result = ['ok' => false, 'body' => '', 'error' => ''];
    $ch = curl_init($url);
    curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true, CURLOPT_MAXREDIRS => 5, CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_TIMEOUT => 20, CURLOPT_USERAGENT => 'BroadcastUrSelf Logo Fetcher/1.0', CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => false]);
    $body = curl_exec($ch); $err = curl_error($ch); $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE); curl_close($ch);
    if ($body === false || $code >= 400 || $code === 0) { $result['error'] = $err ?: ('HTTP ' . $code); return $result; }
    $result['ok'] = true; $result['body'] = (string)$body; return $result;
}

function download_remote_file(string $url): array {
    $result = ['ok' => false, 'data' => null, 'mime' => '', 'error' => ''];
    $ch = curl_init($url);
    curl_setopt_array($ch, [CURLOPT_RETURNTRANSFER => true, CURLOPT_FOLLOWLOCATION => true, CURLOPT_MAXREDIRS => 5, CURLOPT_CONNECTTIMEOUT => 10, CURLOPT_TIMEOUT => 25, CURLOPT_USERAGENT => 'BroadcastUrSelf Logo Fetcher/1.0', CURLOPT_SSL_VERIFYPEER => false, CURLOPT_SSL_VERIFYHOST => false]);
    $data = curl_exec($ch); $err = curl_error($ch); $code = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE); $mime = (string)curl_getinfo($ch, CURLINFO_CONTENT_TYPE); curl_close($ch);
    if ($data === false || $code >= 400 || $code === 0) { $result['error'] = $err ?: ('HTTP ' . $code); return $result; }
    $result['ok'] = true; $result['data'] = $data; $result['mime'] = $mime; return $result;
}

function logo_candidates_from_html(string $html, string $website): array {
    $candidates = [];
    if (preg_match('~<meta[^>]+property=["\']og:image["\'][^>]+content=["\']([^"\']+)["\']~i', $html, $m)) $candidates[] = absolutize_url($website, html_entity_decode($m[1], ENT_QUOTES));
    if (preg_match('~<meta[^>]+name=["\']twitter:image["\'][^>]+content=["\']([^"\']+)["\']~i', $html, $m)) $candidates[] = absolutize_url($website, html_entity_decode($m[1], ENT_QUOTES));
    if (preg_match_all('~<link[^>]+rel=["\'][^"\']*(?:icon|shortcut icon|apple-touch-icon)[^"\']*["\'][^>]+href=["\']([^"\']+)["\']~i', $html, $m)) foreach ($m[1] as $href) $candidates[] = absolutize_url($website, html_entity_decode($href, ENT_QUOTES));
    if (preg_match_all('~<img[^>]+(?:src|data-src)=["\']([^"\']+)["\'][^>]*>~i', $html, $m)) {
        foreach ($m[1] as $src) {
            $src = absolutize_url($website, html_entity_decode($src, ENT_QUOTES)); $score = 0; $lower = strtolower($src);
            if (strpos($lower, 'logo') !== false) $score += 5;
            if (strpos($lower, 'header') !== false) $score += 2;
            if (preg_match('~\.(svg|png|webp|jpg|jpeg)(\?|$)~i', $lower)) $score += 1;
            $candidates[] = ['url' => $src, 'score' => $score];
        }
    }
    $flat = [];
    foreach ($candidates as $candidate) $flat[] = is_array($candidate) ? $candidate : ['url' => $candidate, 'score' => 10];
    $dedup = [];
    foreach ($flat as $item) { $url = trim((string)($item['url'] ?? '')); if ($url === '') continue; $dedup[$url] = max($dedup[$url] ?? 0, (int)($item['score'] ?? 0)); }
    $out = [];
    foreach ($dedup as $url => $score) $out[] = ['url' => $url, 'score' => $score];
    usort($out, fn($a, $b) => ($b['score'] <=> $a['score']) ?: strcmp($a['url'], $b['url']));
    return array_column($out, 'url');
}

function station_slug(string $name): string {
    $slug = strtolower(trim($name)); $slug = preg_replace('~[^a-z0-9]+~', '-', $slug); $slug = trim($slug, '-');
    return $slug !== '' ? $slug : 'station';
}

function file_extension_from_url_or_mime(string $url, string $mime): string {
    $path = parse_url($url, PHP_URL_PATH) ?: ''; $ext = strtolower(pathinfo($path, PATHINFO_EXTENSION));
    if (in_array($ext, ['png','jpg','jpeg','gif','webp','svg','ico'], true)) return $ext === 'jpeg' ? 'jpg' : $ext;
    $mime = strtolower(trim(explode(';', $mime)[0]));
    $map = ['image/png' => 'png','image/jpeg' => 'jpg','image/jpg' => 'jpg','image/gif' => 'gif','image/webp' => 'webp','image/svg+xml' => 'svg','image/x-icon' => 'ico','image/vnd.microsoft.icon' => 'ico'];
    return $map[$mime] ?? 'png';
}

function fetch_station_logo(string $stationName, string $website): array {
    $website = trim($website); if ($website === '') return ['ok' => false, 'error' => 'No website set for this station.'];
    ensure_station_assets_dir(); $page = fetch_remote_text($website);
    if (!$page['ok']) return ['ok' => false, 'error' => 'Could not open station website: ' . $page['error']];
    $candidates = logo_candidates_from_html($page['body'], $website);
    if (!$candidates) return ['ok' => false, 'error' => 'No logo candidate found on the station website.'];
    foreach ($candidates as $candidate) {
        $file = download_remote_file($candidate); if (!$file['ok']) continue;
        $mime = strtolower(trim(explode(';', $file['mime'])[0]));
        $looksLikeImage = strpos($mime, 'image/') === 0 || preg_match('~\.(png|jpg|jpeg|gif|webp|svg|ico)(\?|$)~i', $candidate);
        if (!$looksLikeImage || empty($file['data'])) continue;
        $ext = file_extension_from_url_or_mime($candidate, $file['mime']); $slug = station_slug($stationName);
        $filename = $slug . '-logo.' . $ext; $savePath = station_assets_dir() . '/' . $filename; file_put_contents($savePath, $file['data']);
        return ['ok' => true, 'path' => station_assets_url_dir() . '/' . $filename, 'source' => $candidate];
    }
    return ['ok' => false, 'error' => 'Logo candidates were found, but none could be downloaded as an image.'];
}

function station_rows_from_post(): array {
    $rows = $_POST['stations'] ?? []; $stations = [];
    if (!is_array($rows)) return $stations;
    foreach ($rows as $row) {
        if (!is_array($row)) continue;
        $station = ['name' => trim((string)($row['name'] ?? '')), 'website' => trim((string)($row['website'] ?? '')), 'stream' => trim((string)($row['stream'] ?? '')), 'logo' => trim((string)($row['logo'] ?? '')), 'note' => trim((string)($row['note'] ?? '')), 'enabled' => isset($row['enabled'])];
        if ($station['name'] === '' && $station['website'] === '' && $station['stream'] === '' && $station['logo'] === '' && $station['note'] === '') continue;
        $stations[] = $station;
    }
    return $stations;
}

function schedule_rows_from_post(): array {
    $rows = $_POST['event_schedule'] ?? []; $schedule = [];
    if (!is_array($rows)) return $schedule;
    foreach ($rows as $row) {
        if (!is_array($row)) continue;
        $item = [
            'day_key' => trim((string)($row['day_key'] ?? '')),
            'day_label' => trim((string)($row['day_label'] ?? '')),
            'start' => trim((string)($row['start'] ?? '')),
            'end' => trim((string)($row['end'] ?? '')),
            'title' => trim((string)($row['title'] ?? '')),
            'station' => trim((string)($row['station'] ?? '')),
            'note' => trim((string)($row['note'] ?? '')),
            'enabled' => isset($row['enabled'])
        ];
        if ($item['day_key'] === '' && $item['day_label'] === '' && $item['start'] === '' && $item['end'] === '' && $item['title'] === '' && $item['station'] === '' && $item['note'] === '') continue;
        $schedule[] = $item;
    }
    return $schedule;
}

function winner_rows_from_post(): array {

    $rows = $_POST['winners'] ?? []; $winners = [];
    if (!is_array($rows)) return $winners;
    foreach ($rows as $row) {
        if (!is_array($row)) continue;
        $winner = ['name' => trim((string)($row['name'] ?? '')), 'details' => trim((string)($row['details'] ?? '')), 'station' => trim((string)($row['station'] ?? '')), 'prize' => trim((string)($row['prize'] ?? ''))];
        if ($winner['name'] === '' && $winner['details'] === '' && $winner['station'] === '' && $winner['prize'] === '') continue;
        $winners[] = $winner;
    }
    return $winners;
}

function apply_preset(array &$settings, string $preset): void {
    $settings['event_preset'] = $preset;
    $settings['show_entry_type'] = true;
    $settings['show_field_one'] = true;
    $settings['show_field_two'] = false;
    $settings['show_field_three'] = false;
    $settings['show_message_field'] = false;
    $settings['show_name_field'] = true;
    $settings['show_email_field'] = true;
    $settings['show_platform_field'] = true;

    $settings['require_entry_type'] = false;
    $settings['require_field_one'] = true;
    $settings['require_field_two'] = false;
    $settings['require_field_three'] = false;
    $settings['require_message_field'] = false;
    $settings['require_name_field'] = false;
    $settings['require_email_field'] = true;
    $settings['require_platform_field'] = true;

    switch ($preset) {
        case 'clue_hunt':
            $settings['entry_type_options'] = ['Clue Answer', 'Competition Entry'];
            $settings['field_one_label'] = 'Main Answer';
            $settings['field_two_label'] = 'Second Detail';
            $settings['show_field_two'] = true;
            break;
        case 'song_guess':
            $settings['entry_type_options'] = ['Song Guess'];
            $settings['field_one_label'] = 'Artist Name';
            $settings['field_one_placeholder'] = 'Enter the artist name';
            $settings['field_two_label'] = 'Song Title';
            $settings['field_two_placeholder'] = 'Enter the song title';
            $settings['show_field_two'] = true;
            $settings['require_field_two'] = true;
            break;
        case 'giveaway':
            $settings['entry_type_options'] = ['Giveaway Entry'];
            $settings['field_one_label'] = 'Entry Answer';
            $settings['show_message_field'] = true;
            break;
        case 'signup':
            $settings['entry_type_options'] = ['Signup'];
            $settings['field_one_label'] = 'Signup Subject';
            $settings['show_message_field'] = true;
            $settings['require_name_field'] = true;
            break;
        case 'announcement_only':
            $settings['show_submission_button'] = false;
            $settings['submission_page_open'] = false;
            break;
        case 'first_entry':
            $settings['entry_type_options'] = ['First Entry Wins'];
            $settings['field_one_label'] = 'Entry';
            break;
        case 'top_three':
            $settings['entry_type_options'] = ['Top 3 Entry'];
            $settings['field_one_label'] = 'Entry';
            $settings['show_message_field'] = true;
            break;
        default:
            break;
    }
}

function filter_submission_rows(array $rows, array $filters): array {
    return array_values(array_filter($rows, function ($row) use ($filters) {
        if ($filters['entry_type'] !== '' && (($row['entry_type'] ?? '') !== $filters['entry_type'])) return false;
        if ($filters['platform'] !== '' && (($row['platform'] ?? '') !== $filters['platform'])) return false;
        if ($filters['q'] !== '') {
            $hay = strtolower(implode(' ', [$row['entry_type'] ?? '', $row['field_one'] ?? '', $row['field_two'] ?? '', $row['field_three'] ?? '', $row['message_text'] ?? '', $row['name'] ?? '', $row['email'] ?? '', $row['platform'] ?? '']));
            if (strpos($hay, strtolower($filters['q'])) === false) return false;
        }
        return true;
    }));
}

if (isset($_POST['save_settings'])) {
    $keys = ['site_name','site_tagline','site_logo','site_intro','community_blurb','footer_note','primary_button_label','primary_button_url','secondary_button_label','station_heading','site_mode','event_preset','event_type','event_name','headline','event_poster','pot_label','pot_value','date_range','description','how_it_works','event_notice','cta_text','status_text','announcement_text','announcement_link','coming_soon_title','coming_soon_text','live_now_title','live_now_text','winners_title','winners_text','no_event_title','no_event_text','submission_button_text','submission_title','submission_intro','success_message','entry_type_label','field_one_label','field_one_placeholder','field_two_label','field_two_placeholder','field_three_label','field_three_placeholder','field_message_label','field_message_placeholder','name_label','email_label','platform_label','start_at','end_at','submission_open_at','submission_close_at','schedule_timezone','schedule_title','schedule_intro'];
    foreach ($keys as $key) $settings[$key] = trim($_POST[$key] ?? '');

    $checkboxKeys = ['event_active','show_prize_box','show_submission_button','submission_page_open','show_countdown','submissions_auto_schedule','announcement_enabled','show_entry_type','require_entry_type','show_field_one','require_field_one','show_field_two','require_field_two','show_field_three','require_field_three','show_message_field','require_message_field','show_name_field','require_name_field','show_email_field','require_email_field','show_platform_field','require_platform_field'];
    foreach ($checkboxKeys as $key) $settings[$key] = isset($_POST[$key]);

    $settings['stations'] = station_rows_from_post();
    $settings['winners'] = winner_rows_from_post();
    $settings['event_schedule'] = schedule_rows_from_post();
    $settings['platforms'] = textarea_to_array($_POST['platforms'] ?? '');
    $settings['entry_type_options'] = textarea_to_array($_POST['entry_type_options'] ?? '');

    if (isset($_POST['apply_preset']) && trim((string)($_POST['event_preset'] ?? '')) !== '') {
        apply_preset($settings, trim((string)$_POST['event_preset']));
        $message = 'Preset applied. Review the fields and save again if you want to fine-tune anything.';
    } else {
        $message = 'Settings saved.';
    }

    save_settings($settings);
    $settings = get_settings();
}

if (isset($_POST['quick_close'])) {
    $settings['submission_page_open'] = false;
    $settings['submissions_auto_schedule'] = false;
    save_settings($settings);
    $settings = get_settings();
    $message = 'Submissions closed.';
}

if (isset($_POST['fetch_station_logo'])) {
    $settings['stations'] = station_rows_from_post();
    $index = (int)($_POST['fetch_station_logo']);
    if (isset($settings['stations'][$index])) {
        $station = $settings['stations'][$index];
        $result = fetch_station_logo((string)($station['name'] ?? ''), (string)($station['website'] ?? ''));
        if ($result['ok']) {
            $settings['stations'][$index]['logo'] = $result['path'];
            save_settings($settings);
            $settings = get_settings();
            $message = 'Logo fetched for ' . ($station['name'] ?: 'station') . '.';
        } else {
            $message = $result['error'];
        }
    }
}

if (isset($_POST['mark_winner'])) {
    $index = (int)$_POST['mark_winner'];
    $rank = trim((string)($_POST['winner_rank'][$index] ?? 'Winner'));
    if (isset($submissions[$index])) {
        $submissions[$index]['is_winner'] = true;
        $submissions[$index]['winner_rank'] = $rank !== '' ? $rank : 'Winner';
        save_submissions($submissions);
        $submissions = get_submissions();
        $message = 'Submission marked as winner.';
    }
}

if (isset($_POST['unmark_winner'])) {
    $index = (int)$_POST['unmark_winner'];
    if (isset($submissions[$index])) {
        $submissions[$index]['is_winner'] = false;
        $submissions[$index]['winner_rank'] = '';
        save_submissions($submissions);
        $submissions = get_submissions();
        $message = 'Winner mark removed.';
    }
}

if (isset($_POST['add_marked_winners_to_page'])) {
    $winners = [];
    foreach ($submissions as $row) {
        if (!empty($row['is_winner'])) {
            $name = trim((string)($row['name'] ?? ''));
            $details = trim(implode(' / ', array_filter([$row['winner_rank'] ?? '', $row['field_one'] ?? '', $row['field_two'] ?? '', $row['field_three'] ?? ''])));
            $station = trim((string)($row['platform'] ?? ''));
            $winners[] = ['name' => $name !== '' ? $name : 'Winner', 'details' => $details, 'station' => $station, 'prize' => ''];
        }
    }
    $settings['winners'] = $winners;
    save_settings($settings);
    $settings = get_settings();
    $message = 'Marked winners copied into the winners panel.';
}

if (isset($_POST['delete_submission'])) {
    $index = (int) $_POST['delete_submission'];
    if (isset($submissions[$index])) {
        unset($submissions[$index]);
        save_submissions($submissions);
        $submissions = get_submissions();
        $message = 'Submission deleted.';
    }
}

if (isset($_POST['clear_submissions'])) {
    save_submissions([]);
    $submissions = [];
    $message = 'All submissions cleared.';
}

if (isset($_GET['export']) && $_GET['export'] === 'csv') {
    header('Content-Type: text/csv');
    header('Content-Disposition: attachment; filename="broadcasturself-submissions.csv"');
    $out = fopen('php://output', 'w');
    fputcsv($out, ['Winner','Winner Rank','Entry Type','Field One','Field Two','Field Three','Message','Name','Email','Platform','IP','Timestamp']);
    foreach ($submissions as $row) {
        fputcsv($out, [!empty($row['is_winner']) ? 'Yes' : 'No', $row['winner_rank'] ?? '', $row['entry_type'] ?? '', $row['field_one'] ?? '', $row['field_two'] ?? '', $row['field_three'] ?? '', $row['message_text'] ?? '', $row['name'] ?? '', $row['email'] ?? '', $row['platform'] ?? '', $row['ip'] ?? '', $row['timestamp'] ?? '']);
    }
    fclose($out);
    exit;
}

$stations = $settings['stations'] ?? [];
$winners = $settings['winners'] ?? [];
$eventSchedule = $settings['event_schedule'] ?? [];
$filteredSubmissions = filter_submission_rows($submissions, $filters);
$entryTypes = array_values(array_unique(array_filter(array_map(fn($row) => trim((string)($row['entry_type'] ?? '')), $submissions))));
$platformsSeen = array_values(array_unique(array_filter(array_map(fn($row) => trim((string)($row['platform'] ?? '')), $submissions))));
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
<title>BroadcastUrSelf Admin</title>
<link rel="preconnect" href="https://fonts.googleapis.com"><link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Oswald:wght@400;600;700&family=Inter:wght@400;500;700&display=swap" rel="stylesheet">
<style>
:root{--bg:#050608;--panel:rgba(10,11,16,.9);--panel2:rgba(255,255,255,.03);--line:rgba(255,170,68,.22);--text:#eef6ff;--muted:rgba(238,246,255,.74);--gold:#ffb347;--gold2:#ff7f11}
*{box-sizing:border-box} body{margin:0;font-family:Inter,system-ui,sans-serif;color:var(--text);background:linear-gradient(180deg,#050608,#0b0d12)}
.wrap{max-width:1480px;margin:0 auto;padding:22px 18px 50px}.top{display:flex;justify-content:space-between;align-items:center;gap:12px;flex-wrap:wrap;margin-bottom:18px}.top a{color:#ffd391}
.grid{display:grid;grid-template-columns:1.12fr .88fr;gap:20px}.panel{background:var(--panel);border:1px solid var(--line);border-radius:28px;padding:22px;box-shadow:0 28px 70px rgba(0,0,0,.45);min-width:0}
h1,h2,h3{font-family:Oswald,Inter,sans-serif;margin:0 0 12px} p{color:var(--muted)} label{display:block;font-weight:700;margin:10px 0 8px}
input,textarea,select{width:100%;max-width:100%;padding:13px 14px;border-radius:14px;border:1px solid rgba(255,255,255,.1);background:rgba(255,255,255,.06);color:var(--text)}
textarea{min-height:110px;resize:vertical}.row{display:grid;grid-template-columns:1fr 1fr;gap:14px}.row3{display:grid;grid-template-columns:1fr 1fr 1fr;gap:14px}
.checks{display:flex;gap:18px;flex-wrap:wrap;margin-top:8px}.checks label{display:flex;align-items:center;gap:8px;margin:0;font-weight:600}.checks input{width:auto}
button,.button{display:inline-flex;align-items:center;justify-content:center;padding:13px 18px;border-radius:999px;border:0;cursor:pointer;font-weight:800;background:linear-gradient(180deg,var(--gold),var(--gold2));color:#210d00;text-decoration:none}
.button.secondary, button.secondary{background:rgba(255,255,255,.08);color:var(--text);border:1px solid rgba(255,255,255,.09)} .remove{background:rgba(255,255,255,.08)!important;color:var(--text)!important;border:1px solid rgba(255,255,255,.08)!important}
.msg{margin:0 0 14px;padding:12px 14px;border-radius:14px;background:rgba(36,121,24,.25);border:1px solid rgba(126,217,87,.28)}.small{font-size:.92rem;color:var(--muted)}
.toggle-grid{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:12px;margin-top:8px}.toggle-row{padding:14px;border-radius:18px;background:var(--panel2);border:1px solid rgba(255,255,255,.06)}
.toggle-title{font-weight:800;margin-bottom:10px}.toggle-row label{display:flex;align-items:center;gap:8px;margin:8px 0 0;font-weight:600}.toggle-row input{width:auto}
.station-manager,.winner-manager,.schedule-manager{display:grid;gap:14px;margin-top:12px}.station-row,.winner-row,.schedule-row{background:var(--panel2);border:1px solid rgba(255,255,255,.07);border-radius:22px;padding:16px}
.station-top,.winner-top,.schedule-top{display:flex;justify-content:space-between;align-items:center;gap:14px;flex-wrap:wrap;margin-bottom:8px}.station-enable,.schedule-enable{display:flex;align-items:center;gap:8px;font-weight:700}.station-enable input,.schedule-enable input{width:auto}.station-actions,.winner-actions,.schedule-actions{display:flex;gap:10px;flex-wrap:wrap}
.station-grid,.winner-grid,.schedule-grid{display:grid;grid-template-columns:1fr 1fr;gap:14px}.station-grid .full,.winner-grid .full,.schedule-grid .full{grid-column:1 / -1}
.table-wrap{overflow:auto} table{width:100%;border-collapse:collapse;min-width:1180px} th,td{padding:12px;border-bottom:1px solid rgba(255,255,255,.08);text-align:left;vertical-align:top} td form{margin:0} code.hint{display:inline-block;margin-top:6px;padding:5px 8px;border-radius:10px;background:rgba(255,255,255,.05)}
.rank-input{min-width:120px;width:120px}.filters{display:grid;grid-template-columns:1.2fr .9fr .9fr auto;gap:12px;align-items:end;margin-bottom:16px}
@media (max-width:1180px){.grid{grid-template-columns:1fr}} @media (max-width:860px){.row,.row3,.toggle-grid,.station-grid,.winner-grid,.filters{grid-template-columns:1fr}}
</style>
</head>
<body>
<div class="wrap">
  <div class="top">
    <div><h1>BroadcastUrSelf Admin</h1><p>Control the main site, the event engine, participating stations, winners, and submissions from one place.</p></div>
    <div style="display:flex;gap:10px;flex-wrap:wrap"><a class="button secondary" href="<?= e(site_url('index.php')) ?>">View Site</a><a class="button secondary" href="<?= e(site_url('admin.php?logout=1')) ?>">Log Out</a></div>
  </div>

  <div class="grid">
    <div class="panel">
      <?php if ($message): ?><div class="msg"><?= e($message) ?></div><?php endif; ?>
      <form method="post">
        <h2>Site branding</h2>
        <div class="row">
          <div><label>Site Name</label><input type="text" name="site_name" value="<?= e($settings['site_name'] ?? '') ?>"></div>
          <div><label>Site Tagline</label><input type="text" name="site_tagline" value="<?= e($settings['site_tagline'] ?? '') ?>"></div>
        </div>
        <div class="row">
          <div><label>Site Logo / Header Banner</label><input type="text" name="site_logo" value="<?= e($settings['site_logo'] ?? '') ?>"></div>
          <div><label>Footer Note</label><input type="text" name="footer_note" value="<?= e($settings['footer_note'] ?? '') ?>"></div>
        </div>
        <label>Site Intro</label><textarea name="site_intro"><?= e($settings['site_intro'] ?? '') ?></textarea>
        <label>Community Blurb</label><textarea name="community_blurb"><?= e($settings['community_blurb'] ?? '') ?></textarea>

        <h2 style="margin-top:26px">Site mode and preset</h2>
        <div class="row3">
          <div>
            <label>Site Mode</label>
            <select name="site_mode">
              <?php foreach (['active_event' => 'Active Event','coming_soon' => 'Coming Soon','live_now' => 'Live Now','winners_announced' => 'Winners Announced','no_event' => 'No Event'] as $val => $label): ?>
                <option value="<?= e($val) ?>" <?= ($settings['site_mode'] ?? '') === $val ? 'selected' : '' ?>><?= e($label) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div>
            <label>Event Preset</label>
            <select name="event_preset">
              <?php foreach (['custom' => 'Custom','clue_hunt' => 'Clue Hunt','song_guess' => 'Song Guess','giveaway' => 'Giveaway','signup' => 'Signup / Registration','announcement_only' => 'Announcement Only','first_entry' => 'First Entry Wins','top_three' => 'Top 3 Winners'] as $val => $label): ?>
                <option value="<?= e($val) ?>" <?= ($settings['event_preset'] ?? '') === $val ? 'selected' : '' ?>><?= e($label) ?></option>
              <?php endforeach; ?>
            </select>
          </div>
          <div style="display:flex;align-items:end"><button type="submit" name="apply_preset" value="1">Apply Preset</button></div>
        </div>

        <h2 style="margin-top:26px">Announcement bar</h2>
        <div class="checks"><label><input type="checkbox" name="announcement_enabled" <?= !empty($settings['announcement_enabled']) ? 'checked' : '' ?>> Show announcement bar</label></div>
        <div class="row">
          <div><label>Announcement Text</label><input type="text" name="announcement_text" value="<?= e($settings['announcement_text'] ?? '') ?>"></div>
          <div><label>Announcement Link</label><input type="text" name="announcement_link" value="<?= e($settings['announcement_link'] ?? '') ?>"></div>
        </div>

        <h2 style="margin-top:26px">Featured event</h2>
        <div class="row3">
          <div><label>Event Type</label><input type="text" name="event_type" value="<?= e($settings['event_type'] ?? '') ?>"></div>
          <div><label>Event Name</label><input type="text" name="event_name" value="<?= e($settings['event_name'] ?? '') ?>"></div>
          <div><label>Poster Image</label><input type="text" name="event_poster" value="<?= e($settings['event_poster'] ?? '') ?>"></div>
        </div>
        <div class="row3">
          <div><label>Primary Button Label</label><input type="text" name="primary_button_label" value="<?= e($settings['primary_button_label'] ?? '') ?>"></div>
          <div><label>Primary Event Link</label><input type="text" name="primary_button_url" value="<?= e($settings['primary_button_url'] ?? '') ?>"></div>
          <div><label>Submission Button Text</label><input type="text" name="submission_button_text" value="<?= e($settings['submission_button_text'] ?? '') ?>"></div>
        </div>
        <div class="row3">
          <div><label>Headline</label><input type="text" name="headline" value="<?= e($settings['headline'] ?? '') ?>"></div>
          <div><label>Dates</label><input type="text" name="date_range" value="<?= e($settings['date_range'] ?? '') ?>"></div>
          <div><label>Status Text</label><input type="text" name="status_text" value="<?= e($settings['status_text'] ?? '') ?>"></div>
        </div>
        <div class="row"><div><label>Pot / Prize Label</label><input type="text" name="pot_label" value="<?= e($settings['pot_label'] ?? '') ?>"></div><div><label>Pot / Prize Value</label><input type="text" name="pot_value" value="<?= e($settings['pot_value'] ?? '') ?>"></div></div>
        <label>Description</label><textarea name="description"><?= e($settings['description'] ?? '') ?></textarea>
        <label>How It Works</label><textarea name="how_it_works"><?= e($settings['how_it_works'] ?? '') ?></textarea>
        <div class="row"><div><label>Event Notice</label><input type="text" name="event_notice" value="<?= e($settings['event_notice'] ?? '') ?>"></div><div><label>Call To Action</label><input type="text" name="cta_text" value="<?= e($settings['cta_text'] ?? '') ?>"></div></div>

        <h2 style="margin-top:26px">Countdown and scheduling</h2>
        <div class="checks">
          <label><input type="checkbox" name="show_countdown" <?= !empty($settings['show_countdown']) ? 'checked' : '' ?>> Show countdown</label>
          <label><input type="checkbox" name="submissions_auto_schedule" <?= !empty($settings['submissions_auto_schedule']) ? 'checked' : '' ?>> Auto schedule submissions</label>
        </div>
        <div class="row">
          <div><label>Event Start (any PHP strtotime format)</label><input type="text" name="start_at" value="<?= e($settings['start_at'] ?? '') ?>" placeholder="2026-04-03 18:00"></div>
          <div><label>Event End</label><input type="text" name="end_at" value="<?= e($settings['end_at'] ?? '') ?>" placeholder="2026-04-06 22:00"></div>
        </div>
        <div class="row">
          <div><label>Submission Open At</label><input type="text" name="submission_open_at" value="<?= e($settings['submission_open_at'] ?? '') ?>" placeholder="2026-04-03 18:00"></div>
          <div><label>Submission Close At</label><input type="text" name="submission_close_at" value="<?= e($settings['submission_close_at'] ?? '') ?>" placeholder="2026-04-06 22:00"></div>
        </div>

        <h2 style="margin-top:26px">State copy</h2>
        <div class="row">
          <div><label>Coming Soon Title</label><input type="text" name="coming_soon_title" value="<?= e($settings['coming_soon_title'] ?? '') ?>"></div>
          <div><label>Coming Soon Text</label><input type="text" name="coming_soon_text" value="<?= e($settings['coming_soon_text'] ?? '') ?>"></div>
        </div>
        <div class="row">
          <div><label>Live Now Title</label><input type="text" name="live_now_title" value="<?= e($settings['live_now_title'] ?? '') ?>"></div>
          <div><label>Live Now Text</label><input type="text" name="live_now_text" value="<?= e($settings['live_now_text'] ?? '') ?>"></div>
        </div>
        <div class="row">
          <div><label>Winners Title</label><input type="text" name="winners_title" value="<?= e($settings['winners_title'] ?? '') ?>"></div>
          <div><label>Winners Text</label><input type="text" name="winners_text" value="<?= e($settings['winners_text'] ?? '') ?>"></div>
        </div>
        <div class="row">
          <div><label>No Event Title</label><input type="text" name="no_event_title" value="<?= e($settings['no_event_title'] ?? '') ?>"></div>
          <div><label>Station Section Heading</label><input type="text" name="station_heading" value="<?= e($settings['station_heading'] ?? '') ?>"></div>
        </div>
        <label>No Event Text</label><textarea name="no_event_text"><?= e($settings['no_event_text'] ?? '') ?></textarea>

        <h2 style="margin-top:26px">Participating stations</h2>
        <p class="small">Turn each station on only when it is taking part. Add as many as you need. Each station can have its own website, stream link, optional note, and optional logo image path or URL.</p>
        <div id="stationManager" class="station-manager">
          <?php foreach ($stations as $i => $station): ?>
            <div class="station-row">
              <div class="station-top">
                <label class="station-enable"><input type="checkbox" name="stations[<?= $i ?>][enabled]" <?= !empty($station['enabled']) ? 'checked' : '' ?>> Enabled for this event</label>
                <div class="station-actions">
                  <button type="submit" name="fetch_station_logo" value="<?= $i ?>" class="secondary">Fetch Logo</button>
                  <button type="button" class="remove" onclick="removeStationRow(this)">Remove</button>
                </div>
              </div>
              <div class="station-grid">
                <div><label>Station Name</label><input type="text" name="stations[<?= $i ?>][name]" value="<?= e($station['name'] ?? '') ?>"></div>
                <div><label>Logo Path / URL</label><input type="text" name="stations[<?= $i ?>][logo]" value="<?= e($station['logo'] ?? '') ?>" placeholder="assets/stations/my-station.png"></div>
                <div><label>Website Link</label><input type="text" name="stations[<?= $i ?>][website]" value="<?= e($station['website'] ?? '') ?>" placeholder="https://example.com/"></div>
                <div><label>Listen Link</label><input type="text" name="stations[<?= $i ?>][stream]" value="<?= e($station['stream'] ?? '') ?>" placeholder="http://stream.example.com/live"></div>
                <div class="full"><label>Station Note</label><input type="text" name="stations[<?= $i ?>][note]" value="<?= e($station['note'] ?? '') ?>" placeholder="Clues every hour / supporting the hunt / weekend support"></div>
              </div>
            </div>
          <?php endforeach; ?>
        </div>
        <div style="display:flex;gap:10px;flex-wrap:wrap;margin-top:14px"><button type="button" class="secondary" onclick="addStationRow()">+ Add Station</button></div>
        <p class="small">Fetch Logo looks for a usable image on the station website, saves it into <code class="hint">assets/stations/</code>, and fills the logo field with the local path.</p>

        <div class="checks" style="margin-top:18px">
          <label><input type="checkbox" name="event_active" <?= !empty($settings['event_active']) ? 'checked' : '' ?>> Featured event active</label>
          <label><input type="checkbox" name="show_prize_box" <?= !empty($settings['show_prize_box']) ? 'checked' : '' ?>> Show prize box</label>
          <label><input type="checkbox" name="show_submission_button" <?= !empty($settings['show_submission_button']) ? 'checked' : '' ?>> Show submission button</label>
          <label><input type="checkbox" name="submission_page_open" <?= !empty($settings['submission_page_open']) ? 'checked' : '' ?>> Open submission page now</label>
        </div>

        <h2 style="margin-top:26px">Event schedule</h2>
        <p class="small">Public side shows this as the live 24 hour event schedule. Admin side lets you add, remove, disable, or replace slots as more DJs are confirmed.</p>
        <div class="row3">
          <div><label>Schedule Title</label><input type="text" name="schedule_title" value="<?= e($settings['schedule_title'] ?? '') ?>"></div>
          <div><label>Schedule Timezone Label</label><input type="text" name="schedule_timezone" value="<?= e($settings['schedule_timezone'] ?? 'EST') ?>" placeholder="EST"></div>
          <div><label>Schedule Intro</label><input type="text" name="schedule_intro" value="<?= e($settings['schedule_intro'] ?? '') ?>"></div>
        </div>
        <div id="scheduleManager" class="schedule-manager">
          <?php foreach ($eventSchedule as $i => $slot): ?>
            <div class="schedule-row">
              <div class="schedule-top">
                <h3>Schedule Slot <?= $i + 1 ?></h3>
                <div class="schedule-actions">
                  <label class="schedule-enable"><input type="checkbox" name="event_schedule[<?= $i ?>][enabled]" <?= !empty($slot['enabled']) ? 'checked' : '' ?> data-schedule-field="enabled"> Enabled</label>
                  <button type="button" class="remove" onclick="removeScheduleRow(this)">Remove</button>
                </div>
              </div>
              <div class="schedule-grid">
                <div><label>Day Key</label><input type="date" name="event_schedule[<?= $i ?>][day_key]" value="<?= e($slot['day_key'] ?? '') ?>" data-schedule-field="day_key"></div>
                <div><label>Day Label</label><input type="text" name="event_schedule[<?= $i ?>][day_label]" value="<?= e($slot['day_label'] ?? '') ?>" placeholder="Fri 3 Apr 2026" data-schedule-field="day_label"></div>
                <div><label>Start</label><input type="text" name="event_schedule[<?= $i ?>][start]" value="<?= e($slot['start'] ?? '') ?>" placeholder="00:00" data-schedule-field="start"></div>
                <div><label>End</label><input type="text" name="event_schedule[<?= $i ?>][end]" value="<?= e($slot['end'] ?? '') ?>" placeholder="24:00" data-schedule-field="end"></div>
                <div><label>Slot Title / DJ</label><input type="text" name="event_schedule[<?= $i ?>][title]" value="<?= e($slot['title'] ?? '') ?>" placeholder="DJ name or Available Slot" data-schedule-field="title"></div>
                <div><label>Station / Source</label><input type="text" name="event_schedule[<?= $i ?>][station]" value="<?= e($slot['station'] ?? '') ?>" placeholder="Station name" data-schedule-field="station"></div>
                <div class="full"><label>Note</label><input type="text" name="event_schedule[<?= $i ?>][note]" value="<?= e($slot['note'] ?? '') ?>" placeholder="Live block / replay / open slot" data-schedule-field="note"></div>
              </div>
            </div>
          <?php endforeach; ?>
        </div>
        <div style="display:flex;gap:10px;flex-wrap:wrap;margin-top:14px"><button type="button" class="secondary" onclick="addScheduleRow()">+ Add Schedule Slot</button></div>

        <h2 style="margin-top:26px">Winners panel</h2>
        <p class="small">Add one or many winners for the winners-announced mode. You can also mark winners from the submission manager and copy them here.</p>
        <div id="winnerManager" class="winner-manager">
          <?php foreach ($winners as $i => $winner): ?>
            <div class="winner-row">
              <div class="winner-top">
                <h3>Winner <?= $i + 1 ?></h3>
                <div class="winner-actions"><button type="button" class="remove" onclick="removeWinnerRow(this)">Remove</button></div>
              </div>
              <div class="winner-grid">
                <div><label>Winner Name</label><input type="text" name="winners[<?= $i ?>][name]" value="<?= e($winner['name'] ?? '') ?>"></div>
                <div><label>Winning Station / Source</label><input type="text" name="winners[<?= $i ?>][station]" value="<?= e($winner['station'] ?? '') ?>"></div>
                <div class="full"><label>Details / Answer / Rank</label><input type="text" name="winners[<?= $i ?>][details]" value="<?= e($winner['details'] ?? '') ?>"></div>
                <div class="full"><label>Prize</label><input type="text" name="winners[<?= $i ?>][prize]" value="<?= e($winner['prize'] ?? '') ?>"></div>
              </div>
            </div>
          <?php endforeach; ?>
        </div>
        <div style="display:flex;gap:10px;flex-wrap:wrap;margin-top:14px"><button type="button" class="secondary" onclick="addWinnerRow()">+ Add Winner</button></div>

        <h2 style="margin-top:26px">Submission form</h2>
        <div class="row">
          <div><label>Submission Page Title</label><input type="text" name="submission_title" value="<?= e($settings['submission_title'] ?? '') ?>"></div>
          <div><label>Success Message</label><input type="text" name="success_message" value="<?= e($settings['success_message'] ?? '') ?>"></div>
        </div>
        <label>Submission Intro</label><textarea name="submission_intro"><?= e($settings['submission_intro'] ?? '') ?></textarea>

        <h3 style="margin-top:22px">Field toggles</h3>
        <div class="toggle-grid">
          <?php
            $defs = [
              ['label' => 'Entry type dropdown', 'show' => 'show_entry_type', 'require' => 'require_entry_type'],
              ['label' => 'Field one', 'show' => 'show_field_one', 'require' => 'require_field_one'],
              ['label' => 'Field two', 'show' => 'show_field_two', 'require' => 'require_field_two'],
              ['label' => 'Field three', 'show' => 'show_field_three', 'require' => 'require_field_three'],
              ['label' => 'Message / notes', 'show' => 'show_message_field', 'require' => 'require_message_field'],
              ['label' => 'Name', 'show' => 'show_name_field', 'require' => 'require_name_field'],
              ['label' => 'Email', 'show' => 'show_email_field', 'require' => 'require_email_field'],
              ['label' => 'Platform source', 'show' => 'show_platform_field', 'require' => 'require_platform_field']
            ];
            foreach ($defs as $def):
          ?>
            <div class="toggle-row">
              <div class="toggle-title"><?= e($def['label']) ?></div>
              <label><input type="checkbox" name="<?= e($def['show']) ?>" <?= !empty($settings[$def['show']]) ? 'checked' : '' ?>> Show</label>
              <label><input type="checkbox" name="<?= e($def['require']) ?>" <?= !empty($settings[$def['require']]) ? 'checked' : '' ?>> Required</label>
            </div>
          <?php endforeach; ?>
        </div>

        <div class="row3">
          <div><label>Entry Type Label</label><input type="text" name="entry_type_label" value="<?= e($settings['entry_type_label'] ?? '') ?>"></div>
          <div><label>Name Label</label><input type="text" name="name_label" value="<?= e($settings['name_label'] ?? '') ?>"></div>
          <div><label>Email Label</label><input type="text" name="email_label" value="<?= e($settings['email_label'] ?? '') ?>"></div>
        </div>
        <div class="row"><div><label>Field One Label</label><input type="text" name="field_one_label" value="<?= e($settings['field_one_label'] ?? '') ?>"></div><div><label>Field One Placeholder</label><input type="text" name="field_one_placeholder" value="<?= e($settings['field_one_placeholder'] ?? '') ?>"></div></div>
        <div class="row"><div><label>Field Two Label</label><input type="text" name="field_two_label" value="<?= e($settings['field_two_label'] ?? '') ?>"></div><div><label>Field Two Placeholder</label><input type="text" name="field_two_placeholder" value="<?= e($settings['field_two_placeholder'] ?? '') ?>"></div></div>
        <div class="row"><div><label>Field Three Label</label><input type="text" name="field_three_label" value="<?= e($settings['field_three_label'] ?? '') ?>"></div><div><label>Field Three Placeholder</label><input type="text" name="field_three_placeholder" value="<?= e($settings['field_three_placeholder'] ?? '') ?>"></div></div>
        <div class="row"><div><label>Message Label</label><input type="text" name="field_message_label" value="<?= e($settings['field_message_label'] ?? '') ?>"></div><div><label>Message Placeholder</label><input type="text" name="field_message_placeholder" value="<?= e($settings['field_message_placeholder'] ?? '') ?>"></div></div>
        <div class="row"><div><label>Platform Label</label><input type="text" name="platform_label" value="<?= e($settings['platform_label'] ?? '') ?>"></div><div><label>Entry Type Options</label><textarea name="entry_type_options"><?= e(implode("\n", $settings['entry_type_options'] ?? [])) ?></textarea></div></div>
        <label>Platform Options</label><textarea name="platforms"><?= e(implode("\n", $settings['platforms'] ?? [])) ?></textarea>

        <div style="display:flex;gap:10px;flex-wrap:wrap;margin-top:18px">
          <button type="submit" name="save_settings">Save Settings</button>
          <a class="button secondary" href="<?= e(site_url('index.php')) ?>">Preview Site</a>
        </div>
      </form>
    </div>

    <div class="panel">
      <h2>Submission manager</h2>
      <p>Search and filter entries, mark one or many winners, export CSV, or clear the list when an event ends.</p>

      <div style="display:flex;gap:10px;flex-wrap:wrap;margin-bottom:16px">
        <a class="button secondary" href="<?= e(site_url('admin.php?export=csv')) ?>">Export CSV</a>
        <form method="post" onsubmit="return confirm('Close submissions now?');"><button type="submit" name="quick_close" class="secondary">Close Submissions Now</button></form>
        <form method="post"><button type="submit" name="add_marked_winners_to_page" class="secondary">Copy Marked Winners To Panel</button></form>
        <form method="post" onsubmit="return confirm('Clear all submissions?');"><button type="submit" name="clear_submissions" class="secondary">Clear All</button></form>
      </div>

      <form method="get" class="filters">
        <div><label>Search</label><input type="text" name="q" value="<?= e($filters['q']) ?>" placeholder="name, email, answer, platform"></div>
        <div><label>Entry Type</label><select name="entry_type"><option value="">All</option><?php foreach ($entryTypes as $opt): ?><option value="<?= e($opt) ?>" <?= $filters['entry_type'] === $opt ? 'selected' : '' ?>><?= e($opt) ?></option><?php endforeach; ?></select></div>
        <div><label>Platform</label><select name="platform"><option value="">All</option><?php foreach ($platformsSeen as $opt): ?><option value="<?= e($opt) ?>" <?= $filters['platform'] === $opt ? 'selected' : '' ?>><?= e($opt) ?></option><?php endforeach; ?></select></div>
        <div style="display:flex;gap:10px;align-items:end"><button type="submit">Filter</button><a class="button secondary" href="<?= e(site_url('admin.php')) ?>">Reset</a></div>
      </form>

      <div class="table-wrap">
        <table>
          <thead><tr><th>Winner</th><th>Rank</th><th>Entry Type</th><th>Field One</th><th>Field Two</th><th>Field Three</th><th>Message</th><th>Name</th><th>Email</th><th>Platform</th><th>Timestamp</th><th></th></tr></thead>
          <tbody>
          <?php if (!$filteredSubmissions): ?>
            <tr><td colspan="12">No submissions found.</td></tr>
          <?php else: ?>
            <?php foreach ($filteredSubmissions as $filteredRow): ?>
              <?php
                $actualIndex = null;
                foreach ($submissions as $idx => $candidate) { if ($candidate === $filteredRow) { $actualIndex = $idx; break; } }
                if ($actualIndex === null) continue;
                $row = $submissions[$actualIndex];
              ?>
              <tr>
                <td><?= !empty($row['is_winner']) ? 'Yes' : 'No' ?></td>
                <td>
                  <form method="post" style="display:flex;gap:8px;align-items:center;flex-wrap:wrap">
                    <input class="rank-input" type="text" name="winner_rank[<?= (int)$actualIndex ?>]" value="<?= e($row['winner_rank'] ?? '') ?>" placeholder="Winner / 1st / 2nd / 3rd">
                    <?php if (!empty($row['is_winner'])): ?>
                      <button type="submit" name="unmark_winner" value="<?= (int)$actualIndex ?>" class="secondary">Unmark</button>
                    <?php else: ?>
                      <button type="submit" name="mark_winner" value="<?= (int)$actualIndex ?>" class="secondary">Mark</button>
                    <?php endif; ?>
                  </form>
                </td>
                <td><?= e($row['entry_type'] ?? '') ?></td>
                <td><?= e($row['field_one'] ?? '') ?></td>
                <td><?= e($row['field_two'] ?? '') ?></td>
                <td><?= e($row['field_three'] ?? '') ?></td>
                <td><?= e($row['message_text'] ?? '') ?></td>
                <td><?= e($row['name'] ?? '') ?></td>
                <td><?= e($row['email'] ?? '') ?></td>
                <td><?= e($row['platform'] ?? '') ?></td>
                <td><?= e($row['timestamp'] ?? '') ?></td>
                <td>
                  <form method="post" onsubmit="return confirm('Delete this submission?');">
                    <button type="submit" name="delete_submission" value="<?= (int)$actualIndex ?>" class="secondary">Delete</button>
                  </form>
                </td>
              </tr>
            <?php endforeach; ?>
          <?php endif; ?>
          </tbody>
        </table>
      </div>
    </div>
  </div>
</div>

<template id="stationRowTemplate">
  <div class="station-row">
    <div class="station-top">
      <label class="station-enable"><input type="checkbox" data-field="enabled" checked> Enabled for this event</label>
      <div class="station-actions"><button type="button" class="remove" onclick="removeStationRow(this)">Remove</button></div>
    </div>
    <div class="station-grid">
      <div><label>Station Name</label><input type="text" data-field="name"></div>
      <div><label>Logo Path / URL</label><input type="text" data-field="logo" placeholder="assets/stations/my-station.png"></div>
      <div><label>Website Link</label><input type="text" data-field="website" placeholder="https://example.com/"></div>
      <div><label>Listen Link</label><input type="text" data-field="stream" placeholder="http://stream.example.com/live"></div>
      <div class="full"><label>Station Note</label><input type="text" data-field="note" placeholder="Clues every hour / supporting the hunt / weekend support"></div>
    </div>
  </div>
</template>

<template id="winnerRowTemplate">
  <div class="winner-row">
    <div class="winner-top"><h3>Winner</h3><div class="winner-actions"><button type="button" class="remove" onclick="removeWinnerRow(this)">Remove</button></div></div>
    <div class="winner-grid">
      <div><label>Winner Name</label><input type="text" data-winner-field="name"></div>
      <div><label>Winning Station / Source</label><input type="text" data-winner-field="station"></div>
      <div class="full"><label>Details / Answer / Rank</label><input type="text" data-winner-field="details"></div>
      <div class="full"><label>Prize</label><input type="text" data-winner-field="prize"></div>
    </div>
  </div>
</template>

<template id="scheduleRowTemplate">
  <div class="schedule-row">
    <div class="schedule-top">
      <h3>Schedule Slot</h3>
      <div class="schedule-actions">
        <label class="schedule-enable"><input type="checkbox" data-schedule-field="enabled" checked> Enabled</label>
        <button type="button" class="remove" onclick="removeScheduleRow(this)">Remove</button>
      </div>
    </div>
    <div class="schedule-grid">
      <div><label>Day Key</label><input type="date" data-schedule-field="day_key"></div>
      <div><label>Day Label</label><input type="text" data-schedule-field="day_label" placeholder="Fri 3 Apr 2026"></div>
      <div><label>Start</label><input type="text" data-schedule-field="start" placeholder="00:00"></div>
      <div><label>End</label><input type="text" data-schedule-field="end" placeholder="24:00"></div>
      <div><label>Slot Title / DJ</label><input type="text" data-schedule-field="title" placeholder="DJ name or Available Slot"></div>
      <div><label>Station / Source</label><input type="text" data-schedule-field="station" placeholder="Station name"></div>
      <div class="full"><label>Note</label><input type="text" data-schedule-field="note" placeholder="Live block / replay / open slot"></div>
    </div>
  </div>
</template>

<script>
function syncStationIndexes() {
  document.querySelectorAll('#stationManager .station-row').forEach((row, index) => {
    row.querySelectorAll('[data-field]').forEach((field) => {
      const key = field.getAttribute('data-field');
      field.name = `stations[${index}][${key}]`;
    });
    row.querySelectorAll('input[name^="stations["]').forEach((field) => {
      const match = field.name.match(/stations\[\d+\]\[(.+)\]/);
      if (match) field.name = `stations[${index}][${match[1]}]`;
    });
  });
}
function addStationRow(){document.getElementById('stationManager').appendChild(document.getElementById('stationRowTemplate').content.cloneNode(true));syncStationIndexes();}
function removeStationRow(button){const row=button.closest('.station-row'); if(row){row.remove();syncStationIndexes();}}

function syncWinnerIndexes() {
  document.querySelectorAll('#winnerManager .winner-row').forEach((row, index) => {
    row.querySelectorAll('[data-winner-field]').forEach((field) => {
      const key = field.getAttribute('data-winner-field');
      field.name = `winners[${index}][${key}]`;
    });
    const h3 = row.querySelector('h3'); if (h3) h3.textContent = `Winner ${index + 1}`;
  });
}
function addWinnerRow(){document.getElementById('winnerManager').appendChild(document.getElementById('winnerRowTemplate').content.cloneNode(true));syncWinnerIndexes();}
function removeWinnerRow(button){const row=button.closest('.winner-row'); if(row){row.remove();syncWinnerIndexes();}}

function syncScheduleIndexes() {
  document.querySelectorAll('#scheduleManager .schedule-row').forEach((row, index) => {
    row.querySelectorAll('[data-schedule-field]').forEach((field) => {
      const key = field.getAttribute('data-schedule-field');
      field.name = `event_schedule[${index}][${key}]`;
    });
    const h3 = row.querySelector('h3'); if (h3) h3.textContent = `Schedule Slot ${index + 1}`;
  });
}
function addScheduleRow(){document.getElementById('scheduleManager').appendChild(document.getElementById('scheduleRowTemplate').content.cloneNode(true));syncScheduleIndexes();}
function removeScheduleRow(button){const row=button.closest('.schedule-row'); if(row){row.remove();syncScheduleIndexes();}}
document.addEventListener('DOMContentLoaded', function(){syncStationIndexes();syncWinnerIndexes();syncScheduleIndexes();});
</script>
</body>
</html>
