<?php

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

return new class extends Migration
{
    public function up(): void
    {
        if (!Schema::hasTable('nav_items') || !Schema::hasTable('role_nav_items') || !Schema::hasTable('roles')) {
            return;
        }

        $now = now();
        $label = 'Badge Scanning List';
        $url = '/app/administrator/attendance/badge-scans';

        $parentId = DB::table('nav_items')
            ->whereNull('deleted_at')
            ->whereRaw('LOWER(label) = ?', ['attendance'])
            ->orderBy('id')
            ->value('id');

        $navId = DB::table('nav_items')
            ->where('url', $url)
            ->value('id');

        if (!$navId) {
            $navId = DB::table('nav_items')->insertGetId([
                'menu_parent_id' => $parentId ?: null,
                'label' => $label,
                'url' => $url,
                'icon_class' => 'bi-upc-scan',
                'target' => null,
                'sort_order' => 50,
                'is_enabled' => 1,
                'created_at' => $now,
                'updated_at' => $now,
                'deleted_at' => null,
            ]);
        } else {
            DB::table('nav_items')
                ->where('id', $navId)
                ->update([
                    'menu_parent_id' => $parentId ?: null,
                    'label' => $label,
                    'icon_class' => 'bi-upc-scan',
                    'sort_order' => 50,
                    'is_enabled' => 1,
                    'updated_at' => $now,
                    'deleted_at' => null,
                ]);
        }

        $roleIds = DB::table('roles')
            ->where('is_active', 1)
            ->where(function ($query) {
                $query->whereIn(DB::raw('LOWER(name)'), ['administrator', 'admin'])
                    ->orWhereIn(DB::raw('LOWER(COALESCE(slug, ""))'), ['administrator', 'admin']);
            })
            ->pluck('id')
            ->map(fn ($id) => (int) $id)
            ->filter(fn ($id) => $id > 0)
            ->values();

        foreach ($roleIds as $roleId) {
            $exists = DB::table('role_nav_items')
                ->where('role_id', $roleId)
                ->where('nav_item_id', $navId)
                ->exists();

            if (!$exists) {
                DB::table('role_nav_items')->insert([
                    'role_id' => $roleId,
                    'nav_item_id' => $navId,
                    'created_at' => $now,
                    'updated_at' => $now,
                ]);
            }
        }
    }

    public function down(): void
    {
        if (!Schema::hasTable('nav_items')) {
            return;
        }

        $url = '/app/administrator/attendance/badge-scans';
        $navId = DB::table('nav_items')->where('url', $url)->value('id');

        if ($navId && Schema::hasTable('role_nav_items')) {
            DB::table('role_nav_items')->where('nav_item_id', $navId)->delete();
        }

        if ($navId) {
            DB::table('nav_items')->where('id', $navId)->delete();
        }
    }
};
