<?php
$file = __DIR__ . '/public/index.html';
if (!is_file($file)) {
    http_response_code(503);
    echo 'Vue app has not been built. Run npm install && npm run build.';
    exit;
}

require_once __DIR__ . '/config/db.php';

function app_site_title(): string
{
    $title = '六合彩资料';
    $db = @new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
    if ($db->connect_errno) {
        return $title;
    }
    $db->set_charset('utf8mb4');
    $stmt = $db->prepare("SELECT `value` FROM system_settings WHERE `key`='site_name' LIMIT 1");
    if ($stmt && $stmt->execute()) {
        $row = $stmt->get_result()->fetch_assoc();
        if (!empty($row['value'])) {
            $title = (string)$row['value'];
        }
    }
    if ($stmt) {
        $stmt->close();
    }
    $db->close();
    return $title;
}

$html = file_get_contents($file);
$title = htmlspecialchars(app_site_title(), ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
echo preg_replace('/<title>.*?<\/title>/is', '<title>' . $title . '</title>', $html, 1);
