<?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
    {
        Schema::table('menu_item_recipes', function (Blueprint $table) {
            if (!Schema::hasColumn('menu_item_recipes', 'menu_item_id')) {
                $table->foreignId('menu_item_id')->after('id')->constrained('pos_menu_items')->onDelete('cascade');
            }
            if (!Schema::hasColumn('menu_item_recipes', 'inventory_item_id')) {
                $table->foreignId('inventory_item_id')->after('menu_item_id')->constrained('items')->onDelete('cascade');
            }
            if (!Schema::hasColumn('menu_item_recipes', 'quantity')) {
                $table->decimal('quantity', 10, 2)->after('inventory_item_id');
            }
            if (!Schema::hasColumn('menu_item_recipes', 'unit')) {
                $table->string('unit')->nullable()->after('quantity');
            }
            if (!Schema::hasColumn('menu_item_recipes', 'details')) {
                $table->text('details')->nullable()->after('unit');
            }
            if (!Schema::hasColumn('menu_item_recipes', 'sort_order')) {
                $table->integer('sort_order')->default(0)->after('details');
            }
        });

        // Add indexes
        try {
            Schema::table('menu_item_recipes', function (Blueprint $table) {
                $table->index('menu_item_id');
                $table->index('inventory_item_id');
            });
        } catch (\Exception $e) {
            // Indexes might already exist
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        Schema::table('menu_item_recipes', function (Blueprint $table) {
            if (Schema::hasColumn('menu_item_recipes', 'sort_order')) {
                $table->dropColumn('sort_order');
            }
            if (Schema::hasColumn('menu_item_recipes', 'details')) {
                $table->dropColumn('details');
            }
            if (Schema::hasColumn('menu_item_recipes', 'unit')) {
                $table->dropColumn('unit');
            }
            if (Schema::hasColumn('menu_item_recipes', 'quantity')) {
                $table->dropColumn('quantity');
            }
            if (Schema::hasColumn('menu_item_recipes', 'inventory_item_id')) {
                $table->dropForeign(['inventory_item_id']);
                $table->dropColumn('inventory_item_id');
            }
            if (Schema::hasColumn('menu_item_recipes', 'menu_item_id')) {
                $table->dropForeign(['menu_item_id']);
                $table->dropColumn('menu_item_id');
            }
        });
    }
};
