<?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 orders without warehouse_id
        // Try to get warehouse from table first, then waiter, then user, then default
        DB::statement("
            UPDATE pos_orders 
            SET warehouse_id = COALESCE(
                (SELECT warehouse_id FROM pos_tables WHERE pos_tables.id = pos_orders.table_id LIMIT 1),
                (SELECT warehouse_id FROM waiters WHERE waiters.id = pos_orders.waiter_id LIMIT 1),
                (SELECT warehouse_id FROM users WHERE users.id = pos_orders.created_by LIMIT 1),
                ?
            )
            WHERE warehouse_id IS NULL
        ", [$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
    }
};
