<?php
// db.php – zentrale PDO-Verbindung

require_once __DIR__ . '/env.php';

loadEnv(__DIR__ . '/.env');

// =============================================================
// Installer-Guard
// Wenn die App noch nicht installiert ist, immer zuerst ins Setup.
// Ausnahme: wir sind bereits im /install/ Pfad.
// =============================================================
$installLock = __DIR__ . '/install/install.lock';
$scriptName  = (string)($_SERVER['SCRIPT_NAME'] ?? '');
if (!file_exists($installLock) && strpos($scriptName, '/install/') === false) {
    header('Location: install/index.php');
    exit;
}

$DB_HOST = env('DB_HOST', 'localhost');
$DB_PORT = env('DB_PORT', '');
$DB_NAME = env('DB_NAME', '');
$DB_USER = env('DB_USER', '');
$DB_PASS = env('DB_PASS', '');

$portPart = ($DB_PORT !== null && trim($DB_PORT) !== '') ? ';port=' . trim($DB_PORT) : '';
$dsn = "mysql:host={$DB_HOST}{$portPart};dbname={$DB_NAME};charset=utf8mb4";

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

try {
    $pdo = new PDO($dsn, $DB_USER, $DB_PASS, $options);
} catch (PDOException $e) {
    if (env('APP_DEBUG', '0') === '1') {
        die('DB-Fehler: ' . htmlspecialchars($e->getMessage()));
    }
    die('Datenbankfehler.');
}
