<?php

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

return new class extends Migration {
    public function up(): void
    {
        if (Schema::getConnection()->getDriverName() !== 'sqlite') {
            // For other DBs, modify the enum directly
            DB::statement("ALTER TABLE users MODIFY COLUMN role ENUM('admin','partner','customer','team_member') NOT NULL DEFAULT 'customer'");
            return;
        }

        // SQLite: rebuild users table with team_member role
        $rows = DB::select('SELECT * FROM users');
        $cols = Schema::getColumnListing('users');

        Schema::disableForeignKeyConstraints();
        Schema::drop('users');
        Schema::enableForeignKeyConstraints();

        // Recreate without role first
        Schema::create('users', function ($table) {
            $table->id();
            $table->string('name');
            $table->string('email')->unique();
            $table->timestamp('email_verified_at')->nullable();
            $table->string('password');
            $table->rememberToken();
            $table->timestamps();
            $table->string('phone', 20)->nullable()->unique();
            $table->string('role', 30)->default('customer');
            $table->boolean('is_partner_approved')->default(false);
            $table->string('avatar')->nullable();
            $table->text('address')->nullable();
            $table->string('city', 80)->nullable();
            $table->string('pincode', 12)->nullable();
            $table->decimal('lat', 10, 7)->nullable();
            $table->decimal('lng', 10, 7)->nullable();
        });

        // Reinsert rows
        foreach ($rows as $r) {
            $arr = (array) $r;
            $insert = [];
            foreach ($cols as $c) {
                if (array_key_exists($c, $arr)) {
                    $insert[$c] = $arr[$c];
                }
            }
            // Set timestamps to string for insert
            foreach (['created_at','updated_at','email_verified_at'] as $tk) {
                if (isset($insert[$tk]) && $insert[$tk] !== null) {
                    $insert[$tk] = date('Y-m-d H:i:s', strtotime($insert[$tk]));
                }
            }
            DB::table('users')->insert($insert);
        }
    }

    public function down(): void
    {
        // No rollback
    }
};