<?php

namespace App\Database;

use App\Core\Database;

/**
 * ITSWEBER CMS – Migration Runner
 *
 * Discovers and executes migration files in order.
 */
class Migrator
{
    private Database $db;
    private string $migrationsPath;

    public function __construct(Database $db, string $migrationsPath)
    {
        $this->db = $db;
        $this->migrationsPath = $migrationsPath;
    }

    /**
     * Run all migrations.
     */
    public function runAll(): array
    {
        $files = glob($this->migrationsPath . '/*.php');
        sort($files);

        $results = [];
        foreach ($files as $file) {
            $className = $this->getClassName($file);
            require_once $file;

            $fullClass = 'App\\Database\\Migrations\\' . $className;
            if (!class_exists($fullClass)) {
                // Try without namespace
                $fullClass = $className;
            }

            $migration = new $fullClass($this->db);
            $migration->up();
            $results[] = basename($file);
        }

        return $results;
    }

    /**
     * Extract class name from migration file.
     */
    private function getClassName(string $file): string
    {
        $filename = pathinfo($file, PATHINFO_FILENAME);
        // Remove numeric prefix: 001_create_users_table → CreateUsersTable
        $name = preg_replace('/^\d+_/', '', $filename);
        return str_replace('_', '', ucwords($name, '_'));
    }
}
