<?php
/**
 * Führt alle *.sql aus database/update aus. Erwartet $pdo im Scope.
 * Rückgabe: ['executed' => int, 'errors' => string[]]
 */
$updateDir = null;
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 !== '' && strpos($s, '--') !== 0;
                }
            );
            foreach ($statements as $stmt) {
                if ($stmt === '') continue;
                try {
                    $pdo->exec($stmt);
                    $executed++;
                } catch (Throwable $e) {
                    $errors[] = basename($file) . ': ' . $e->getMessage();
                }
            }
        }
    }
}
return ['executed' => $executed, 'errors' => $errors];
