<?php
// BroadcastUrSelf master site + event template
// Change these before going live.

define('ADMIN_USER', 'admin');
define('ADMIN_PASS', 'change-this-password');
define('DATA_DIR', __DIR__ . '/data');
define('SETTINGS_FILE', DATA_DIR . '/settings.json');
define('SUBMISSIONS_FILE', DATA_DIR . '/submissions.json');
define('BASE_URL', ''); // e.g. /community if installed in a subfolder

function site_url(string $path = ''): string {
    $base = rtrim(BASE_URL, '/');
    $path = ltrim($path, '/');
    return $base . ($path ? '/' . $path : '');
}

function default_stations(): array {
    return [
        ['name' => 'Underground FX', 'website' => 'https://undergroundfxradio.com/', 'stream' => 'http://radio.undergroundfxradio.com:9000/stream', 'logo' => '', 'note' => '', 'enabled' => true],
        ['name' => 'Radio Galaxy FX', 'website' => 'https://www.radiogalaxyfx.com/', 'stream' => 'http://dj.radiogalaxyfx.com:8000/live', 'logo' => '', 'note' => '', 'enabled' => true],
        ['name' => 'Oldies And More', 'website' => 'https://oldiesandmore.org/', 'stream' => 'http://cr3.broadcasturself.com:23990/stream', 'logo' => '', 'note' => '', 'enabled' => true],
        ['name' => 'Almost Heaven Radio', 'website' => 'https://almostheavenradio.com/', 'stream' => 'http://cr3.broadcasturself.com:6969/stream', 'logo' => '', 'note' => '', 'enabled' => false],
        ['name' => 'Home Time Radio', 'website' => 'https://hometimeradio.com/', 'stream' => 'http://cr3.broadcasturself.com:65001/stream', 'logo' => '', 'note' => '', 'enabled' => true],
        ['name' => 'Thunder Mountain Radio', 'website' => 'https://thundermountainradio.org/', 'stream' => 'http://cr3.broadcasturself.com:6660/stream', 'logo' => '', 'note' => '', 'enabled' => true],
        ['name' => "Smurfette's Country Delights", 'website' => 'https://smurfettescountrydelights.com/', 'stream' => 'http://cr3.broadcasturself.com:1982/stream', 'logo' => '', 'note' => '', 'enabled' => true],
    ];
}


function default_event_schedule(): array {
    return [
        ['day_key' => '2026-04-03', 'day_label' => 'Fri 3 Apr 2026', 'start' => '00:00', 'end' => '11:00', 'title' => 'Available Slot', 'station' => '', 'note' => 'Open block - add a live DJ or special event segment.', 'enabled' => true],
        ['day_key' => '2026-04-03', 'day_label' => 'Fri 3 Apr 2026', 'start' => '11:00', 'end' => '14:00', 'title' => 'Junkyard Dawg', 'station' => 'Thunder Mountain Radio', 'note' => 'Live DJ block', 'enabled' => true],
        ['day_key' => '2026-04-03', 'day_label' => 'Fri 3 Apr 2026', 'start' => '14:00', 'end' => '19:00', 'title' => 'Available Slot', 'station' => '', 'note' => 'Open block - add a live DJ or special event segment.', 'enabled' => true],
        ['day_key' => '2026-04-03', 'day_label' => 'Fri 3 Apr 2026', 'start' => '19:00', 'end' => '22:00', 'title' => 'DJ Moosehunter', 'station' => 'Radio Galaxy FX / Almost Heaven Radio', 'note' => 'Shared live block', 'enabled' => true],
        ['day_key' => '2026-04-03', 'day_label' => 'Fri 3 Apr 2026', 'start' => '22:00', 'end' => '24:00', 'title' => 'Available Slot', 'station' => '', 'note' => 'Open block - add a live DJ or special event segment.', 'enabled' => true],

        ['day_key' => '2026-04-04', 'day_label' => 'Sat 4 Apr 2026', 'start' => '00:00', 'end' => '24:00', 'title' => 'Available Slot', 'station' => '', 'note' => 'Full day open for live event scheduling.', 'enabled' => true],

        ['day_key' => '2026-04-05', 'day_label' => 'Sun 5 Apr 2026', 'start' => '00:00', 'end' => '15:00', 'title' => 'Available Slot', 'station' => '', 'note' => 'Open block - add a live DJ or special event segment.', 'enabled' => true],
        ['day_key' => '2026-04-05', 'day_label' => 'Sun 5 Apr 2026', 'start' => '15:00', 'end' => '18:00', 'title' => 'Dj-Kathy Encore', 'station' => 'Home Time Radio', 'note' => 'Replay / featured show block', 'enabled' => true],
        ['day_key' => '2026-04-05', 'day_label' => 'Sun 5 Apr 2026', 'start' => '18:00', 'end' => '19:00', 'title' => 'Make Believe Ballroom', 'station' => 'Dan Pettengill', 'note' => 'Featured show', 'enabled' => true],
        ['day_key' => '2026-04-05', 'day_label' => 'Sun 5 Apr 2026', 'start' => '19:00', 'end' => '21:00', 'title' => 'Moments to Remember', 'station' => 'Bob Moke', 'note' => 'Featured show', 'enabled' => true],
        ['day_key' => '2026-04-05', 'day_label' => 'Sun 5 Apr 2026', 'start' => '21:00', 'end' => '22:00', 'title' => 'Welcome to War Trace', 'station' => 'Jerry Fox', 'note' => 'Featured show', 'enabled' => true],
        ['day_key' => '2026-04-05', 'day_label' => 'Sun 5 Apr 2026', 'start' => '22:00', 'end' => '24:00', 'title' => 'DJ-Musicman', 'station' => 'Home Time Radio', 'note' => 'Live DJ block', 'enabled' => true],

        ['day_key' => '2026-04-06', 'day_label' => 'Mon 6 Apr 2026', 'start' => '00:00', 'end' => '08:00', 'title' => 'Available Slot', 'station' => '', 'note' => 'Open block - add a live DJ or special event segment.', 'enabled' => true],
        ['day_key' => '2026-04-06', 'day_label' => 'Mon 6 Apr 2026', 'start' => '08:00', 'end' => '12:00', 'title' => 'Jumpin Johnny B - Monday Morning Jumps', 'station' => 'Radio Galaxy FX / Almost Heaven Radio', 'note' => 'Shared live block', 'enabled' => true],
        ['day_key' => '2026-04-06', 'day_label' => 'Mon 6 Apr 2026', 'start' => '12:00', 'end' => '14:00', 'title' => 'Junkyard Dawg', 'station' => 'Thunder Mountain Radio', 'note' => 'Live DJ block', 'enabled' => true],
        ['day_key' => '2026-04-06', 'day_label' => 'Mon 6 Apr 2026', 'start' => '14:00', 'end' => '24:00', 'title' => 'Available Slot', 'station' => '', 'note' => 'Open block - add a live DJ or special event segment.', 'enabled' => true],
    ];
}

function default_settings(): array {
    return [
        'site_name' => 'BroadcastUrSelf',
        'site_tagline' => 'Radio Hosting & Community Platform',
        'site_logo' => 'assets/site-logo.png',
        'site_intro' => 'A professional home base for your radio station community, featured events, seasonal promotions, contests, announcements, and network activity.',
        'community_blurb' => 'Use this as the main BroadcastUrSelf site, then swap the featured event section whenever you launch something new.',
        'footer_note' => 'Powered by BroadcastUrSelf radio hosting and community events.',
        'primary_button_label' => 'Event Link',
        'primary_button_url' => '',
        'secondary_button_label' => 'Open Submission Page',
        'station_heading' => 'Participating Network',

        'site_mode' => 'active_event', // active_event, coming_soon, live_now, winners_announced, no_event
        'event_preset' => 'custom', // clue_hunt, song_guess, giveaway, signup, announcement_only, first_entry, top_three, custom

        'event_active' => true,
        'event_type' => 'Featured Event',
        'event_name' => 'Featured Community Event',
        'headline' => 'Promote your next big event with a branded landing page.',
        'event_poster' => 'assets/default-event-poster.png',
        'pot_label' => 'Current Pot',
        'pot_value' => '145',
        'date_range' => 'April 3rd – April 6th',
        'description' => 'The event link is the main destination for the featured event. Participating stations and DJs can also run clue drops, promos, or supporting content across the network.',
        'how_it_works' => 'Use the button to direct listeners to the main event, stream, station page, external landing page, or sponsor page. You can keep submissions closed until the event begins.',
        'event_notice' => 'The event link can be added later if not ready yet.',
        'cta_text' => 'Now promoting across the community!',
        'status_text' => 'Submissions are currently closed.',

        'show_countdown' => false,
        'start_at' => '',
        'end_at' => '',
        'submissions_auto_schedule' => false,
        'submission_open_at' => '',
        'submission_close_at' => '',

        'announcement_enabled' => false,
        'announcement_text' => '',
        'announcement_link' => '',

        'no_event_title' => 'No featured event is live right now.',
        'no_event_text' => 'The BroadcastUrSelf community is still active across the network. Check back soon for the next event, competition, or special broadcast.',
        'coming_soon_title' => 'Something big is coming soon.',
        'coming_soon_text' => 'The next BroadcastUrSelf community event is being prepared right now. Watch this space for launch details.',
        'live_now_title' => 'The event is live now.',
        'live_now_text' => 'Tune in across the network and follow the action live as the community event unfolds.',
        'winners_title' => 'Winners Announced',
        'winners_text' => 'Thanks to everyone who took part. Here are the winning entries for this event.',

        'show_prize_box' => true,
        'show_submission_button' => true,
        'submission_button_text' => 'Open Submission Page',
        'submission_page_open' => false,
        'submission_title' => 'Submit Your Entry',
        'submission_intro' => 'Use this form for clue answers, contest entries, registration, nominations, or other community submissions.',
        'success_message' => 'Thanks. Your submission has been received.',

        'show_entry_type' => true,
        'require_entry_type' => false,
        'entry_type_label' => 'Entry Type',
        'entry_type_options' => ['Clue Answer', 'Competition Entry', 'General Submission', 'Request', 'Other'],

        'show_field_one' => true,
        'require_field_one' => true,
        'field_one_label' => 'Title / Artist / Main Answer',
        'field_one_placeholder' => 'Enter the main answer or subject',

        'show_field_two' => true,
        'require_field_two' => false,
        'field_two_label' => 'Song / Description / Extra Detail',
        'field_two_placeholder' => 'Enter supporting information',

        'show_field_three' => false,
        'require_field_three' => false,
        'field_three_label' => 'Third Answer / Extra Detail',
        'field_three_placeholder' => 'Enter a third answer or detail',

        'show_message_field' => true,
        'require_message_field' => false,
        'field_message_label' => 'Message / Notes',
        'field_message_placeholder' => 'Add any extra details here',

        'show_name_field' => true,
        'require_name_field' => false,
        'name_label' => 'Your Name',

        'show_email_field' => true,
        'require_email_field' => true,
        'email_label' => 'Email Address',

        'show_platform_field' => true,
        'require_platform_field' => true,
        'platform_label' => 'Where did you hear about this event?',
        'platforms' => ['Website', 'Discord', 'Facebook', 'On Air', 'Other'],

        'stations' => default_stations(),
        'winners' => [],
        'schedule_timezone' => 'EST',
        'schedule_title' => '4 Day Live Event Schedule',
        'schedule_intro' => 'Full 24 hour event schedule in EST. Open slots can be filled from admin as more DJs are confirmed.',
        'event_schedule' => default_event_schedule(),
        'featured_blocks' => []
    ];
}

function is_assoc_array(array $arr): bool {
    if ($arr === []) return false;
    return array_keys($arr) !== range(0, count($arr) - 1);
}

function merge_settings(array $defaults, array $settings): array {
    foreach ($defaults as $key => $value) {
        if (!array_key_exists($key, $settings)) {
            $settings[$key] = $value;
        } elseif (is_array($value) && is_array($settings[$key]) && is_assoc_array($value) && is_assoc_array($settings[$key])) {
            $settings[$key] = merge_settings($value, $settings[$key]);
        }
    }
    return $settings;
}

function normalize_stations($stations): array {
    $normalized = [];
    if (!is_array($stations)) return $normalized;

    foreach ($stations as $station) {
        if (is_string($station)) {
            $name = trim($station);
            if ($name !== '') {
                $normalized[] = ['name' => $name, 'website' => '', 'stream' => '', 'logo' => '', 'note' => '', 'enabled' => true];
            }
            continue;
        }
        if (!is_array($station)) continue;

        $name = trim((string)($station['name'] ?? ''));
        $website = trim((string)($station['website'] ?? ''));
        $stream = trim((string)($station['stream'] ?? ($station['url'] ?? '')));
        $logo = trim((string)($station['logo'] ?? ''));
        $note = trim((string)($station['note'] ?? ''));
        $enabled = !empty($station['enabled']);

        if ($name === '' && $website === '' && $stream === '' && $logo === '' && $note === '') continue;

        $normalized[] = ['name' => $name, 'website' => $website, 'stream' => $stream, 'logo' => $logo, 'note' => $note, 'enabled' => $enabled];
    }

    usort($normalized, function (array $a, array $b): int {
        return strnatcasecmp($a['name'] ?? '', $b['name'] ?? '');
    });
    return $normalized;
}

function normalize_event_schedule($rows): array {
    $normalized = [];
    if (!is_array($rows)) return $normalized;
    foreach ($rows as $row) {
        if (!is_array($row)) continue;
        $dayKey = trim((string)($row['day_key'] ?? ''));
        $dayLabel = 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 = !array_key_exists('enabled', $row) || !empty($row['enabled']);
        if ($dayKey === '' && $dayLabel === '' && $start === '' && $end === '' && $title === '' && $station === '' && $note === '') continue;
        if ($dayLabel === '' && $dayKey !== '') {
            $ts = strtotime($dayKey);
            if ($ts !== false) $dayLabel = date('D j M Y', $ts);
        }
        $normalized[] = ['day_key' => $dayKey, 'day_label' => $dayLabel, 'start' => $start, 'end' => $end, 'title' => $title, 'station' => $station, 'note' => $note, 'enabled' => $enabled];
    }
    usort($normalized, function (array $a, array $b): int {
        $ak = ($a['day_key'] ?? '') . ' ' . ($a['start'] ?? '');
        $bk = ($b['day_key'] ?? '') . ' ' . ($b['start'] ?? '');
        return strcmp($ak, $bk);
    });
    return $normalized;
}

function normalize_winners($winners): array {

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

function ensure_data_files(): void {
    if (!is_dir(DATA_DIR)) mkdir(DATA_DIR, 0775, true);
    if (!file_exists(SETTINGS_FILE)) file_put_contents(SETTINGS_FILE, json_encode(default_settings(), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
    if (!file_exists(SUBMISSIONS_FILE)) file_put_contents(SUBMISSIONS_FILE, json_encode([], JSON_PRETTY_PRINT));
}

function get_settings(): array {
    ensure_data_files();
    $settings = json_decode((string) file_get_contents(SETTINGS_FILE), true);
    $settings = is_array($settings) ? $settings : [];
    $settings = merge_settings(default_settings(), $settings);
    $settings['stations'] = normalize_stations($settings['stations'] ?? []);
    $settings['winners'] = normalize_winners($settings['winners'] ?? []);
    $settings['event_schedule'] = normalize_event_schedule($settings['event_schedule'] ?? []);
    return $settings;
}

function save_settings(array $settings): void {
    if (isset($settings['stations'])) $settings['stations'] = normalize_stations($settings['stations']);
    if (isset($settings['winners'])) $settings['winners'] = normalize_winners($settings['winners']);
    if (isset($settings['event_schedule'])) $settings['event_schedule'] = normalize_event_schedule($settings['event_schedule']);
    file_put_contents(SETTINGS_FILE, json_encode($settings, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
}

function get_submissions(): array {
    ensure_data_files();
    $data = json_decode((string) file_get_contents(SUBMISSIONS_FILE), true);
    $rows = is_array($data) ? $data : [];
    foreach ($rows as &$row) {
        if (!isset($row['is_winner'])) $row['is_winner'] = false;
        if (!isset($row['winner_rank'])) $row['winner_rank'] = '';
    }
    return $rows;
}

function save_submissions(array $submissions): void {
    file_put_contents(SUBMISSIONS_FILE, json_encode(array_values($submissions), JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES));
}

function e($value): string {
    return htmlspecialchars((string) $value, ENT_QUOTES, 'UTF-8');
}

function bool_setting(array $settings, string $key, bool $default = false): bool {
    return isset($settings[$key]) ? (bool) $settings[$key] : $default;
}

function now_ts(): int {
    return time();
}

function parse_datetime_value(string $value): ?int {
    $value = trim($value);
    if ($value === '') return null;
    $ts = strtotime($value);
    return $ts !== false ? $ts : null;
}

function computed_submission_open(array $settings): bool {
    if (!bool_setting($settings, 'submissions_auto_schedule')) {
        return bool_setting($settings, 'submission_page_open');
    }
    $now = now_ts();
    $openAt = parse_datetime_value((string)($settings['submission_open_at'] ?? ''));
    $closeAt = parse_datetime_value((string)($settings['submission_close_at'] ?? ''));
    if ($openAt !== null && $now < $openAt) return false;
    if ($closeAt !== null && $now > $closeAt) return false;
    return true;
}
?>