<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration {
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::create('formulir_notes', function (Blueprint $table) {
            $table->id();
            $table->morphs('notable');
            $table->foreignId('user_id')->constrained()->onDelete('cascade');
            $table->text('catatan');
            $table->timestamps();
        });

        // Data migration: Move existing notes from formulir_pendaftaran
        $pendaftarans = \DB::table('formulir_pendaftaran')->whereNotNull('catatan')->get();
        foreach ($pendaftarans as $p) {
            // Find an admin user to attribute the note to if no user is specified
            // For now, we'll just attribute it to the first admin found or skip if none
            $admin = \DB::table('users')->where('role', 'admin')->first();
            if ($admin) {
                \DB::table('formulir_notes')->insert([
                    'notable_id' => $p->id,
                    'notable_type' => 'App\Models\FormulirPendaftaran',
                    'user_id' => $admin->id,
                    'catatan' => $p->catatan,
                    'created_at' => $p->updated_at,
                    'updated_at' => $p->updated_at,
                ]);
            }
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::dropIfExists('formulir_notes');
    }
};
