<?php
declare(strict_types=1);

/**
 * Öffentliches Gate: Coming Soon vs. Live.
 * Admin (/admin) und API (/api) sowie statische Assets werden per .htaccess ausgenommen.
 */

function slbs_site_mode(): string
{
    // 1) DB (sofort nach Admin-Umschalter aktuell)
    $configFile = __DIR__ . '/admin/config.php';
    if (!is_file($configFile)) {
        $configFile = __DIR__ . '/admin/config.example.php';
    }
    if (is_file($configFile)) {
        try {
            /** @var array $cfg */
            $cfg = require $configFile;
            $host = (string) ($cfg['db_host'] ?? 'localhost');
            $name = (string) ($cfg['db_name'] ?? '');
            $user = (string) ($cfg['db_user'] ?? '');
            $pass = (string) ($cfg['db_pass'] ?? '');
            $charset = (string) ($cfg['db_charset'] ?? 'utf8mb4');
            if ($name !== '') {
                $pdo = new PDO(
                    "mysql:host={$host};dbname={$name};charset={$charset}",
                    $user,
                    $pass,
                    [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
                );
                $stmt = $pdo->prepare('SELECT setting_value FROM cms_settings WHERE setting_key = ? LIMIT 1');
                $stmt->execute(['site.mode']);
                $row = $stmt->fetch(PDO::FETCH_ASSOC);
                $val = is_array($row) ? (string) ($row['setting_value'] ?? '') : '';
                if ($val === 'live' || $val === 'coming_soon') {
                    return $val;
                }
            }
        } catch (Throwable $e) {
            // Datei-Fallback
        }
    }

    // 2) Neueste Modus-Datei
    $candidates = [
        __DIR__ . '/api/cms/site-mode.json',
        rtrim(sys_get_temp_dir(), '/\\') . '/slbs-site-mode.json',
    ];
    $bestFile = null;
    $bestMtime = -1;
    foreach ($candidates as $file) {
        if (!is_readable($file)) {
            continue;
        }
        $mtime = (int) (@filemtime($file) ?: 0);
        if ($mtime >= $bestMtime) {
            $bestMtime = $mtime;
            $bestFile = $file;
        }
    }
    if ($bestFile !== null) {
        $data = json_decode((string) file_get_contents($bestFile), true);
        if (is_array($data) && ($data['mode'] ?? '') === 'live') {
            return 'live';
        }
        if (is_array($data) && ($data['mode'] ?? '') === 'coming_soon') {
            return 'coming_soon';
        }
    }
    return 'coming_soon';
}

function slbs_public_base(): string
{
    $script = str_replace('\\', '/', (string) ($_SERVER['SCRIPT_NAME'] ?? '/site-gate.php'));
    $base = dirname($script);
    if ($base === '/' || $base === '\\' || $base === '.') {
        return '';
    }
    return rtrim($base, '/');
}

function slbs_request_relative(string $base): string
{
    $path = parse_url((string) ($_SERVER['REQUEST_URI'] ?? '/'), PHP_URL_PATH);
    $path = is_string($path) && $path !== '' ? $path : '/';
    if ($base !== '' && str_starts_with($path, $base)) {
        $path = substr($path, strlen($base)) ?: '/';
    }
    if ($path === '' || $path[0] !== '/') {
        $path = '/' . $path;
    }
    return $path;
}

function slbs_serve_html(string $absoluteFile, bool $noIndex = false): void
{
    header('Content-Type: text/html; charset=utf-8');
    header('Cache-Control: no-store, no-cache, must-revalidate');
    if ($noIndex) {
        header('X-Robots-Tag: noindex, nofollow');
    }
    readfile($absoluteFile);
    exit;
}

$mode = slbs_site_mode();
$base = slbs_public_base();
$relative = slbs_request_relative($base);
$isComingSoonPath = str_starts_with($relative, '/coming-soon');

if ($mode === 'coming_soon') {
    $comingSoonIndex = __DIR__ . '/coming-soon/page.html';
    if (!is_file($comingSoonIndex)) {
        // Fallback für ältere Deployments
        $comingSoonIndex = __DIR__ . '/coming-soon/index.html';
    }
    if ($isComingSoonPath) {
        if (is_file($comingSoonIndex)) {
            slbs_serve_html($comingSoonIndex, true);
        }
        http_response_code(503);
        header('Content-Type: text/plain; charset=utf-8');
        echo 'Coming-Soon-Seite fehlt.';
        exit;
    }
    // Explizit index.php – sonst bleibt man ggf. an statischem HTML hängen
    header('Location: ' . $base . '/coming-soon/index.php', true, 302);
    exit;
}

// Live: Coming-Soon-Pfade auf die Startseite lenken
if ($isComingSoonPath) {
    header('Location: ' . ($base !== '' ? $base . '/' : '/'), true, 302);
    exit;
}

// Live: passende statische HTML-Datei ausliefern
// Direktaufruf von index.php / site-gate.php ist dieselbe Startseite wie /
if ($relative === '/' || $relative === '' || $relative === '/index.php' || $relative === '/site-gate.php') {
    $home = __DIR__ . '/_live-index.html';
    if (!is_file($home)) {
        $home = __DIR__ . '/index.html';
    }
    if (is_file($home)) {
        slbs_serve_html($home);
    }
}

$file = __DIR__ . $relative;
if (str_ends_with($relative, '/')) {
    $file = __DIR__ . $relative . 'index.html';
} elseif (is_dir($file)) {
    $file = rtrim($file, '/') . '/index.html';
} elseif (!is_file($file) && is_file($file . '/index.html')) {
    $file = $file . '/index.html';
}

if (is_file($file) && str_ends_with($file, '.html')) {
    slbs_serve_html($file);
}

$fallback = __DIR__ . '/404.html';
if (is_file($fallback)) {
    http_response_code(404);
    slbs_serve_html($fallback);
}

http_response_code(404);
header('Content-Type: text/plain; charset=utf-8');
echo 'Seite nicht gefunden.';
