<?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
    {
        // Step 1: Create or get the restaurant "Azan Shinwari & Fast Foods"
        $restaurant = DB::table('restaurants')->where('code', 'AZS')->first();
        
        if ($restaurant) {
            // Restaurant already exists, use it
            $restaurantId = $restaurant->id;
            // Update the name if it's different
            if ($restaurant->name !== 'Azan Shinwari & Fast Foods') {
                DB::table('restaurants')
                    ->where('id', $restaurantId)
                    ->update(['name' => 'Azan Shinwari & Fast Foods']);
            }
        } else {
            // Create the restaurant
            $restaurantId = DB::table('restaurants')->insertGetId([
                'name' => 'Azan Shinwari & Fast Foods',
                'code' => 'AZS',
                'logo' => null,
                'address' => null,
                'phone' => null,
                'email' => null,
                'status' => 'active',
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }

        // Step 2: Update all existing records in tables with restaurant_id
        $tablesToUpdate = [
            'users',
            'agents',
            'stock_outs',
            'stock_closings',
            'waiters',
            'pos_tables',
            'pos_menu_items',
            'pos_orders',
            'restaurant_menu_categories',
            'pos_customers',
            'inventories',
            'pos_order_items',
            'menu_item_recipes',
            'recipe_usage_logs',
            'items',
            'inventory_categories',
            'branches', // warehouses renamed to branches
            'shifts',
            'daily_expenses',
        ];

        foreach ($tablesToUpdate as $tableName) {
            if (Schema::hasTable($tableName) && Schema::hasColumn($tableName, 'restaurant_id')) {
                // Update all records that don't have a restaurant_id set
                DB::table($tableName)
                    ->whereNull('restaurant_id')
                    ->update(['restaurant_id' => $restaurantId]);
            }
        }

        // Step 3: Update branches (warehouses) to link to this restaurant
        if (Schema::hasTable('branches') && Schema::hasColumn('branches', 'restaurant_id')) {
            DB::table('branches')
                ->whereNull('restaurant_id')
                ->update(['restaurant_id' => $restaurantId]);
        }

        // Also check for warehouses table (in case it still exists)
        if (Schema::hasTable('warehouses') && Schema::hasColumn('warehouses', 'restaurant_id')) {
            DB::table('warehouses')
                ->whereNull('restaurant_id')
                ->update(['restaurant_id' => $restaurantId]);
        }

        // Step 4: Update users with restaurant_owner role to link to this restaurant
        if (Schema::hasTable('users') && Schema::hasColumn('users', 'restaurant_id')) {
            DB::table('users')
                ->where('role', 'restaurant_owner')
                ->whereNull('restaurant_id')
                ->update(['restaurant_id' => $restaurantId]);
        }
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // Find the restaurant by name
        $restaurant = DB::table('restaurants')
            ->where('name', 'Azan Shinwari & Fast Foods')
            ->first();

        if ($restaurant) {
            $restaurantId = $restaurant->id;

            // Set restaurant_id to null for all records linked to this restaurant
            $tablesToUpdate = [
                'users',
                'agents',
                'stock_outs',
                'stock_closings',
                'waiters',
                'pos_tables',
                'pos_menu_items',
                'pos_orders',
                'restaurant_menu_categories',
                'pos_customers',
                'inventories',
                'pos_order_items',
                'menu_item_recipes',
                'recipe_usage_logs',
                'items',
                'inventory_categories',
                'branches',
                'warehouses',
                'shifts',
                'daily_expenses',
            ];

            foreach ($tablesToUpdate as $tableName) {
                if (Schema::hasTable($tableName) && Schema::hasColumn($tableName, 'restaurant_id')) {
                    DB::table($tableName)
                        ->where('restaurant_id', $restaurantId)
                        ->update(['restaurant_id' => null]);
                }
            }

            // Delete the restaurant
            DB::table('restaurants')->where('id', $restaurantId)->delete();
        }
    }
};
