<?php
/**
 * Configuração central do aplicativo StreamBox.
 * Mantém versões de logo, fundo, cores e URL upstream da API de jogos.
 */

define('STREAMBOX_CONFIG_FILE', __DIR__ . '/../app_config.json');

function streambox_config_defaults(): array {
    $root = dirname(__DIR__);
    return [
        'version' => 1,
        'logo_version' => is_file($root . '/img/logo.png') ? (int)filemtime($root . '/img/logo.png') : 1,
        'background_version' => is_file($root . '/img/bg.png') ? (int)filemtime($root . '/img/bg.png') : 1,
        'colors_version' => is_file($root . '/cores.json') ? (int)filemtime($root . '/cores.json') : 1,
        'games_api_url' => 'https://xsender.painelmaster.lol/retornojogosmx.json',
        'updated_at' => gmdate('c'),
    ];
}

function streambox_config_read(): array {
    $defaults = streambox_config_defaults();
    if (!is_file(STREAMBOX_CONFIG_FILE)) {
        streambox_config_write($defaults);
        return $defaults;
    }
    $raw = @file_get_contents(STREAMBOX_CONFIG_FILE);
    $data = json_decode((string)$raw, true);
    if (!is_array($data)) {
        return $defaults;
    }
    return array_merge($defaults, $data);
}

function streambox_config_write(array $config): bool {
    $config['updated_at'] = gmdate('c');
    $json = json_encode($config, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
    if ($json === false) return false;
    $tmp = STREAMBOX_CONFIG_FILE . '.tmp';
    if (@file_put_contents($tmp, $json . PHP_EOL, LOCK_EX) === false) return false;
    return @rename($tmp, STREAMBOX_CONFIG_FILE);
}

function streambox_config_update(array $changes, ?string $bump = null): array {
    $config = streambox_config_read();
    foreach ($changes as $key => $value) {
        $config[$key] = $value;
    }
    $config['version'] = max(1, (int)($config['version'] ?? 1)) + 1;
    if ($bump === 'logo') $config['logo_version'] = time();
    if ($bump === 'background') $config['background_version'] = time();
    if ($bump === 'colors') $config['colors_version'] = time();
    streambox_config_write($config);
    return $config;
}

function streambox_no_cache_headers(): void {
    header('Cache-Control: no-store, no-cache, must-revalidate, max-age=0');
    header('Pragma: no-cache');
    header('Expires: 0');
}
