<?php
/**
 * Simple PHP script to seed migrations table
 * Usage: php seed-migrations.php [path_to_migrations_dir]
 */

require __DIR__ . '/vendor/autoload.php';

$app = require_once __DIR__ . '/bootstrap/app.php';
$app->make(\Illuminate\Contracts\Console\Kernel::class)->bootstrap();

use Illuminate\Support\Facades\DB;

$migrationsDir = $argv[1] ?? __DIR__ . '/database/migrations';

if (!is_dir($migrationsDir)) {
    echo "❌ Migrations directory not found: $migrationsDir\n";
    exit(1);
}

echo "───────────────────────────────────────────────\n";
echo "  Laravel Migration Table Seeder\n";
echo "───────────────────────────────────────────────\n";
echo "  Dir: $migrationsDir\n";
echo "───────────────────────────────────────────────\n\n";

// Collect migration files
$files = array_filter(scandir($migrationsDir), function ($file) use ($migrationsDir) {
    return $file !== '.' && $file !== '..' && pathinfo($file, PATHINFO_EXTENSION) === 'php';
});

$migrations = array_map(function ($file) {
    return pathinfo($file, PATHINFO_FILENAME);
}, $files);

sort($migrations);

if (empty($migrations)) {
    echo "⚠️  No migration files found.\n";
    exit(0);
}

echo "Found " . count($migrations) . " migration file(s). Inserting missing ones...\n\n";

$inserted = 0;
$skipped = 0;

foreach ($migrations as $migration) {
    $exists = DB::table('migrations')
        ->where('migration', $migration)
        ->exists();

    if ($exists) {
        echo "  ⏭  SKIP    $migration\n";
        $skipped++;
    } else {
        $nextBatch = DB::table('migrations')->max('batch') + 1;
        
        try {
            DB::table('migrations')->insert([
                'migration' => $migration,
                'batch' => $nextBatch,
            ]);
            echo "  ✅ INSERTED $migration\n";
            $inserted++;
        } catch (\Exception $e) {
            echo "  ❌ FAILED   $migration - " . $e->getMessage() . "\n";
        }
    }
}

echo "\n";
echo "───────────────────────────────────────────────\n";
echo "  Done. Inserted: $inserted  |  Skipped: $skipped\n";
echo "───────────────────────────────────────────────\n";
