<?php
$dbUrl = getenv('DATABASE_URL');

if ($dbUrl) {
    $parsed = parse_url($dbUrl);
    $host = $parsed['host'] ?? 'localhost';
    $port = $parsed['port'] ?? 5432;
    $user = $parsed['user'] ?? '';
    $pass = $parsed['pass'] ?? '';
    $dbname = ltrim($parsed['path'] ?? '', '/');
} else {
    $configFile = __DIR__ . '/config.local.php';
    if (file_exists($configFile)) {
        $config = require $configFile;
        $host = $config['db_host'];
        $port = $config['db_port'];
        $dbname = $config['db_name'];
        $user = $config['db_user'];
        $pass = $config['db_pass'];
    } else {
        die("Database configuration not found. Create app/config/config.local.php with your credentials.");
    }
}

$dsn = "pgsql:host={$host};port={$port};dbname={$dbname}";

try {
    $db = new DB\SQL($dsn, $user, $pass);
    $f3->set('DB', $db);
} catch (PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}
