<?php defined('BASEPATH') or exit('No direct script access allowed');
$user_id = (int) ($this->session->userdata('user_id') ?? 0);
$profile_info = isset($current_user_profile) ? $current_user_profile : (function_exists('profile') ? profile($user_id) : null);

$displayName = !empty($profile_info->fullname)
	? $profile_info->fullname
	: ($this->session->userdata('name') ?: $this->session->userdata('user_name') ?: 'User');
$displayEmail = !empty($profile_info->email)
	? $profile_info->email
	: ($this->session->userdata('email') ?: '');
$displayAvatar = !empty($profile_info->avatar)
	? base_url($profile_info->avatar)
	: base_url('assets/img/user/default_avatar.jpg');

$userType = (int) ($this->session->userdata('user_type') ?? 0);
$roleLabel = $userType === 1 ? lang('admin') : ($userType === 2 ? lang('client') : lang('staff'));

$cache_reset_url = $userType === 2 ? base_url('client/dashboard/reset_cache') : base_url('admin/dashboard/reset_cache');
$profile_url = $userType === 2 ? base_url('client/settings/update_profile') : base_url('admin/settings/update_profile');
$activities_url = $userType === 2 ? base_url('client/settings/activities') : base_url('admin/settings/activities');
?>
<aside
	id="sidebar"
	class="client-sidebar fixed inset-y-0 left-0 z-50 w-64 shrink-0 border-r border-sidebar-border sidebar-wrapper transition-transform duration-300 ease-in-out -translate-x-full md:sticky md:top-0 md:translate-x-0 md:self-start md:h-screen md:overflow-hidden flex flex-col overflow-hidden shadow-xl bg-sidebar">
	<div class="sidebar-search-wrap sticky top-0 z-20 border-b border-sidebar-border/50 bg-sidebar/95 px-3 pt-3 pb-3 backdrop-blur">
		<button
			type="button"
			class="md:hidden ml-auto inline-flex h-9 w-9 items-center justify-center rounded-lg border border-sidebar-border/70 bg-black/5 text-sidebar-foreground hover:bg-black/10 dark:bg-black/20 dark:hover:bg-black/30"
			data-sidebar-close
			aria-label="<?= lang('close_sidebar') ?>">
			<i data-lucide="x" class="h-4 w-4"></i>
		</button>
		<div class="relative group">
			<i data-lucide="search" class="absolute left-3 top-2.5 h-4 w-4 text-muted-foreground group-focus-within:text-indigo-500 transition-colors"></i>
			<input
				type="text"
				data-sidebar-search-input
				placeholder="<?= lang('search_modules') ?>"
				class="w-full bg-black/5 dark:bg-black/20 text-sm text-sidebar-foreground rounded-xl pl-10 pr-4 py-2.5 outline-none focus:ring-2 focus:ring-indigo-500/50 border border-transparent placeholder:text-muted-foreground/70 transition-all" />
		</div>
	</div>

	<div class="sidebar-menu-heading px-4 py-1">
			<p class="text-[11px] font-bold text-muted-foreground/70 uppercase tracking-wider mb-2"><?= lang('main_menu') ?></p>
	</div>

	<nav class="min-h-0 flex-1 overflow-y-auto overflow-x-hidden px-2 pb-2 space-y-1 custom-scrollbar" id="nav-container">
		<?php
		if (!isset($menu_tree) || !is_array($menu_tree)) {
			$menu_tree = [];
		}

		// add new menu into menu tree name is modules ulr admin/my_module with icon fa fa-cubes
		// [id] => 1
        //     [parent_id] => 0
        //     [sort_order] => 0
        //     [label] => dashboard
        //     [route] => admin/dashboard
        //     [icon] => layout-dashboard
        //     [children] => Array
        //         (
        //         )

        //     [is_active] => 1
        //     [is_open] =>

		$hasModulesMenu = false;
		foreach ($menu_tree as $menuItem) {
			if (($menuItem['label'] ?? '') === 'modules') {
				$hasModulesMenu = true;
				break;
			}
		}
		if ((int) $userType !== 2 && !$hasModulesMenu) {
			$menu_tree[] = array(
				'id' => 999,
				'parent_id' => 0,
				'sort_order' => 999,
				'label' => 'modules',
				'route' => 'admin/my_module',
				'icon' => 'cubes',
				'children' => array(),
				'is_active' => false,
				'is_open' => false,
			);
		}


		?>
		<?php
		if (!function_exists('render_sidebar_items')) {
			function render_sidebar_items($items, $level = 1, $userType = 0)
			{
				foreach ($items as $item) {
					if ((int) $userType === 2 && (($item['label'] ?? '') === 'modules' || strpos((string) ($item['route'] ?? ''), 'admin/my_module') === 0)) {
						continue;
					}
					if (($item['label'] ?? '') === 'tickets' && (int) $userType === 2) {
						$item['children'] = [];
					}
					$hasChildren = !empty($item['children']);
					$link = $hasChildren ? 'javascript:void(0);' : base_url($item['route']);
					$label = lang($item['label']);

					$isActive = !empty($item['is_active']);
					$isOpen = !empty($item['is_open']);
					$activeClass = $isActive ? 'nav-item-active' : 'text-sidebar-foreground';
					$chevronRotate = $isOpen ? 'rotate-180' : '';
					$submenuHidden = $isOpen ? '' : 'hidden';

					$iconName = normalize_lucide_icon(isset($item['icon']) ? $item['icon'] : '', 'circle');
		?>
					<div class="rounded-lg transition-all duration-200 <?= $activeClass ?>" data-level="<?= $level ?>" data-sidebar-item>
						<a
							href="<?= $link ?>"
							<?php if ($hasChildren): ?>
							onclick="toggleSubmenu('<?= $item['id'] ?>')"
							<?php endif; ?>
							class="sidebar-nav-link w-full !flex items-center justify-between px-3 py-2 text-menu font-medium group rounded-lg hover:bg-black/5 dark:hover:bg-white/5"
							data-menu-id="<?= $item['id'] ?>"
							data-tooltip="<?= html_escape($label) ?>"
							data-placement="right">
							<div class="flex items-center min-w-0">
								<i data-lucide="<?= html_escape($iconName) ?>" class="sidebar-nav-icon mr-3 h-4 w-4 text-gray-400 dark:group-hover:text-white transition-colors <?= $isActive ? 'text-violet-500' : '' ?>"></i>
								<span class="sidebar-nav-text truncate"><?= $label ?></span>
							</div>
							<?php if ($hasChildren): ?>
								<i data-lucide="chevron-down" class="sidebar-nav-chevron h-4 w-4 transition-transform duration-200 text-gray-400 <?= $chevronRotate ?>"></i>
							<?php endif; ?>
						</a>
						<?php if ($hasChildren): ?>
							<div class="sidebar-submenu ml-4 border-l border-white/10 pl-2 <?= $submenuHidden ?>" data-submenu="<?= $item['id'] ?>" data-default-hidden="<?= $isOpen ? '0' : '1' ?>" data-level="<?= $level ?>">
								<?php render_sidebar_items($item['children'], $level + 1, $userType); ?>
							</div>
						<?php endif; ?>
					</div>
		<?php
				}
			}
		}

		render_sidebar_items($menu_tree, 1, $userType);
		?>
	</nav>

	<div class="sidebar-profile-wrap relative mt-auto border-t border-sidebar-border/50 bg-sidebar/95 px-3 py-3 backdrop-blur">
		<button
			type="button"
			id="sidebar-profile-toggle"
			class="sidebar-profile-main flex w-full items-center rounded-2xl border border-sidebar-border/60 bg-white/70 px-3 py-2.5 shadow-sm transition-colors dark:bg-slate-900/50"
			aria-expanded="false">
			<div class="sidebar-profile-avatar relative flex h-9 w-9 shrink-0 items-center justify-center overflow-hidden rounded-full border-2 border-sidebar-background bg-gradient-to-tr from-blue-500 to-cyan-400 text-sm font-bold text-white">
				<img src="<?= $displayAvatar ?>" alt="<?= html_escape($displayName) ?>" class="h-full w-full object-cover">
				<span class="absolute bottom-0 right-0 h-2.5 w-2.5 rounded-full border-2 border-sidebar-background bg-emerald-500"></span>
			</div>
			<div class="sidebar-profile-meta ml-3 min-w-0 text-left overflow-hidden">
				<p class="truncate text-sm font-semibold text-sidebar-foreground"><?= html_escape($displayName) ?></p>
				<p class="truncate text-xs text-muted-foreground"><?= html_escape($displayEmail ?: $roleLabel) ?></p>
			</div>
			<i data-lucide="chevrons-up-down" class="sidebar-profile-chevron ml-auto h-4 w-4 text-muted-foreground"></i>
		</button>

		<div id="sidebar-profile-menu" class="sidebar-profile-menu hidden absolute bottom-full left-3 right-3 z-50 mb-2 rounded-xl border border-border bg-card p-2 shadow-xl">
			<a href="<?= $profile_url ?>" class="flex items-center gap-2 rounded-lg px-3 py-2 text-sm text-foreground hover:bg-muted">
				<i data-lucide="user-round" class="h-4 w-4"></i>
				<span><?= lang('update_profile') ?></span>
			</a>
			<a href="<?= $activities_url ?>" class="flex items-center gap-2 rounded-lg px-3 py-2 text-sm text-foreground hover:bg-muted">
				<i data-lucide="activity" class="h-4 w-4"></i>
				<span><?= lang('activities') ?></span>
			</a>
			<a href="<?= $cache_reset_url ?>" class="flex items-center gap-2 rounded-lg px-3 py-2 text-sm text-foreground hover:bg-muted" onclick="return confirm(<?= json_encode(lang('reset_all_cache_now')) ?>)">
				<i data-lucide="refresh-cw" class="h-4 w-4"></i>
				<span><?= lang('reset_cache') ?></span>
			</a>
			<a href="<?= base_url('login/logout') ?>" class="flex items-center gap-2 rounded-lg px-3 py-2 text-sm text-foreground hover:bg-muted">
				<i data-lucide="log-out" class="h-4 w-4"></i>
				<span><?= lang('logout') ?></span>
			</a>
		</div>
	</div>
</aside>

<div id="sidebar-backdrop" class="fixed inset-0 bg-black/60 backdrop-blur-sm z-40 hidden md:hidden transition-opacity duration-300"></div>

<script>
	(function() {
		var nav = document.getElementById('nav-container');
		if (!nav) return;
		nav.addEventListener('mouseenter', function() {
			nav.classList.add('show-scrollbar');
		});
		nav.addEventListener('mouseleave', function() {
			nav.classList.remove('show-scrollbar');
		});
	})();
</script>
