<?php

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

return new class extends Migration
{
    public function up(): void
    {
        Schema::table('item_attributes', function (Blueprint $table): void {
            $table->unsignedInteger('sort_order')->default(0)->after('allow_multi_select');
        });

        $foodItemAttributes = DB::table('item_attributes')
            ->join('catalog_items', 'catalog_items.id', '=', 'item_attributes.catalog_item_id')
            ->join('attribute', 'attribute.id', '=', 'item_attributes.attribute_id')
            ->where('catalog_items.slug', 'comida')
            ->whereIn('attribute.codigo', ['event_date', 'horario', 'servicio'])
            ->select('item_attributes.id', 'attribute.codigo')
            ->get();

        $sortOrders = [
            'event_date' => 1,
            'horario' => 2,
            'servicio' => 3,
        ];

        foreach ($foodItemAttributes as $itemAttribute) {
            DB::table('item_attributes')
                ->where('id', $itemAttribute->id)
                ->update(['sort_order' => $sortOrders[$itemAttribute->codigo]]);
        }
    }

    public function down(): void
    {
        Schema::table('item_attributes', function (Blueprint $table): void {
            $table->dropColumn('sort_order');
        });
    }
};
