#!/usr/bin/env php
<?php
require __DIR__ . '/../bootstrap/autoload.php';

use App\Core\Database;

date_default_timezone_set(config('app.timezone', 'UTC'));

$pdo = Database::connection();
$config = config('database');
$migrationsTable = $config['migrations_table'];
$pdo->exec("CREATE TABLE IF NOT EXISTS {$migrationsTable} (id INT AUTO_INCREMENT PRIMARY KEY, migration VARCHAR(255) NOT NULL, ran_at DATETIME NOT NULL)");

$statement = $pdo->query("SELECT migration FROM {$migrationsTable}");
$ran = $statement ? $statement->fetchAll(PDO::FETCH_COLUMN) : [];

$files = glob(base_path('database/migrations/*.php'));
sort($files);

foreach ($files as $file) {
    $name = basename($file);
    if (in_array($name, $ran, true)) {
        continue;
    }

    $migration = require $file;
    if (!is_callable($migration)) {
        throw new RuntimeException("Migration {$name} must return a callable.");
    }

    $pdo->beginTransaction();
    try {
        $migration($pdo);
        $stmt = $pdo->prepare("INSERT INTO {$migrationsTable} (migration, ran_at) VALUES (:migration, :ran_at)");
        $stmt->execute(['migration' => $name, 'ran_at' => (new \DateTimeImmutable())->format('Y-m-d H:i:s')]);
        $pdo->commit();
        echo "Migrated: {$name}\n";
    } catch (\Throwable $e) {
        $pdo->rollBack();
        fwrite(STDERR, "Failed: {$name} - {$e->getMessage()}\n");
        exit(1);
    }
}
