<?php
declare(strict_types=1);

session_start();

define('DATA_DIR', __DIR__ . '/../data/');
define('DATA_PATH', DATA_DIR . 'questions.xlsx'); // or questions.csv
define('RESULTS_PATH', DATA_DIR . 'results.csv');
define('USERS_PATH', DATA_DIR . 'users.csv');
define('CONFIG_PATH', DATA_DIR . 'config.json');

$GLOBALS['REQUIRED_COLUMNS'] = [
    'id',
    'question',
    'option_a',
    'option_b',
    'option_c',
    'option_d'
]; // optional: correct, image_path

require_once __DIR__ . '/excel_reader.php';
require_once __DIR__ . '/auth.php';

function read_config(): array {
    if (!file_exists(CONFIG_PATH)) {
        return ['duration_minutes' => 15];
    }

    $json = file_get_contents(CONFIG_PATH);
    $cfg  = json_decode($json, true);

    if (!is_array($cfg)) {
        $cfg = ['duration_minutes' => 15];
    }

    return $cfg;
}

function write_config(array $cfg): bool {
    if (!file_exists(DATA_DIR)) {
        @mkdir(DATA_DIR, 0775, true);
    }

    return (bool)file_put_contents(CONFIG_PATH, json_encode($cfg, JSON_PRETTY_PRINT));
}

function flash_set($msg) {
    $_SESSION['flash'] = $msg;
}

function flash_get() {
    if (!empty($_SESSION['flash'])) {
        $m = $_SESSION['flash'];
        unset($_SESSION['flash']);
        return $m;
    }
    return null;
}
