<?php
declare(strict_types=1);

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

set_exception_handler(static function (Throwable $exception): void {
    if (!headers_sent()) {
        http_response_code(500);
        header('Content-Type: application/json');
    }

    echo json_encode([
        'success' => false,
        'message' => 'Terjadi kesalahan server.',
        'detail' => $exception->getMessage(),
    ]);
    exit;
});

$dsn = "mysql:host={$host};dbname={$database};charset={$charset}";

$options = [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES => false,
];

try {
    $pdo = new PDO($dsn, $username, $password, $options);
} catch (PDOException $exception) {
    http_response_code(500);
    header('Content-Type: application/json');
    echo json_encode([
        'success' => false,
        'message' => 'Koneksi database gagal: ' . $exception->getMessage(),
    ]);
    exit;
}
