<?php
/**
 * Führt alle *.sql aus database/update aus. Erwartet $pdo im Scope.
 * Optional: $databaseUpdateDir setzen (z.B. vom Update-Prozess), dann wird nur dieses Verzeichnis verwendet.
 * Rückgabe: ['executed' => int, 'errors' => string[]]
 */
$updateDir = null;
if (!empty($databaseUpdateDir) && is_dir($databaseUpdateDir)) {
    $updateDir = $databaseUpdateDir;
} else {
    foreach ([__DIR__ . '/database/update', __DIR__ . '/../database/update'] as $dir) {
        if (is_dir($dir)) {
            $updateDir = $dir;
            break;
        }
    }
}
$executed = 0;
$errors = [];
if ($updateDir !== null) {
    $files = glob($updateDir . '/*.sql');
    if ($files !== false && !empty($files)) {
        sort($files);
        foreach ($files as $file) {
            $sql = @file_get_contents($file);
            if ($sql === false || $sql === '') continue;
            $statements = array_filter(
                array_map('trim', explode(';', $sql)),
                function ($s) {
                    $s = trim($s);
                    return $s !== '';
                }
            );
            foreach ($statements as $stmt) {
                $stmt = preg_replace('/^\s*--[^\n]*\n/m', '', $stmt);
                $stmt = trim($stmt);
                if ($stmt === '' || preg_match('/^\s*--/', $stmt)) continue;
                try {
                    $pdo->exec($stmt);
                    $executed++;
                } catch (Throwable $e) {
                    $errors[] = basename($file) . ': ' . $e->getMessage();
                }
            }
        }
    }
}
return ['executed' => $executed, 'errors' => $errors];
