<?php
declare(strict_types=1);

function ccw_load_env_file(string $path): void
{
    static $loadedPaths = array();

    if (isset($loadedPaths[$path]) || !is_file($path) || !is_readable($path)) {
        return;
    }

    $loadedPaths[$path] = true;
    $lines = file($path, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);

    if (!is_array($lines)) {
        return;
    }

    foreach ($lines as $line) {
        $line = trim((string) $line);
        if ($line === '' || str_starts_with($line, '#') || !str_contains($line, '=')) {
            continue;
        }

        [$key, $value] = array_map('trim', explode('=', $line, 2));
        if ($key === '') {
            continue;
        }

        if (
            (str_starts_with($value, '"') && str_ends_with($value, '"'))
            || (str_starts_with($value, '\'') && str_ends_with($value, '\''))
        ) {
            $value = substr($value, 1, -1);
        }

        if (getenv($key) === false) {
            putenv($key . '=' . $value);
        }

        $_ENV[$key] = $value;
        $_SERVER[$key] = $value;
    }
}

function ccw_env_value(string $key, ?string $default = null): ?string
{
    $value = getenv($key);
    if (is_string($value) && trim($value) !== '') {
        return trim($value);
    }

    foreach (array($_ENV, $_SERVER) as $source) {
        if (isset($source[$key]) && trim((string) $source[$key]) !== '') {
            return trim((string) $source[$key]);
        }
    }

    return $default;
}

ccw_load_env_file(dirname(__DIR__) . '/.env');

$host = (string) ccw_env_value('CCW_DB_HOST', '127.0.0.1');
$user = (string) ccw_env_value('CCW_DB_USER', '');
$pass = (string) ccw_env_value('CCW_DB_PASS', '');
$db = (string) ccw_env_value('CCW_DB_NAME', 'CCW');
$portsRaw = (string) ccw_env_value('CCW_DB_PORTS', (string) ccw_env_value('CCW_DB_PORT', '3306'));
$ports = array_values(array_unique(array_filter(array_map(static function (string $value): int {
    return (int) trim($value);
}, explode(',', $portsRaw)), static function (int $port): bool {
    return $port > 0;
})));

if (empty($ports)) {
    $ports = array(3306);
}

if (!extension_loaded('mysqli')) {
    die('Connection failed: PHP mysqli extension is not enabled.');
}

if ($user === '' || $db === '') {
    die('Connection failed: database environment variables are not configured.');
}

mysqli_report(MYSQLI_REPORT_OFF);

$conn = null;
$errors = array();

foreach ($ports as $port) {
    $try = @new mysqli($host, $user, $pass, $db, $port);

    if (!$try->connect_error) {
        $conn = $try;
        break;
    }

    $message = $try->connect_error;

    if (stripos($message, 'Server sent charset unknown to the client') !== false) {
        $message = "This PHP / XAMPP build does not support the MySQL instance charset on port {$port}.";
    }

    $errors[] = "port {$port}: {$message}";
}

if (!$conn) {
    die('Connection failed: ' . implode(' | ', $errors));
}

$conn->set_charset('utf8mb4');

function db_prepare(mysqli $conn, string $sql): mysqli_stmt
{
    $stmt = $conn->prepare($sql);

    if (!$stmt) {
        throw new RuntimeException('Database prepare failed: ' . $conn->error);
    }

    return $stmt;
}
