<?php

namespace App\Services;

use App\Models\AppSetting;
use App\Models\MenuModels;

class LayoutSidebarService
{
    public function build($authUser, array $pendingResponseByPath = [], array $pendingResponseCounts = []): array
    {
        $resolvedMenus = collect();
        $parentMenus = collect();
        $childrenByParent = collect();
        $breadcrumbMenus = collect();
        $renderMenuNodes = fn (int $parentId = 0, int $depth = 0) => '';
        $appBrandName = trim((string) (AppSetting::query()->where('key', 'company.name')->value('value') ?: '')) ?: 'RBAC Admin';
        $appLogoUrl = trim((string) (AppSetting::query()->where('key', 'company.logo_url')->value('value') ?: '')) ?: asset('logo.png');

                $resolvedMenus = collect();
                $parentMenus = collect();
                $childrenByParent = collect();
                $breadcrumbMenus = collect();

                if ($authUser) {
                    $authUser->loadMissing(['permissions:id', 'roles.permissions:id']);
                    $activeRoles = $authUser->roles->filter(fn ($role) => (bool) ($role->pivot->is_active ?? true));
                    $isAdministrator = $activeRoles->contains(function ($role) {
                        $slug = strtolower((string) ($role->slug ?? ''));
                        $name = strtolower((string) ($role->name ?? ''));
                        return in_array($slug, ['administrator', 'super-admin'], true)
                            || in_array($name, ['administrator', 'super admin'], true)
                            || str_contains($slug, 'administrator')
                            || str_contains($name, 'administrator');
                    });

                    $directPermissionIds = $authUser->permissions
                        ->pluck('id')
                        ->filter();

                    $rolePermissionIds = $activeRoles
                        ->flatMap(fn ($role) => $role->permissions->pluck('id'))
                        ->filter();

                    $allowedPermissionIds = $directPermissionIds
                        ->merge($rolePermissionIds)
                        ->unique()
                        ->values();

                    $userDepartment = trim((string) ($authUser->department ?? ''));
                    if ($userDepartment !== '') {
                        $profileRoleName = 'Profil Menu ' . $userDepartment;
                        $profileRoleSlug = \Illuminate\Support\Str::slug($profileRoleName);
                        $profileRole = \App\Models\RoleModels::query()
                            ->with('permissions:id')
                            ->where('name', $profileRoleName)
                            ->orWhere('slug', $profileRoleSlug)
                            ->first();
                        if ($profileRole) {
                            $profilePermissionIds = $profileRole->permissions->pluck('id')->map(fn ($id) => (int) $id);
                            $allowedPermissionIds = $allowedPermissionIds
                                ->merge($profilePermissionIds)
                                ->unique()
                                ->values();
                        }
                    }

                    $activeProfileNames = $activeRoles
                        ->pluck('name')
                        ->filter()
                        ->map(fn ($name) => trim((string) $name))
                        ->filter(fn ($name) => str_starts_with(strtolower($name), 'profil '))
                        ->flatMap(function ($name) {
                            $normalized = preg_replace('/\\s+/', ' ', trim((string) $name));
                            $lower = strtolower($normalized);
                            $aliases = collect([$normalized]);

                            if (str_starts_with($lower, 'profil menu ')) {
                                $suffix = trim(substr($normalized, strlen('Profil Menu ')));
                                if ($suffix !== '') {
                                    $aliases->push('Profil ' . $suffix);
                                }
                            } elseif (str_starts_with($lower, 'profil ')) {
                                $suffix = trim(substr($normalized, strlen('Profil ')));
                                if ($suffix !== '') {
                                    $aliases->push('Profil Menu ' . $suffix);
                                }
                            }

                            return $aliases;
                        })
                        ->filter()
                        ->unique()
                        ->values();
                    if ($activeProfileNames->isEmpty() && $userDepartment !== '') {
                        $activeProfileNames = collect([
                            'Profil Menu ' . $userDepartment,
                            'Profil ' . $userDepartment,
                        ]);
                    }
                    $activeProfileNamesLower = $activeProfileNames
                        ->map(fn ($name) => strtolower(trim((string) $name)))
                        ->filter()
                        ->unique()
                        ->values();

                    $rawMenus = MenuModels::query()
                        ->with('permissions:id,slug')
                        ->where('is_active', true)
                        ->where(function ($q) use ($activeProfileNamesLower) {
                            $q->whereNull('department')->orWhere('department', '');
                            if ($activeProfileNamesLower->isNotEmpty()) {
                                $q->orWhereIn(
                                    \Illuminate\Support\Facades\DB::raw('LOWER(TRIM(department))'),
                                    $activeProfileNamesLower->all()
                                );
                            }
                        })
                        ->where(function ($q) {
                            $q->whereNull('url')->orWhere('url', '!=', '/menu_privilige');
                        })
                        ->orderBy('sort_order')
                        ->orderBy('name')
                        ->get();

                    $allowedPermissionSlugs = collect();
                    if ($allowedPermissionIds->isNotEmpty()) {
                        $allowedPermissionSlugs = \App\Models\PermissionModels::query()
                            ->whereIn('id', $allowedPermissionIds)
                            ->pluck('slug')
                            ->filter()
                            ->map(fn ($slug) => strtolower((string) $slug));
                    }

                    $allowedMenus = $rawMenus->filter(function ($menu) use ($allowedPermissionIds, $allowedPermissionSlugs) {
                        if ($allowedPermissionIds->isEmpty() && $allowedPermissionSlugs->isEmpty()) {
                            return false;
                        }
                        $menuSlug = strtolower((string) ($menu->slug ?? ''));
                        $menuName = strtolower((string) ($menu->name ?? ''));
                        $menuPermissionIds = $menu->permissions->pluck('id')->map(fn ($id) => (int) $id);
                        if ($menuPermissionIds->intersect($allowedPermissionIds)->isNotEmpty()) {
                            return true;
                        }
                        if ($menuSlug !== '' && $allowedPermissionSlugs->contains($menuSlug . '.view')) {
                            return true;
                        }
                        if ($menuName === 'dashboard' && $allowedPermissionSlugs->contains('dashboard.view')) {
                            return true;
                        }
                        return false;
                    })->values();

                    $isPlaceholderUrl = function ($url): bool {
                        $value = strtolower(trim((string) ($url ?? '')));
                        return in_array($value, ['', '#', '/#', 'javascript:void(0)', 'javascript:void(0);'], true);
                    };

                    // Remove duplicated menu entries (same URL/slug target) to keep sidebar clean.
                    $allowedMenus = $allowedMenus
                        ->unique(function ($menu) use ($isPlaceholderUrl) {
                            $path = !$isPlaceholderUrl($menu->url)
                                ? (string) $menu->url
                                : '/' . ltrim((string) $menu->slug, '/');
                            $path = '/' . ltrim((string) $path, '/');
                            if ($path === '/') {
                                return 'path:/';
                            }
                            if (!$isPlaceholderUrl($menu->url)) {
                                return 'path:' . strtolower(rtrim($path, '/'));
                            }
                            return 'name:' . strtolower(trim((string) ($menu->name ?? '')));
                        })
                        ->values();
                    $resolvedMap = $allowedMenus->keyBy('id');
                    $pendingParentIds = $allowedMenus->pluck('parent_id')->filter()->unique()->values();

                    while ($pendingParentIds->isNotEmpty()) {
                        $parentRows = $rawMenus->whereIn('id', $pendingParentIds)->values();
                        foreach ($parentRows as $parentRow) {
                            $resolvedMap->put($parentRow->id, $parentRow);
                        }

                        $knownIds = $resolvedMap->keys();
                        $pendingParentIds = $parentRows
                            ->pluck('parent_id')
                            ->filter()
                            ->unique()
                            ->reject(fn ($id) => $knownIds->contains($id))
                            ->values();
                    }

                    $resolvedMenus = $resolvedMap->values();

                    // Merge duplicate siblings (same parent + same target path) and re-parent children
                    // from removed duplicate IDs so nested menus are not lost.
                    $canonicalByKey = [];
                    $aliasParentIds = [];
                    foreach ($resolvedMenus as $menu) {
                        $parentId = (int) ($menu->parent_id ?? 0);
                        $path = !$isPlaceholderUrl($menu->url)
                            ? (string) $menu->url
                            : '/' . ltrim((string) ($menu->slug ?? ''), '/');
                        $path = '/' . ltrim((string) $path, '/');
                        $path = strtolower(rtrim($path, '/'));
                        if ($path === '') {
                            $path = '/';
                        }
                        $name = strtolower(trim((string) ($menu->name ?? '')));
                        $usePathKey = $path !== '/' && !$isPlaceholderUrl($menu->url);
                        $key = $parentId . '|' . ($usePathKey ? 'path:' . $path : 'name:' . $name);

                        if (!isset($canonicalByKey[$key])) {
                            $canonicalByKey[$key] = (int) $menu->id;
                            continue;
                        }

                        $aliasParentIds[(int) $menu->id] = (int) $canonicalByKey[$key];
                    }

                    if (!empty($aliasParentIds)) {
                        foreach ($resolvedMenus as $menu) {
                            $parentId = (int) ($menu->parent_id ?? 0);
                            $guard = 0;
                            while (isset($aliasParentIds[$parentId]) && $guard < 20) {
                                $parentId = (int) $aliasParentIds[$parentId];
                                $guard++;
                            }
                            $menu->parent_id = $parentId > 0 ? $parentId : null;
                        }
                    }

                    $resolvedMenus = $resolvedMenus
                        ->reject(fn ($menu) => isset($aliasParentIds[(int) $menu->id]))
                        ->values();
                    $parentMenus = $resolvedMenus
                        ->whereNull('parent_id')
                        ->sortBy([['sort_order', 'asc'], ['name', 'asc']])
                        ->values();
                    $childrenByParent = $resolvedMenus
                        ->groupBy(fn ($menu) => $menu->parent_id ? (int) $menu->parent_id : 0)
                        ->map(fn ($items) => $items->sortBy([['sort_order', 'asc'], ['name', 'asc']])->values());

                    $isMenuPathActive = function ($menu, bool $allowPrefix = true) use ($isPlaceholderUrl) {
                        $requestPath = '/' . ltrim((string) request()->path(), '/');
                        $menuPath = !$isPlaceholderUrl($menu->url)
                            ? (string) $menu->url
                            : '/' . ltrim((string) $menu->slug, '/');
                        $menuPath = '/' . ltrim((string) $menuPath, '/');
                        $menuPath = rtrim($menuPath, '/');
                        $requestPath = rtrim($requestPath, '/');

                        if ($menuPath === '') {
                            $menuPath = '/';
                        }
                        if ($requestPath === '') {
                            $requestPath = '/';
                        }
                        if ($menuPath === '/') {
                            return $requestPath === '/';
                        }

                        if ($requestPath === $menuPath) {
                            return true;
                        }

                        return $allowPrefix
                            ? str_starts_with($requestPath . '/', $menuPath . '/')
                            : false;
                    };

                    $hasActiveDescendant = function (int $menuId) use (&$hasActiveDescendant, $childrenByParent, $isMenuPathActive): bool {
                        $children = $childrenByParent->get($menuId, collect());
                        foreach ($children as $child) {
                            if ($isMenuPathActive($child) || $hasActiveDescendant((int) $child->id)) {
                                return true;
                            }
                        }
                        return false;
                    };

                    // Default icon mapping if `menus.icon` is empty.
                    // Keep it conservative: we only apply this when icon is missing.
                    $guessMenuIcon = function ($menu, bool $hasChildren) use ($isPlaceholderUrl): string {
                        $name = strtolower(trim((string) ($menu->name ?? '')));
                        $slug = strtolower(trim((string) ($menu->slug ?? '')));
                        $url = strtolower(trim((string) ($menu->url ?? '')));
                        $path = !$isPlaceholderUrl($url) ? $url : '/' . ltrim($slug, '/');
                        $search = $name . '|' . $slug . '|' . $path;

                        $map = [
                            'dashboard' => 'fas fa-gauge-high',
                            'attendance' => 'fas fa-fingerprint',
                            'absen' => 'fas fa-fingerprint',
                            'review' => 'fas fa-clipboard-check',
                            'approval' => 'fas fa-clipboard-check',
                            'pengajuan' => 'fas fa-file-signature',
                            'request' => 'fas fa-file-signature',
                            'kalender' => 'fas fa-calendar-days',
                            'calendar' => 'fas fa-calendar-days',
                            'hris' => 'fas fa-users',
                            'karyawan' => 'fas fa-users',
                            'payroll' => 'fas fa-file-invoice-dollar',
                            'penggajian' => 'fas fa-file-invoice-dollar',
                            'finance' => 'fas fa-money-bill-wave',
                            'keuangan' => 'fas fa-money-bill-wave',
                            'accounting' => 'fas fa-money-bill-wave',
                            'warehouse' => 'fas fa-warehouse',
                            'gudang' => 'fas fa-warehouse',
                            'procurement' => 'fas fa-cart-shopping',
                            'pengadaan' => 'fas fa-cart-shopping',
                            'purchase order' => 'fas fa-cart-shopping',
                            'po' => 'fas fa-cart-shopping',
                            'project' => 'fas fa-diagram-project',
                            'proyek' => 'fas fa-diagram-project',
                            'manufacturing' => 'fas fa-industry',
                            'mobile' => 'fas fa-mobile-screen-button',
                            'api key' => 'fas fa-key',
                            'module' => 'fas fa-cubes',
                            'user' => 'fas fa-user',
                            'role' => 'fas fa-user-shield',
                            'menu' => 'fas fa-bars',
                            'backup' => 'fas fa-database',
                            'report' => 'fas fa-chart-column',
                        ];

                        foreach ($map as $needle => $icon) {
                            if ($needle === 'po') {
                                // Avoid matching words like "profile" unintentionally.
                                if (preg_match('/(^|\\W)po(\\W|$)/', $search) === 1) {
                                    return $icon;
                                }
                                continue;
                            }
                            if (str_contains($search, $needle)) {
                                return $icon;
                            }
                        }

                        return $hasChildren ? 'fas fa-folder-tree' : 'far fa-circle';
                    };

                    $menuBadgeData = function ($menu) use ($isPlaceholderUrl, $pendingResponseByPath, $pendingResponseCounts) {
                        $menuPath = !$isPlaceholderUrl($menu->url)
                            ? (string) $menu->url
                            : '/' . ltrim((string) ($menu->slug ?? ''), '/');
                        $menuPath = '/' . ltrim((string) $menuPath, '/');
                        $menuPath = rtrim($menuPath, '/');
                        if ($menuPath === '') {
                            $menuPath = '/';
                        }

                        $pendingCount = (int) ($pendingResponseByPath[$menuPath] ?? 0);
                        $secondaryCount = 0;
                        $secondaryClass = 'text-bg-info';
                        $secondaryTitle = '';
                        if ($pendingCount <= 0) {
                            $search = strtolower($menuPath) . '|' . strtolower((string) ($menu->slug ?? '')) . '|' . strtolower((string) ($menu->name ?? ''));

                            if (
                                str_contains($search, 'surat-perintah-lembur') ||
                                str_contains($search, 'request-lembur') ||
                                (str_contains($search, 'lembur') && str_contains($search, 'request'))
                            ) {
                                $pendingCount = (int) ($pendingResponseCounts['spl'] ?? 0);
                            } elseif (
                                str_contains($search, 'forgetting-clock') ||
                                str_contains($search, 'forgeting-clock') ||
                                str_contains($search, 'forgettingclock') ||
                                str_contains($search, 'forgetingclock') ||
                                str_contains($search, 'lupa-clock')
                            ) {
                                $pendingCount = (int) ($pendingResponseCounts['fc'] ?? 0);
                            } elseif (
                                str_contains($search, 'leave-request') ||
                                str_contains($search, 'request-leave') ||
                                (str_contains($search, 'leave') && str_contains($search, 'request'))
                            ) {
                                $pendingCount = (int) ($pendingResponseCounts['leave'] ?? 0);
                            } elseif (
                                str_contains($search, 'login-reset') ||
                                str_contains($search, 'reset-login') ||
                                str_contains($search, 'reset password') ||
                                str_contains($search, 'reset-password')
                            ) {
                                $pendingCount = (int) ($pendingResponseCounts['login_reset'] ?? 0);
                            } elseif (
                                str_contains($search, 'master-shift-schedule') ||
                                str_contains($search, 'master jadwal bulanan')
                            ) {
                                $pendingCount = (int) ($pendingResponseCounts['shift_schedule'] ?? 0);
                            } elseif (
                                str_contains($search, 'reimbursement') ||
                                str_contains($search, 'reimburse')
                            ) {
                                $pendingCount = (int) ($pendingResponseCounts['reimbursement'] ?? 0);
                            } elseif (
                                str_contains($search, 'master-profil-bulan') ||
                                (str_contains($search, 'profil') && str_contains($search, 'bulan'))
                            ) {
                                $secondaryCount = (int) ($pendingResponseCounts['profil_bulan_missing'] ?? 0);
                                $secondaryTitle = 'Karyawan aktif belum masuk ke profil bulan aktif';
                            }
                        }

                        return [
                            'pending' => $pendingCount,
                            'secondary' => $secondaryCount,
                            'secondary_class' => $secondaryClass,
                            'secondary_title' => $secondaryTitle,
                        ];
                    };
                    $menuBadgeTotal = function ($menu) use (&$menuBadgeTotal, $childrenByParent, $menuBadgeData) {
                        $data = $menuBadgeData($menu);
                        $total = (int) $data['pending'] + (int) $data['secondary'];
                        foreach ($childrenByParent->get((int) $menu->id, collect()) as $child) {
                            $total += $menuBadgeTotal($child);
                        }
                        return $total;
                    };
                    $renderMenuNodes = function (int $parentId = 0, int $depth = 0) use (&$renderMenuNodes, $childrenByParent, $isMenuPathActive, $hasActiveDescendant, $isPlaceholderUrl, $guessMenuIcon, $menuBadgeData, $menuBadgeTotal) {
                        $children = $childrenByParent
                            ->get($parentId, collect())
                            ->unique(function ($menu) use ($isPlaceholderUrl) {
                                $path = !$isPlaceholderUrl($menu->url)
                                    ? (string) $menu->url
                                    : '/' . ltrim((string) ($menu->slug ?? ''), '/');
                                $path = '/' . ltrim((string) $path, '/');
                                $path = strtolower(rtrim($path, '/'));
                                if ($path === '') {
                                    $path = '/';
                                }
                                $name = strtolower(trim((string) ($menu->name ?? '')));
                                $usePathKey = $path !== '/' && !$isPlaceholderUrl($menu->url);
                                return $usePathKey ? 'path:' . $path : 'name:' . $name;
                            })
                            ->values();
                        if ($children->isEmpty()) {
                            return '';
                        }

                        $html = '';
                        foreach ($children as $menu) {
                            $hasChildren = $childrenByParent->has((int) $menu->id);
                            $menuPath = !$isPlaceholderUrl($menu->url)
                                ? (string) $menu->url
                                : '/' . ltrim((string) $menu->slug, '/');
                            $menuPath = '/' . ltrim((string) $menuPath, '/');
                            $menuPath = rtrim($menuPath, '/');
                            if ($menuPath === '') {
                                $menuPath = '/';
                            }
                            $menuUrl = url($menuPath);
                            // Leaf menu should be exact match only to avoid double-active
                            // for sibling paths like /iclock/admin and /iclock/admin/devices.
                            $isActive = $isMenuPathActive($menu, $hasChildren);
                            $isChildActive = $hasActiveDescendant((int) $menu->id);
                            $isOpen = $isActive || $isChildActive;
                            $rawIcon = trim((string) ($menu->icon ?? ''));
                            if ($rawIcon === '') {
                                $rawIcon = $guessMenuIcon($menu, $hasChildren);
                            }
                            if (str_starts_with($rawIcon, 'mi:') || str_starts_with($rawIcon, 'material:')) {
                                $materialName = trim((string) preg_replace('/^(mi|material):/i', '', $rawIcon));
                                $iconHtml = '<span class="nav-icon material-icons">' . e($materialName !== '' ? $materialName : 'menu') . '</span>';
                            } elseif (str_starts_with($rawIcon, 'ion:')) {
                                $ionName = trim((string) preg_replace('/^ion:/i', '', $rawIcon));
                                $iconHtml = '<ion-icon class="nav-icon" name="' . e($ionName !== '' ? $ionName : 'ellipse-outline') . '"></ion-icon>';
                            } else {
                                $iconHtml = '<i class="nav-icon ' . e($rawIcon) . '"></i>';
                            }
                            $name = e($menu->name);
                            $badgeData = $menuBadgeData($menu);
                            $pendingCount = (int) $badgeData['pending'];
                            $secondaryCount = (int) $badgeData['secondary'];
                            $secondaryClass = (string) $badgeData['secondary_class'];
                            $secondaryTitle = (string) $badgeData['secondary_title'];
                            $badgeParts = [];
                            if ($pendingCount > 0) {
                                $badgeParts[] = '<span class="badge rounded-pill text-bg-warning menu-badge" title="Perlu approval">' . e((string) $pendingCount) . '</span>';
                            }
                            if ($secondaryCount > 0) {
                                $badgeParts[] = '<span class="badge rounded-pill ' . e($secondaryClass) . ' menu-badge" title="' . e($secondaryTitle ?: 'Info') . '">' . e((string) $secondaryCount) . '</span>';
                            }
                            $badgeHtml = implode('', $badgeParts);
                            $childBadgeHtml = '';
                            if ($hasChildren && $badgeHtml === '') {
                                $childBadgeTotal = max(0, $menuBadgeTotal($menu));
                                if ($childBadgeTotal > 0) {
                                    $childBadgeHtml = '<span class="badge rounded-pill text-bg-warning menu-badge menu-badge-summary" title="Ada notifikasi di submenu">' . e((string) $childBadgeTotal) . '</span>';
                                }
                            }

                            if ($hasChildren) {
                                $html .= '<li class="nav-item has-treeview ' . ($isOpen ? 'menu-open' : '') . '">';
                                $html .= '<a href="#" class="nav-link nav-depth-' . (int) min($depth, 4) . ' ' . ($isOpen ? 'active' : '') . '">';
                                $html .= $iconHtml;
                                $html .= $badgeHtml . $childBadgeHtml;
                                $html .= '<p class="menu-label">' . $name . '<i class="nav-arrow fas fa-angle-right"></i></p>';
                                $html .= '</a>';
                                $html .= '<ul class="nav nav-treeview">';
                                $html .= $renderMenuNodes((int) $menu->id, $depth + 1);
                                $html .= '</ul>';
                                $html .= '</li>';
                            } else {
                                $html .= '<li class="nav-item">';
                                $html .= '<a href="' . e($menuUrl) . '" class="nav-link nav-depth-' . (int) min($depth, 4) . ' ' . ($isActive ? 'active' : '') . '">';
                                $html .= $iconHtml;
                                $html .= $badgeHtml;
                                $html .= '<p class="menu-label">' . $name . '</p>';
                                $html .= '</a>';
                                $html .= '</li>';
                            }
                        }

                        return $html;
                    };

                    $menuById = $resolvedMenus->keyBy('id');
                    $matchedMenu = $resolvedMenus->first(fn ($menu) => $isMenuPathActive($menu));
                    if ($matchedMenu) {
                        $cursor = $matchedMenu;
                        while ($cursor) {
                            $breadcrumbMenus->prepend($cursor);
                            $parentId = $cursor->parent_id ? (int) $cursor->parent_id : null;
                            $cursor = $parentId ? $menuById->get($parentId) : null;
                        }
                    }
                    $appBrandName = trim((string) (\App\Models\AppSetting::query()->where('key', 'company.name')->value('value') ?: '')) ?: 'RBAC Admin';
                    $appLogoUrl = trim((string) (\App\Models\AppSetting::query()->where('key', 'company.logo_url')->value('value') ?: '')) ?: asset('logo.png');
                }
        return [
            'breadcrumbMenus' => $breadcrumbMenus,
            'renderMenuNodes' => $renderMenuNodes,
            'appBrandName' => $appBrandName,
            'appLogoUrl' => $appLogoUrl,
        ];
    }
}
