<?php
// Canonical database connection for legacy and current application pages.
// The installer writes install_config.php with the dedicated account and port.

mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

if (isset($GLOBALS['conn']) && $GLOBALS['conn'] instanceof mysqli) {
    $conn = $GLOBALS['conn'];
    return;
}

require_once dirname(__DIR__) . '/admin/app_runtime.php';

$database = function_exists('ua_install_database_config')
    ? ua_install_database_config()
    : [];

$DB_HOST = trim((string)($database['host'] ?? ''));
$DB_USER = (string)($database['user'] ?? '');
$DB_PASS = (string)($database['pass'] ?? '');
$DB_NAME = trim((string)($database['name'] ?? ''));
$DB_PORT = (int)($database['port'] ?? 3306);
$DB_CHARSET = trim((string)($database['charset'] ?? 'utf8mb4'));

if ($DB_PORT <= 0) {
    $DB_PORT = 3306;
}
if ($DB_CHARSET === '') {
    $DB_CHARSET = 'utf8mb4';
}

// Branch and agent installations intentionally have no local database. Never
// fall back to root/3306 and accidentally expose stale local data.
if ($DB_HOST === '' || $DB_USER === '' || $DB_NAME === '') {
    throw new RuntimeException('No database is configured for this installation.');
}

try {
    $conn = mysqli_init();
    if (!$conn) {
        throw new RuntimeException('mysqli initialization failed.');
    }
    mysqli_options($conn, MYSQLI_OPT_CONNECT_TIMEOUT, 5);
    $conn->real_connect($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME, $DB_PORT);
    $conn->set_charset($DB_CHARSET);
    $GLOBALS['conn'] = $conn;
} catch (Throwable $error) {
    error_log(sprintf(
        '[NetworkCustomers] Legacy DB bootstrap failed host=%s port=%d database=%s user=%s error=%s',
        $DB_HOST,
        $DB_PORT,
        $DB_NAME,
        $DB_USER,
        $error->getMessage()
    ));
    throw $error;
}
