<?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
    {
        $tables = [
            'contacts',
            'contact_notes',
            'contact_history',
            'inventory_orders',
            'inventory_transactions',
            'order_items',
            'invoice_items',
            'invoice_taxes',
            'receipts',
            'in_out_logs', // Ensuring it exists
            'audit_logs', // Redundant but safe
            'pending_staff_requests' // Redundant but safe
        ];

        foreach ($tables as $tableName) {
            if (Schema::hasTable($tableName)) {
                Schema::table($tableName, function (Blueprint $table) use ($tableName) {
                    if (!Schema::hasColumn($tableName, 'hotel_id')) {
                        $table->unsignedBigInteger('hotel_id')->nullable()->after('id');
                        
                        if (Schema::hasTable('hotels')) {
                            $table->foreign('hotel_id')->references('id')->on('hotels')->onDelete('cascade');
                        }
                    }
                });
            }
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        $tables = [
            'contacts',
            'contact_notes',
            'contact_history',
            'inventory_orders',
            'inventory_transactions',
            'order_items',
            'invoice_items',
            'invoice_taxes',
            'receipts',
            'in_out_logs',
            'audit_logs',
            'pending_staff_requests'
        ];

        foreach ($tables as $tableName) {
            if (Schema::hasTable($tableName)) {
                Schema::table($tableName, function (Blueprint $table) use ($tableName) {
                    if (Schema::hasColumn($tableName, 'hotel_id')) {
                        try {
                            // Drop foreign key if it follows standard naming
                            $table->dropForeign([$tableName . '_hotel_id_foreign']);
                        } catch (\Exception $e) {
                            // Ignore if fallback fails
                        }
                        $table->dropColumn('hotel_id');
                    }
                });
            }
        }
    }
};
