<?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 event_schedule_days(): array {
    return [
        '2026-04-03' => 'Fri 3 Apr 2026',
        '2026-04-04' => 'Sat 4 Apr 2026',
        '2026-04-05' => 'Sun 5 Apr 2026',
        '2026-04-06' => 'Mon 6 Apr 2026',
    ];
}

function default_hourly_schedule(): array {
    $days = event_schedule_days();
    $schedule = [];
    foreach ($days as $dayKey => $dayLabel) {
        for ($hour = 0; $hour < 24; $hour++) {
            $timeLabel = sprintf('%02d:00 - %02d:00', $hour, ($hour + 1) % 24);
            if ($hour === 23) $timeLabel = '23:00 - 24:00';
            $schedule[$dayKey][sprintf('%02d', $hour)] = [
                'day_key' => $dayKey,
                'day_label' => $dayLabel,
                'hour' => sprintf('%02d', $hour),
                'time_label' => $timeLabel,
                'title' => '',
                'station' => '',
                'note' => '',
                'enabled' => true,
            ];
        }
    }

    $apply = function(string $dayKey, int $startHour, int $endHour, string $title, string $station = '', string $note = '') use (&$schedule): void {
        for ($hour = $startHour; $hour < $endHour; $hour++) {
            if (!isset($schedule[$dayKey][sprintf('%02d', $hour)])) continue;
            $schedule[$dayKey][sprintf('%02d', $hour)]['title'] = $title;
            $schedule[$dayKey][sprintf('%02d', $hour)]['station'] = $station;
            $schedule[$dayKey][sprintf('%02d', $hour)]['note'] = $note;
        }
    };

    $apply('2026-04-03', 11, 14, 'Junkyard Dawg', 'Thunder Mountain Radio', 'Live DJ');
    $apply('2026-04-03', 19, 22, 'DJ Moosehunter', 'Radio Galaxy FX / Almost Heaven Radio', 'Live DJ simulcast');

    $apply('2026-04-05', 18, 19, 'Make Believe Ballroom', 'Dan Pettengill / Home Time Radio', 'Special show');
    $apply('2026-04-05', 19, 21, 'Moments to Remember', 'Bob Moke / Home Time Radio', 'Special show');
    $apply('2026-04-05', 21, 22, 'Welcome to War Trace', 'Jerry Fox / Home Time Radio', 'Special show');
    $apply('2026-04-05', 22, 24, 'DJ-Musicman', 'Home Time Radio', 'Live DJ');

    $apply('2026-04-06', 8, 12, 'Jumpin Johnny B - Monday Morning Jumps', 'Radio Galaxy FX / Almost Heaven Radio', 'Live DJ simulcast');
    $apply('2026-04-06', 12, 14, 'Junkyard Dawg', 'Thunder Mountain Radio', 'Live DJ');

    return $schedule;
}

function normalize_hourly_schedule($schedule): array {
    $defaults = default_hourly_schedule();
    if (!is_array($schedule)) return $defaults;
    foreach ($defaults as $dayKey => $hours) {
        $incomingDay = $schedule[$dayKey] ?? [];
        if (!is_array($incomingDay)) $incomingDay = [];
        foreach ($hours as $hourKey => $slotDefaults) {
            $slot = $incomingDay[$hourKey] ?? [];
            if (!is_array($slot)) $slot = [];
            $defaults[$dayKey][$hourKey] = [
                'day_key' => $dayKey,
                'day_label' => trim((string)($slot['day_label'] ?? $slotDefaults['day_label'])),
                'hour' => sprintf('%02d', (int)$hourKey),
                'time_label' => $slotDefaults['time_label'],
                'title' => trim((string)($slot['title'] ?? '')),
                'station' => trim((string)($slot['station'] ?? '')),
                'note' => trim((string)($slot['note'] ?? '')),
                'enabled' => array_key_exists('enabled', $slot) ? !empty($slot['enabled']) : true,
            ];
        }
        ksort($defaults[$dayKey], SORT_NATURAL);
    }
    return $defaults;
}

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' => [],
        'featured_blocks' => [],
        'schedule_timezone' => 'EST',
        'schedule_title' => '4 Day Event Schedule',
        'schedule_intro' => 'Full 24 hour event schedule for the event in EST. Open hours can be filled from the admin side as more DJs are confirmed.',
        'hourly_schedule' => default_hourly_schedule()
    ];
}

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_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'] ?? []);
    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']);
    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;
}
?>