<?php

namespace App\Http\Middleware;

use Closure;
use Spatie\Menu\Laravel\Facades\Menu;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Auth;

class MenuMiddleware
{
    public function handle($request, Closure $next)
    {
        $menu = Menu::new()
            ->addClass('nav nav-pills nav-sidebar flex-column nav-flat')
            ->setWrapperTag('ul')
            ->setAttributes([
                'data-widget' => 'treeview',
                'role' => 'menu',
                'data-accordion' => 'false'
            ])
            ->html('<li class="nav-item">
                    <a href="'.url('/').'" class="nav-link">
                    <i class="nav-icon mdi mdi-home"></i>
                    <p>Halaman Utama </p>
                    </a>
                    </li>');

        $user = Auth::guard('admin')->user();
        $role = $user->roles->first();
        $currentRoleId = $role ? $role->id : null;

        if ($currentRoleId) {
            // Single query to get all authorized menus
            $allMenus = DB::table('menus')
                ->join('role_menu', 'menus.id', '=', 'role_menu.menu_id')
                ->where('role_menu.role_id', $currentRoleId)
                ->select('menus.*')
                ->orderBy('order', 'ASC')
                ->get();

            // Organize menus into parents and children
            $parents = $allMenus->where('parent_id', null);
            $childrenByParent = $allMenus->whereNotNull('parent_id')
                ->groupBy('parent_id');

            foreach ($parents as $parent) {
                $this->addMenuItems($menu, $parent, $childrenByParent->get($parent->id));
            }
        }

        view()->share('menu', $menu->render());

        return $next($request);
    }

    protected function addMenuItems($menu, $item, $children)
    {
        if ($children && $children->isNotEmpty()) {
            $submenu = Menu::new()->addClass('nav nav-treeview');
            foreach ($children as $child) {
                $submenu->html($this->createMenuItem($child));
            }

            $menu->html(
                '<li class="nav-item">' .
                    '<a href="#" class="nav-link">' .
                        '<i class="nav-icon ' . $item->icon . '"></i>' .
                        '<p>' . $item->title . '<i class="fas fa-angle-left right mt-1"></i></p>' .
                    '</a>' .
                    $submenu->render() .
                '</li>'
            );
        } else {
            $menu->html($this->createMenuItem($item));
        }
    }

    protected function createMenuItem($item)
    {
        return '<li class="nav-item">' .
            '<a href="' . url($item->url) . '" class="nav-link">' .
                '<i class="' . ($item->parent_id ? 'nav-icon ' : '') . $item->icon . '"></i>' .
                '<p>' . $item->title . '</p>' .
            '</a>' .
        '</li>';
    }
}