<?php

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

return new class extends Migration
{
    public function up(): void
    {
        // 1. Add new columns to users
        Schema::table('users', function (Blueprint $table) {
            $table->string('nik_ibu', 16)->nullable()->after('id');
            $table->string('nama_lengkap')->nullable()->after('nik_ibu');
            $table->string('username')->nullable()->unique()->after('nama_lengkap');
        });

        // 2. Migrate existing data
        $users = DB::table('users')->where('role', 'orangtua')->get();
        foreach ($users as $user) {
            if ($user->nama_anak || $user->tanggal_lahir) {
                // Check if nik_anak already exists to prevent unique constraint violation
                $existing = DB::table('children')->where('nik_anak', $user->nik_anak)->first();
                if (!$existing) {
                    DB::table('children')->insert([
                        'id' => $user->id,
                        'user_id' => $user->id,
                        'nama_lengkap_anak' => $user->nama_anak ?: 'Anak ' . $user->id,
                        'tanggal_lahir' => $user->tanggal_lahir ?: now()->format('Y-m-d'),
                        'nik_anak' => $user->nik_anak,
                        'created_at' => now(),
                        'updated_at' => now(),
                    ]);
                }
            }
            
            DB::table('users')->where('id', $user->id)->update([
                'username' => 'user_' . $user->id,
                'nama_lengkap' => 'Orang Tua ' . $user->id,
            ]);
        }
        
        // Migrate admin user
        DB::table('users')->where('role', 'admin')->update([
            'username' => 'admin',
            'nama_lengkap' => 'Administrator',
        ]);

        // 3. Drop old columns
        Schema::table('users', function (Blueprint $table) {
            // dropUnique requires the index name if we didn't specify it during creation. 
            // the name generated by laravel is usually 'users_nik_anak_unique'
            // We just drop it using the array syntax.
            $table->dropUnique(['nik_anak']);
            $table->dropColumn(['nama_anak', 'nik_anak', 'tanggal_lahir']);
        });
    }

    public function down(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('nama_anak')->nullable();
            $table->string('nik_anak', 16)->nullable()->unique();
            $table->date('tanggal_lahir')->nullable();
        });
        
        // Cannot cleanly revert the data migration here, we just put columns back
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn(['nik_ibu', 'nama_lengkap', 'username']);
        });
    }
};
