<?php
declare(strict_types=1);

mysqli_report(MYSQLI_REPORT_OFF);

$host = getenv('SPBU_DB_HOST') ?: getenv('DB_HOST') ?: '127.0.0.1';
$username = getenv('SPBU_DB_USERNAME') ?: getenv('DB_USERNAME') ?: 'root';
$password = getenv('SPBU_DB_PASSWORD') ?: getenv('DB_PASSWORD') ?: '';
$database = getenv('SPBU_DB_DATABASE') ?: 'webgis_spbu';

try {
    $connection = new mysqli($host, $username, $password, $database);
} catch (Throwable $exception) {
    http_response_code(500);
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'message' => 'Koneksi database gagal. Pastikan MySQL XAMPP sedang berjalan.',
        'detail' => $exception->getMessage(),
    ]);
    exit;
}

if (!$connection || $connection->connect_errno) {
    http_response_code(500);
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'message' => 'Koneksi database gagal. Pastikan MySQL XAMPP sedang berjalan.',
    ]);
    exit;
}

$connection->set_charset('utf8mb4');
