<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->string('first_name')->nullable()->after('name');
            $table->string('last_name')->nullable()->after('first_name');
            $table->string('phone')->nullable()->after('email');
            $table->string('role_type')->default('admin')->after('is_admin');
            $table->string('status')->default('active')->after('role_type');
        });

        $users = DB::table('users')->get();
        foreach ($users as $user) {
            $parts = preg_split('/\s+/', trim((string) $user->name), 2);
            DB::table('users')->where('id', $user->id)->update([
                'first_name' => $parts[0] ?: 'Admin',
                'last_name' => $parts[1] ?? 'Manager',
                'role_type' => $user->is_admin ? 'super_admin' : 'admin',
                'status' => 'active',
            ]);
        }
    }

    public function down(): void
    {
        Schema::table('users', function (Blueprint $table) {
            $table->dropColumn(['first_name', 'last_name', 'phone', 'role_type', 'status']);
        });
    }
};
