<?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 = [
            'staff_departments',
            'staff_positions',
            'leaves',
            'leave_types',
            'leave_balances',
            'attendances',
            'staff_attendance',
            'staff_leave_requests'
        ];

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

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        $tables = [
            'staff_departments',
            'staff_positions',
            'leaves',
            'leave_types',
            'leave_balances',
            'attendances',
            'staff_attendance',
            'staff_leave_requests'
        ];

        foreach ($tables as $tableName) {
            if (Schema::hasTable($tableName) && Schema::hasColumn($tableName, 'hotel_id')) {
                Schema::table($tableName, function (Blueprint $table) use ($tableName) {
                    // Drop foreign key if it exists
                    if (Schema::hasTable('hotels')) {
                        // Check if the FK exists before dropping (naming convention: table_column_foreign)
                        try {
                            $table->dropForeign([$tableName . '_hotel_id_foreign']);
                        } catch (\Exception $e) {
                            // Ignore if FK doesn't exist under this name
                        }
                    }
                    $table->dropColumn('hotel_id');
                });
            }
        }
    }
};
