<?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
    {
        // Find Azan Restaurant warehouse (or create it if it doesn't exist)
        $defaultWarehouseId = DB::table('warehouses')
            ->where(function($query) {
                $query->where('name', 'like', '%AZAN%')
                      ->orWhere('name', 'like', '%Azan%')
                      ->orWhere('name', 'like', '%Shinwari%');
            })
            ->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 Azan Restaurant warehouse
        if (!$defaultWarehouseId) {
            $defaultWarehouseId = DB::table('warehouses')->insertGetId([
                'name' => 'Azan Restaurant',
                'code' => 'AZAN',
                'status' => 'active',
                'created_at' => now(),
                'updated_at' => now(),
            ]);
        }
        
        // Assign warehouse_id to existing POS users (pos_manager and pos_staff only)
        // Leave admin and other staff with null/empty warehouse_id
        DB::table('users')
            ->whereNull('warehouse_id')
            ->whereIn('role', ['pos_manager', 'pos_staff'])
            ->update(['warehouse_id' => $defaultWarehouseId]);
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        // Set warehouse_id to null for pos_manager and pos_staff users
        // This is optional - you may want to keep the warehouse_id even on rollback
        DB::table('users')
            ->whereIn('role', ['pos_manager', 'pos_staff'])
            ->update(['warehouse_id' => null]);
    }
};
