<?php

namespace src\Service;

class migrationService
{
    public function up()
    {
        $conexao = new \src\Conexao\Conexao();
        $conn = $conexao->getConexao();

        $query = "SELECT migration FROM migrations";
        $stmt = $conn->prepare($query);
        if (!$stmt) {
            echo "Erro ao preparar a consulta: " . $conn->error;
            return null;
        }
        $stmt->execute();
        $result = $stmt->get_result();

        $appliedMigrations = [];
        while ($row = $result->fetch_assoc()) {
            $appliedMigrations[] = $row['migration'];
        }

        $files = glob('./../../src/Migrations/*.php');
        foreach ($files as $file) {
            $migrationName = basename($file, '.php');
            if (!in_array($migrationName, $appliedMigrations)) {
                require_once $file;
                $migrationClass = "src\\Migrations\\$migrationName";
                $migration = new $migrationClass();
                $migration->up();

                $queryInser = 'INSERT INTO migrations (migration) VALUES (?)';

                $stmt = $conn->prepare($queryInser);

                if (!$stmt) {
                    echo "Erro ao preparar a consulta: " . $conn->error;
                    return null;
                }

                $stmt->bind_param('s', $migrationName);
                $stmt->execute();
            }
        }
    }
}
