<?php
ini_set('display_errors', '1');
error_reporting(E_ALL);

echo "<pre>\n";

try {
    echo "1. Lade config...\n";
    $c = require __DIR__ . '/lib/config.php';
    echo "   driver={$c['db_driver']} dsn={$c['db_dsn']}\n";

    echo "2. Verbinde Datenbank...\n";
    require_once __DIR__ . '/lib/db.php';
    $pdo = db();
    echo "   Verbindung OK\n";

    echo "3. Zaehle User...\n";
    $count = (int) $pdo->query('SELECT COUNT(*) FROM users')->fetchColumn();
    echo "   $count User gefunden\n";

    if ($count === 0) {
        echo "4. Erstelle Admin-User...\n";
        $hash = password_hash('adminadmin', PASSWORD_BCRYPT, ['cost' => 12]);
        $stmt = $pdo->prepare(
            'INSERT INTO users (username, name, role, password_hash, active, created_at)
             VALUES (?, ?, ?, ?, 1, ?)'
        );
        $stmt->execute(['admin', 'Administrator', 'admin', $hash, date('c')]);
        echo "   Admin erstellt: username=admin password=adminadmin\n";
    } else {
        echo "4. DB hat bereits User — kein Admin eingefuegt.\n";
    }

    echo "\nSetup erfolgreich abgeschlossen.\n";
} catch (Throwable $e) {
    echo "\nFEHLER: " . $e->getMessage() . "\n";
    echo "Datei: " . $e->getFile() . " Zeile " . $e->getLine() . "\n";
    echo "\nStack trace:\n" . $e->getTraceAsString() . "\n";
}

echo "</pre>\n";
