<?php
// Basic site config
// 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', ''); // Optional: set if installed in a subfolder, e.g. /egg-hunt

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

function ensure_data_files(): void {
    if (!is_dir(DATA_DIR)) {
        mkdir(DATA_DIR, 0775, true);
    }

    if (!file_exists(SETTINGS_FILE)) {
        $defaults = [
            'event_name' => 'Egg Music Hunt',
            'headline' => 'Crack the Cryptic Clue & Win Cash!',
            'poster' => 'assets/poster.png',
            'pot' => 145,
            'date_range' => 'April 3rd – April 6th',
            'description' => 'Solve the cryptic music clue and submit your answer when the hunt opens.',
            'cta_text' => 'The Hunt Begins April 3rd!',
            'cta_url' => '',
            'stations' => [
                'Underground FX',
                'Hometime Radio',
                'Oldies & More Radio',
                'Thundermountain Radio',
                'Smurfettes Country Delights'
            ],
            'platforms' => ['Facebook', 'Discord', 'Filetopia', 'IMVU', 'Other'],
            'answer_page_open' => false,
            'form_title' => 'Submit Your Answer',
            'success_message' => 'Thanks. Your answer has been received.',
        ];
        file_put_contents(SETTINGS_FILE, json_encode($defaults, 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);
    return is_array($settings) ? $settings : [];
}

function save_settings(array $settings): void {
    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);
    return is_array($data) ? $data : [];
}

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

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