<?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
    {
        // Get the default warehouse (Azan Shinwari) - ID should be 1
        $defaultWarehouseId = DB::table('warehouses')
            ->where('name', 'like', '%AZAN%')
            ->orWhere('name', 'like', '%Shinwari%')
            ->orWhere('name', 'like', '%Azan%')
            ->value('id');
        
        // If not found, try to get first active warehouse
        if (!$defaultWarehouseId) {
            $defaultWarehouseId = DB::table('warehouses')
                ->where('status', 'active')
                ->orderBy('id')
                ->value('id');
        }
        
        // If still not found, create it
        if (!$defaultWarehouseId) {
            $defaultWarehouseId = DB::table('warehouses')->insertGetId([
                'name' => 'Azan Shinwari',
                'code' => 'AZAN',
                'status' => 'active',
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }
        
        // Update existing menu items without warehouse_id
        DB::table('pos_menu_items')
            ->whereNull('warehouse_id')
            ->update(['warehouse_id' => $defaultWarehouseId]);
        
        // Update existing tables without warehouse_id
        DB::table('pos_tables')
            ->whereNull('warehouse_id')
            ->update(['warehouse_id' => $defaultWarehouseId]);
        
        // Update existing waiters without warehouse_id
        DB::table('waiters')
            ->whereNull('warehouse_id')
            ->update(['warehouse_id' => $defaultWarehouseId]);
        
        // Update existing POS staff/users without warehouse_id
        DB::table('users')
            ->whereNull('warehouse_id')
            ->whereIn('role', ['pos_staff', 'pos_manager', 'admin', 'manager'])
            ->update(['warehouse_id' => $defaultWarehouseId]);
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // This migration sets default values, so we don't need to reverse it
        // If needed, we could set warehouse_id to null, but that would break data integrity
    }
};
