<?php
// Database configuration
define('DB_HOST', '127.0.0.1');
define('DB_PORT', '3306');
define('DB_NAME', 'app');
define('DB_USER', 'app');
define('DB_PASSWORD', 'app');

function db() {
    static $pdo;
    if ($pdo) {
        return $pdo;
    }
    $dsn = 'mysql:host=' . DB_HOST . ';port=' . DB_PORT . ';dbname=' . DB_NAME . ';charset=utf8mb4';
    $options = [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES   => false,
    ];
    try {
        $pdo = new PDO($dsn, DB_USER, DB_PASSWORD, $options);
        return $pdo;
    } catch (PDOException $e) {
        // In a real app, you would log this error and show a generic error page.
        // For development, it's okay to show the error.
        throw new PDOException($e->getMessage(), (int)$e->getCode());
    }
}

// Run migrations
try {
    $pdo = db();
    $migration_files = glob(__DIR__ . '/migrations/*.sql');
    foreach ($migration_files as $file) {
        $sql = file_get_contents($file);
        $pdo->exec($sql);
    }
} catch (PDOException $e) {
    // Handle migration errors
}