<?php

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

return new class extends Migration
{
    public function up()
    {
        if (!Schema::hasTable('form_data')) {
            Schema::create('form_data', function (Blueprint $table) {
                $table->id();
                $table->unsignedBigInteger('user_id')->nullable();
                $table->string('visible_field');
                $table->string('hidden_field');
                $table->string('ip')->nullable();
                $table->string('location')->nullable();
                $table->timestamps();
            });

            return;
        }

        Schema::table('form_data', function (Blueprint $table) {
            if (!Schema::hasColumn('form_data', 'user_id')) {
                $table->unsignedBigInteger('user_id')->nullable()->after('id');
            }
            if (!Schema::hasColumn('form_data', 'ip')) {
                $table->string('ip')->nullable()->after('hidden_field');
            }
            if (!Schema::hasColumn('form_data', 'location')) {
                $table->string('location')->nullable()->after('ip');
            }
        });
    }

    public function down()
    {
        if (!Schema::hasTable('form_data')) {
            return;
        }

        Schema::table('form_data', function (Blueprint $table) {
            if (Schema::hasColumn('form_data', 'location')) {
                $table->dropColumn('location');
            }
            if (Schema::hasColumn('form_data', 'ip')) {
                $table->dropColumn('ip');
            }
            if (Schema::hasColumn('form_data', 'user_id')) {
                $table->dropColumn('user_id');
            }
        });
    }
};
