<?php
declare(strict_types=1);

header('Content-Type: application/json; charset=utf-8');
header('Cache-Control: no-store, max-age=0');

$contentFile = __DIR__ . '/launcher_content.json';

$content = [
    'server' => [
        'realm_name' => 'Vendelse Poort TBC Server',
        'version' => '2.4.3 Build 8606',
    ],
    'news' => [
        'title' => 'Willkommen auf Vendelse Poort TBC',
        'body' => 'Der Serverfeed ist erreichbar.',
        'url' => 'https://wowtbc.vendelsepoortdielen.de/news',
    ],
    'patch_notes' => [],
    'event' => [
        'title' => 'Nächstes Event',
        'date' => 'Wird bekanntgegeben',
        'time' => '',
        'text' => '',
        'url' => 'https://wowtbc.vendelsepoortdielen.de/events',
    ],
];

if (is_file($contentFile)) {
    $decoded = json_decode((string) file_get_contents($contentFile), true);
    if (is_array($decoded)) {
        $content = array_replace_recursive($content, $decoded);
    }
}

function port_open(string $host, int $port, float $timeout = 0.5): bool
{
    $errno = 0;
    $errstr = '';
    $socket = @fsockopen($host, $port, $errno, $errstr, $timeout);
    if (is_resource($socket)) {
        fclose($socket);
        return true;
    }
    return false;
}

$content['live'] = [
    'login_online' => port_open('127.0.0.1', 3724),
    'world_online' => port_open('127.0.0.1', 8085),
    'checked_at' => gmdate('c'),
];

echo json_encode(
    $content,
    JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES | JSON_PRETTY_PRINT
);
