<?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
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        Schema::table('messages', function (Blueprint $table) {
            $table->dropForeign(['sender_id']);
        });

        Schema::table('messages', function (Blueprint $table) {
            $table->string('sender_name')->nullable()->after('sender_id');
            $table->string('sender_email')->nullable()->after('sender_name');
            $table->string('sender_phone')->nullable()->after('sender_email');
        });

        DB::statement('ALTER TABLE messages MODIFY sender_id BIGINT UNSIGNED NULL');

        Schema::table('messages', function (Blueprint $table) {
            $table->foreign('sender_id')->references('id')->on('users')->onDelete('cascade');
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('messages', function (Blueprint $table) {
            $table->dropForeign(['sender_id']);
        });

        Schema::table('messages', function (Blueprint $table) {
            $table->dropColumn(['sender_name', 'sender_email', 'sender_phone']);
        });

        DB::statement('ALTER TABLE messages MODIFY sender_id BIGINT UNSIGNED NOT NULL');

        Schema::table('messages', function (Blueprint $table) {
            $table->foreign('sender_id')->references('id')->on('users')->onDelete('cascade');
        });
    }
};
