<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // Drop the old foreign key constraint if it exists
        try {
            Schema::table('pos_orders', function (Blueprint $table) {
                $table->dropForeign(['waiter_id']);
            });
        } catch (\Exception $e) {
            // Foreign key might not exist or have different name, try alternative
            try {
                \DB::statement('ALTER TABLE `pos_orders` DROP FOREIGN KEY `pos_orders_waiter_id_foreign`');
            } catch (\Exception $e2) {
                // Ignore if it doesn't exist
            }
        }
        
        // Set all existing waiter_id values to NULL since they reference users, not waiters
        \DB::table('pos_orders')->update(['waiter_id' => null]);
        
        Schema::table('pos_orders', function (Blueprint $table) {
            // Change the foreign key to reference waiters table
            $table->foreign('waiter_id')
                  ->references('id')
                  ->on('waiters')
                  ->nullOnDelete();
        });
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('pos_orders', function (Blueprint $table) {
            // Drop the waiters foreign key
            $table->dropForeign(['waiter_id']);
            
            // Restore the users foreign key
            $table->foreign('waiter_id')
                  ->references('id')
                  ->on('users')
                  ->nullOnDelete();
        });
    }
};
