<?php

declare(strict_types=1);

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

return new class extends Migration
{
    /**
     * Run the migrations.
     */
    public function up(): void
    {
        $systemSettings = DB::table('menus')->where('href', '/admin/settings')->first();
        
        $sortOrder = $systemSettings ? $systemSettings->sort_order + 1 : 21;
        
        DB::table('menus')->where('sort_order', '>=', $sortOrder)->increment('sort_order');
        
        DB::table('menus')->insert([
            'group_name' => 'Settings',
            'title' => 'QZ Tray',
            'href' => '/admin/settings/qz-tray',
            'icon' => 'Printer', // Using 'Printer' icon for printer/certificate settings
            'roles' => json_encode([]),
            'permissions' => json_encode(['manage settings']),
            'sort_order' => $sortOrder,
            'created_at' => Carbon::now(),
            'updated_at' => Carbon::now(),
        ]);
    }

    /**
     * Reverse the migrations.
     */
    public function down(): void
    {
        $menu = DB::table('menus')->where('href', '/admin/settings/qz-tray')->first();
        if ($menu) {
            $sortOrder = $menu->sort_order;
            DB::table('menus')->where('id', $menu->id)->delete();
            DB::table('menus')->where('sort_order', '>', $sortOrder)->decrement('sort_order');
        }
    }
};
