<?php
// includes/db.php

$host = 'localhost';
$user = 'root';      
$pass = '';         
$dbname = 'nfbettingsoftwarebd';

$conn = new mysqli($host, $user, $pass, $dbname);

if ($conn->connect_error) {
    error_log("Database connection failed: " . $conn->connect_error);
    http_response_code(503);
    die("Service temporarily unavailable.");
}

// Set Charset to handle special characters (e.g. Currency symbols)
$conn->set_charset("utf8mb4");

// Global red theme injector for every normal PHP page that loads the database.
// It only touches HTML buffers containing </head>, so API/redirect responses stay clean.
if (PHP_SAPI !== 'cli' && !defined('WCB_RED_THEME_INJECTOR_STARTED')) {
    define('WCB_RED_THEME_INJECTOR_STARTED', true);

    $wcbRootDir = str_replace('\\', '/', dirname(__DIR__));
    $wcbScriptDir = str_replace('\\', '/', dirname($_SERVER['SCRIPT_FILENAME'] ?? ''));
    $wcbDepth = 0;
    if ($wcbScriptDir !== '' && strpos($wcbScriptDir, $wcbRootDir) === 0) {
        $wcbRelativeDir = trim(substr($wcbScriptDir, strlen($wcbRootDir)), '/');
        $wcbDepth = $wcbRelativeDir === '' ? 0 : substr_count($wcbRelativeDir, '/') + 1;
    }
    $wcbAssetPrefix = str_repeat('../', $wcbDepth);
    $wcbRedGlobalHref = $wcbAssetPrefix . 'assets/css/red-global.css?v=20260813';
    $wcbAuthRedHref = $wcbAssetPrefix . 'assets/css/auth-red.css?v=20260813';
    $wcbScriptPath = str_replace('\\', '/', $_SERVER['SCRIPT_FILENAME'] ?? '');
    $wcbNeedsAuthRed = preg_match('~/player/(login|signup)\.php$~i', $wcbScriptPath) === 1;

    ob_start(function ($buffer) use ($wcbRedGlobalHref, $wcbAuthRedHref, $wcbNeedsAuthRed) {
        if (stripos($buffer, '</head>') === false) {
            return $buffer;
        }
        $links = '';
        if (stripos($buffer, 'red-global.css') === false) {
            $links .= '    <link rel="stylesheet" href="' . htmlspecialchars($wcbRedGlobalHref, ENT_QUOTES, 'UTF-8') . '">' . "\n";
        }
        if ($wcbNeedsAuthRed && stripos($buffer, 'auth-red.css') === false) {
            $links .= '    <link rel="stylesheet" href="' . htmlspecialchars($wcbAuthRedHref, ENT_QUOTES, 'UTF-8') . '">' . "\n";
        }
        if ($links === '') {
            return $buffer;
        }
        return preg_replace('/<\/head>/i', $links . '</head>', $buffer, 1);
    });
}

// Auto-fix 9Wicket local game icon if the SQL backup has an empty/placeholder image.
$nine_wicket_icon_patch = __DIR__ . '/game_api_9wicket_icon_patch.php';
if (file_exists($nine_wicket_icon_patch)) {
    require_once $nine_wicket_icon_patch;
    if (function_exists('apply_9wicket_icon_patch')) {
        @apply_9wicket_icon_patch($conn);
    }
}

// Enforce Maintenance Mode on all public/user-facing pages that load the database.
$maintenance_guard = __DIR__ . '/maintenance_guard.php';
if (!defined('GAME_API_SKIP_MAINTENANCE') && file_exists($maintenance_guard)) {
    require_once $maintenance_guard;
    maintenance_enforce($conn);
}
?>
