<?php

namespace App\Http\Middleware;

use App\Models\Menu;
use App\Models\Role;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Crypt;
use Illuminate\Support\Facades\View;
use Symfony\Component\HttpFoundation\Response;

class RoleMenuMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        if (Auth::check()) {
            $menus = $this->menuNav();
            View::share('menus', $menus);
        }

        return $next($request);
    }

    private function menuNav($parentId = null)
    {
        $roleId = Auth::user()->primary_role_id;
        $roleSlug = Role::find($roleId)->slug;
        // Ambil semua menu untuk role tertentu
        $allMenus = Menu::with('children')
            ->whereHas('roles', fn($query) => $query->where('roles.id', $roleId))
            ->orderBy('order')
            ->get();

        // Filter dan susun tree menu
        return $this->buildMenuTree($allMenus, $parentId, $roleSlug);
    }

    private function buildMenuTree($menus, $parentId = null, $roleSlug)
    {
        return $menus->filter(function ($menu) use ($parentId) {
            return $menu->parent_id === $parentId;
        })->map(function ($menu) use ($menus, $roleSlug) {
            return (object) [
                'id'    => Crypt::encrypt($menu->id),
                'name'  => ucwords($menu->name),
                'icon'  => $menu->icon ?? '',
                'route' => $menu->route ?? '',
                'url'   => str_replace('~|role|~', $roleSlug, $menu->url) ?? '',
                'role'  => $roleSlug,
                'sub_menu' => $this->buildMenuTree($menus, $menu->id, $roleSlug),  // recursive call to create submenu
            ];
        })->values(); // reset array indices, still return collection

        // return $menus->filter(function ($menu) use ($parentId) {
        //     return $menu->parent_id === $parentId;
        // })->map(function ($menu) use ($menus, $roleSlug) {
        //     return [
        //         'id' => Crypt::encrypt($menu->id),
        //         'name' => ucwords($menu->name),
        //         'icon' => $menu->icon ?? '',
        //         'route' => $menu->route ?? '',
        //         'url' => str_replace('~|role|~', $roleSlug, $menu->url) ?? '',
        //         'sub_menu' => $this->buildMenuTree($menus, $menu->id, $roleSlug),
        //     ];
        // })->values(); // reset indeks array
    }
}
