<?php

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        // Add branch_id columns alongside warehouse_id for backward compatibility
        $tables = [
            'users' => 'warehouse_id',
            'agents' => 'warehouse_id',
            'stock_outs' => 'warehouse_id',
            'stock_closings' => 'warehouse_id',
            'waiters' => 'warehouse_id',
            'pos_tables' => 'warehouse_id',
            'pos_menu_items' => 'warehouse_id',
            'pos_orders' => 'warehouse_id',
            'restaurant_menu_categories' => 'warehouse_id',
            'pos_customers' => 'warehouse_id',
        ];

        foreach ($tables as $tableName => $columnName) {
            if (Schema::hasTable($tableName) && Schema::hasColumn($tableName, $columnName)) {
                Schema::table($tableName, function (Blueprint $table) use ($tableName, $columnName) {
                    // Add branch_id column
                    $table->unsignedBigInteger('branch_id')->nullable()->after($columnName);
                });
                
                // Copy data from warehouse_id to branch_id (outside the Schema closure)
                DB::statement("UPDATE {$tableName} SET branch_id = {$columnName} WHERE {$columnName} IS NOT NULL");
                
                // Add foreign key constraint and index
                Schema::table($tableName, function (Blueprint $table) {
                    $table->foreign('branch_id')->references('id')->on('branches')->nullOnDelete();
                    $table->index('branch_id');
                });
            }
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        $tables = [
            'users',
            'agents',
            'stock_outs',
            'stock_closings',
            'waiters',
            'pos_tables',
            'pos_menu_items',
            'pos_orders',
            'restaurant_menu_categories',
            'pos_customers',
        ];

        foreach ($tables as $tableName) {
            if (Schema::hasTable($tableName) && Schema::hasColumn($tableName, 'branch_id')) {
                Schema::table($tableName, function (Blueprint $table) {
                    $table->dropForeign(['branch_id']);
                    $table->dropIndex(['branch_id']);
                    $table->dropColumn('branch_id');
                });
            }
        }
    }
};
