<?php

use function PHPUnit\Framework\isEmpty;
$uri = service('request')->getUri();
$uri_segments = $uri->getSegments();

// Build mega menu banner image map
$_megaMenuBanners = [];
$_megaMenuBannersMobile = [];
$_db = \Config\Database::connect();
$_bannerRows = $_db->query("
	SELECT data, media_web, media_mobile
	FROM epos_cms
	WHERE type='mega_menu_banner' AND deleted=0 AND active=1
	ORDER BY id
")->getResultArray();
foreach ($_bannerRows as $_br) {
	$_data = json_decode($_br['data'], true);
	$_mediaWeb = json_decode($_br['media_web'], true);
	$_mediaMobile = json_decode($_br['media_mobile'], true);
	if (!empty($_data['top_cat_id'])) {
		$_catId = $_data['top_cat_id'];
		if (!isset($_megaMenuBanners[$_catId]) && !empty($_mediaWeb['upload_file'])) {
			$_megaMenuBanners[$_catId] = env('app.uploads_baseurl') . '/' . $_mediaWeb['upload_file'];
		}
		if (!isset($_megaMenuBannersMobile[$_catId]) && !empty($_mediaMobile['upload_file'])) {
			$_megaMenuBannersMobile[$_catId] = env('app.uploads_baseurl') . '/' . $_mediaMobile['upload_file'];
		}
	}
}

if(empty($user_info)) {
	$top_menus = [
		['id'=>'home',   'icon' => 'bi-house-fill',   'label' => 'Home',          'url' => '/home',                 'active'=>$uri_segments[0] == 'home'],
    	['id'=>'branch', 'icon' => 'bi-geo-alt-fill', 'label' => empty($branchName) ? 
													  'Select Branch' : 
													  $branchName, 				  'url' => '/myaccount/sel_branch', 'active'=>count($uri_segments) > 1 && $uri_segments[1] == 'sel_branch'],
		['id'=>'login',  'icon' => 'bi-person-fill',  'label' => 'Log In',        'url' => '/login',                'active'=>$uri_segments[0] == 'login'],
	];
	$logon_user_menues = [];
} else {
	$top_menus = [];

	$allowed_module_ids = array_map(function($module) {
		return $module['module_id'];
	}, $allowed_modules);

	if(in_array('home', $allowed_module_ids)) 
		$top_menus[] = ['id'=>'home', 'icon' => 'bi-house-fill', 'label' => 'Home', 'url' => '/home', 'active'=>$uri_segments[0] == 'home'];
	if(in_array('products', $allowed_module_ids)) 
		$top_menus[] = ['id'=>'products', 'icon' => 'bi-list-ul', 'label' => 'Products', 'url' => '/products', 'active'=>$uri_segments[0] == 'products'];
	if(in_array('seasonal_presell', haystack: $allowed_module_ids))
		$top_menus[] = ['id'=>'presell', 'icon' => 'bi-tag-fill', 'label' => 'Seasonal Presell', 'url' => '/seasonal_presell', 'active'=>$uri_segments[0]=='seasonal_presell'];
	if(in_array('promos', $allowed_module_ids)) 
		$top_menus[] = ['id'=>'promos', 'icon' => 'bi-tag-fill', 'label' => 'Promos', 'url' => '/promos', 'active'=>$uri_segments[0] == 'promos'];
	if(in_array('favorites', $allowed_module_ids)) 
		$top_menus[] = ['id'=>'my_favorite', 'icon' => 'bi-heart', 'label' => 'Favourite', 'url' => '/favorites', 'active'=>$uri_segments[0] == 'favorites'];
	if(in_array('orders', $allowed_module_ids)) 
		$top_menus[] = ['id'=>'my_cart', 'icon' => 'bi-cart3', 'label' => 'Empty', 'label_class'=>'cart-amount', 'active'=>$uri_segments[0] == 'orders'];
	if(in_array('employees', $allowed_module_ids))
		$top_menus[] = ['id'=>'employees', 'icon'=>'bi-person-fill', 'label'=>'Users', 'url'=>'/employees', 'active' => $uri_segments[0] == 'employees'];
	// Collection/Delivery toggle — only for users with both capabilities
	$canDeliver = session()->get('can_deliver');
	$canCollect = session()->get('can_collect');
	$orderMode = session()->get('order_mode') ?? 'delivery';
	if ($canDeliver && $canCollect) {
		$modeIcon = ($orderMode === 'collection') ? 'bi-bag-fill' : 'bi-truck';
		$modeLabel = ($orderMode === 'collection') ? 'Collection' : 'Delivery';
		$top_menus[] = ['id'=>'order_mode', 'icon'=>$modeIcon, 'label'=>$modeLabel, 'url'=>'#', 'active'=>false];
	}
	if(in_array('branch', $allowed_module_ids))
		$top_menus[] = ['id'=>'branch', 'icon'=>'bi-geo-alt-fill', 'label'=>empty($branchName) ? 'Select Branch' : $branchName, 'url'=>'/myaccount/sel_allocated_branch', 'active' => count($uri_segments) > 1 && $uri_segments[1] == 'sel_branch'];

	$logon_user_menues = LOGON_USER_MENUES;
	// if(empty($credit_account)) {
	// 	unset($logon_user_menues['my_account']); //1
	// }
	// if(!in_array('orders', $allowed_module_ids)) {
	// 	unset($logon_user_menues['my_orders']); //2
	// }
	// if(empty($credit_account)) {
	// 	unset($logon_user_menues['my_order_history']);//3
	// }
	// if(empty($credit_account)) {
	// 	unset($logon_user_menues['my_invoice_history']);//4
	// }
	// if(empty($credit_account)) {
	// 	unset($logon_user_menues['credit_ledger']);//5
	// }
	if(!in_array('employees', $allowed_module_ids)) {
		unset($logon_user_menues['my_orders']); //2
	}
	if(!in_array('employees', $allowed_module_ids)) {
		unset($logon_user_menues['add_employee']); //2
	}
	if(!in_array('employees', $allowed_module_ids)) {
		unset($logon_user_menues['docusign_list']); //2
	}
}

$active_categories = [];
if(!empty($category_id) && $category_id > 0) {
	foreach($top_categories as $top_category) { 
		if($top_category['category_id'] == $category_id) {
			$active_categories['top'] = $top_category;
			break;
		} 
		
		foreach($top_category['sub_categories'] as $sub_category) {
			if($sub_category['category_id'] == $category_id) {
				$active_categories['top'] = $top_category;
				$active_categories['sub'] = $sub_category;
				break;
			}
		}

		if(!empty($active_category)) break;
	}
}
?>

<!-- Header START -->
<header class="">
	<input type="hidden" name="category_id" id="category_id" value="<?= $category_id ?? 0 ?>" />
    <input type="hidden" id="view_mode" name="view_mode" value="<?= $view_mode ?? 'grid' ?>" />

	<div class="position-fixed top-0 start-0 end-0 d-flex justify-content-center d-none" id="ajax-call-indicator">
		<div class="spinner-border text-primary spinner-border-sm">
		</div>
		<div style="background: #00000000; width: 100%; height: 100vh; z-index: 10; position: absolute; top: 40px; "></div>
	</div>

	<?= view("v2/partials/header_ribbon") ?>

	<div class="header-logo d-flex align-items-center">
		<!-- Logo START -->
		<a class="logo-image" href="/">
			<img class="logo" src="/assets/images/uws-logo.jpg" alt="logo">
		</a>
		<!-- Logo END -->

		<div class="search-product-header flex-fill">
			<?= view('v2/components/SearchInput', ['name'=>'search_product', 'id'=>'search0', 'value'=>$search0 ?? '', 'placeholder' => 'Search Products']) ?>
		</div>

		<div class="header-logo-mainmenu mobile d-flex d-xl-none align-items-center">
			<div class="">
				<i class="bi bi-tags toggle-sidebar" data-toggle-target="#category-sidebar"></i>
			</div>
			<?php if(!empty($user_info)) { ?>
			<div class="d-flex flex-column align-items-center ms-2">
				<a href="/orders/recent"><i class="bi bi-cart3"></i></a>
			</div>
			<?php } ?>
			<div class="ms-2">
				<i class="bi bi-list toggle-sidebar" data-toggle-target="#main-sidebar-menu"></i>
			</div>
		</div>

		<div class="header-logo-mainmenu pc align-items-center d-none d-xl-flex ps-4 pe-2">
			<div class="top-menu d-flex align-items-center">
				<?php foreach($top_menus as $tm) { 
					if($tm['id'] == 'my_cart') { 
				?>
					<a
						class="one-top-menu my-cart d-flex flex-column align-items-center justify-content-center toggle-sidebar <?= $tm['class'] ?? '' ?> <?= $tm['active'] ? 'active' : '' ?> cursor-pointer"
						data-toggle-target="#my-cart-sidebar"
					>
						<i class="bi <?= $tm['icon'] ?>"></i>
						<label class="<?= $tm['label_class'] ?? '' ?>"><?= $tm['label'] ?></label>
					</a>
				<?php } elseif($tm['id'] == 'order_mode') { ?>
					<a
						href="#"
						class="one-top-menu d-flex flex-column align-items-center justify-content-center cursor-pointer"
						onclick="toggleOrderMode(event)"
						title="Click to switch between Collection and Delivery"
					>
						<i id="order-mode-icon" class="bi <?= $tm['icon'] ?>"></i>
						<label id="order-mode-label"><?= $tm['label'] ?></label>
					</a>
				<?php } else { ?>
					<a
						href="<?= $tm['url'] ?? '#' ?>"
						class="one-top-menu d-flex flex-column align-items-center justify-content-center <?= $tm['class'] ?? '' ?> <?= $tm['active'] ? 'active' : '' ?>"
					>
						<i class="bi <?= $tm['icon'] ?>"></i>
						<label class="<?= $tm['label_class'] ?? '' ?>"><?= $tm['label'] ?></label>
					</a>
				<?php } } ?>
			</div>

			<?php if(!empty($user_info)) { ?>
			<div class="ms-2 d-flex align-items-center">
				<a class="nav-link dropdown-toggle p-2" 
					href="#" 
					data-bs-auto-close="outside" 
					data-bs-toggle="dropdown" 
					aria-haspopup="true" 
					aria-expanded="false"
					style="text-decoration: none;"
				>
					<img src='/assets/images/icons/png/profile-boy.png' style="width: 30px; height:30px;" />
					<span class="balance ms-2">Account</span>
				</a>
				<div class="logon-user-menu dropdown-menu dropdown-menu-size-lg p-3">
					<ul class="list-unstyled">
					<?php foreach($logon_user_menues as $menu) { ?>
						<li> <a class="dropdown-item" href="<?= $menu['url'] ?>">
							<img src="<?= $menu['icon'] ?>" />
							<span class="ms-1"><?= $menu['label'] ?></span>
						</a> </li>
					<?php } ?>
					</ul>
				</div>
			</div>
			<?php } ?>
		</div>
	</div>

	<!-- Nav START -->
	<nav class="navbar navbar-expand-xl d-none d-xl-block">
		<!-- Main navbar START -->
		<div class="navbar-collapse collapse" id="navbarCollapse">
			<ul class="navbar-nav navbar-nav-scroll dropdown-hover mx-auto">
				<?php 
					$index = 0;
					foreach($top_categories as $top_category) { 
						$index++;
				?>
				<li class="nav-item dropdown">
					<a class="nav-link dropdown-toggle category-link <?= !empty($active_categories['top']) && $active_categories['top']['category_id'] == $top_category['category_id'] ? 'active' : '' ?>"
						href="#"
						data-bs-auto-close="outside"
						data-bs-toggle="dropdown"
						aria-haspopup="true"
						aria-expanded="false"
						data-category-id="<?= $top_category['category_id'] ?>"
					>
						<?= $top_category['alias'] ?>
					</a>
						<div class="dropdown-menu mega-menu <?= !empty($_megaMenuBanners[$top_category['category_id']]) ? 'has-banner' : '' ?> p-3">
						<div class="d-flex">
							<div class="mega-menu-subcategories flex-grow-1">
								<a class="dropdown-item mega-menu-all category-link" href="#" data-category-id="<?= $top_category['category_id'] ?>">
									All <?= $top_category['alias'] ?>
								</a>
								<div class="mega-menu-columns">
									<?php foreach($top_category['sub_categories'] as $sub_category) { ?>
										<a class="dropdown-item category-link <?= !empty($active_categories['sub']) && $active_categories['sub']['category_id'] == $sub_category['category_id'] ? 'active' : '' ?>"
											href="#"
											data-category-id="<?= $sub_category['category_id'] ?>"
										>
											<?= $sub_category['category_name'] ?>
										</a>
									<?php } ?>
								</div>
							</div>
							<?php if (!empty($_megaMenuBanners[$top_category['category_id']])) { ?>
							<div class="mega-menu-banner">
								<img src="<?= $_megaMenuBanners[$top_category['category_id']] ?>" alt="<?= $top_category['alias'] ?>" />
							</div>
							<?php } ?>
						</div>
					</div>
				</li>
				<?php } ?>
			</ul>
		</div>
		<!-- Main navbar END -->
	</nav>
	<!-- Logo Nav END -->
</header>

<?= view("v2/partials/main_sidebar") ?>
<?= view("v2/partials/category_sidebar", ['active_categories' => $active_categories, 'top_categories' => $top_categories, '_megaMenuBanners' => $_megaMenuBannersMobile]) ?>

<!-- Header END -->
<script>
document.querySelectorAll('.mega-menu').forEach(function(menu) {
	menu.closest('.dropdown').addEventListener('shown.bs.dropdown', function() {
		menu.style.left = '';
		menu.style.right = '';
		var rect = menu.getBoundingClientRect();
		if (rect.right > window.innerWidth) {
			menu.style.left = 'auto';
			menu.style.right = '0';
		} else {
			menu.style.left = '0';
			menu.style.right = 'auto';
		}
	});
});

function toggleOrderMode(e) {
	e.preventDefault();
	if (window.orderModeToggleLocked) {
		if (window.orderModeLockedMessage) {
			var icon = document.getElementById('order-mode-dialog-icon');
			var msg = document.getElementById('order-mode-dialog-msg');
			var dialog = document.getElementById('order-mode-dialog');
			var btn = dialog.querySelector('.btn-ok');
			var cancelBtn = dialog.querySelector('.btn-cancel');
			icon.innerHTML = '<i class="bi bi-info-circle-fill"></i>';
			icon.style.color = '#e65100';
			msg.textContent = window.orderModeLockedMessage;
			btn.textContent = 'OK';
			btn.style.backgroundColor = '#e65100';
			btn.style.borderColor = '#e65100';
			btn.style.color = '#fff';
			cancelBtn.style.display = 'none';
			var modal = new bootstrap.Modal(dialog);
			btn.onclick = function() { modal.hide(); };
			modal.show();
		}
		return;
	}
	var currentLabel = document.getElementById('order-mode-label').textContent.trim().toLowerCase();
	var currentMode = currentLabel === 'collection' ? 'collection' : 'delivery';
	var targetMode = currentMode === 'collection' ? 'delivery' : 'collection';
	showOrderModeDialog(currentMode, targetMode, function() {
		fetch('/myaccount/toggle_order_mode', {method: 'POST', headers: {'X-Requested-With': 'XMLHttpRequest'}})
			.then(r => r.json())
			.then(data => {
				if (data.order_mode) {
					var icon = document.getElementById('order-mode-icon');
					var label = document.getElementById('order-mode-label');
					if (data.order_mode === 'collection') {
						icon.className = 'bi bi-bag-fill';
						label.textContent = 'Collection';
					} else {
						icon.className = 'bi bi-truck';
						label.textContent = 'Delivery';
					}
					var params = new URLSearchParams(window.location.search);
					if (params.has('order_type')) {
						params.set('order_type', data.order_mode);
						window.location.search = params.toString();
					} else {
						window.location.reload();
					}
				}
			});
	});
}

function showOrderModeDialog(currentMode, targetMode, onConfirm) {
	var isTarget = targetMode === 'collection';
	var icon = document.getElementById('order-mode-dialog-icon');
	var msg = document.getElementById('order-mode-dialog-msg');
	var dialog = document.getElementById('order-mode-dialog');
	var btn = dialog.querySelector('.btn-ok');
	var cancelBtn = dialog.querySelector('.btn-cancel');

	icon.innerHTML = '<i class="bi ' + (isTarget ? 'bi-bag-fill' : 'bi-truck') + '"></i>';
	icon.style.color = isTarget ? '#2e7d32' : '#1565c0';
	msg.textContent = 'You are now seeing ' + currentMode + ' pricing and offers, switch to ' + targetMode + ' pricing?';
	btn.textContent = 'Yes';
	btn.style.backgroundColor = isTarget ? '#2e7d32' : '#1565c0';
	btn.style.borderColor = isTarget ? '#2e7d32' : '#1565c0';
	btn.style.color = '#fff';
	cancelBtn.style.display = 'inline-block';

	var modal = new bootstrap.Modal(dialog);
	btn.onclick = function() {
		modal.hide();
		if (onConfirm) onConfirm();
	};
	cancelBtn.onclick = function() { modal.hide(); };
	modal.show();
}

function showOrderModeNotification(mode, onClose) {
	var isCollection = mode === 'collection';
	var icon = document.getElementById('order-mode-dialog-icon');
	var msg = document.getElementById('order-mode-dialog-msg');
	var dialog = document.getElementById('order-mode-dialog');
	var btn = dialog.querySelector('.btn-ok');
	var cancelBtn = dialog.querySelector('.btn-cancel');

	icon.innerHTML = '<i class="bi ' + (isCollection ? 'bi-bag-fill' : 'bi-truck') + '"></i>';
	icon.style.color = isCollection ? '#2e7d32' : '#1565c0';
	msg.textContent = 'You are now seeing ' + mode + ' pricing and offers';
	btn.textContent = 'OK';
	btn.style.backgroundColor = isCollection ? '#2e7d32' : '#1565c0';
	btn.style.borderColor = isCollection ? '#2e7d32' : '#1565c0';
	btn.style.color = '#fff';
	cancelBtn.style.display = 'none';

	var modal = new bootstrap.Modal(dialog);
	btn.onclick = function() {
		modal.hide();
		if (onClose) onClose();
	};
	dialog.addEventListener('hidden.bs.modal', function handler() {
		dialog.removeEventListener('hidden.bs.modal', handler);
		if (onClose) onClose();
		onClose = null;
	});
	modal.show();
}
</script>

<div id="order-mode-dialog" class="modal fade" tabindex="-1" aria-hidden="true">
	<div class="modal-dialog modal-dialog-centered modal-sm">
		<div class="modal-content" style="border-radius: 12px; overflow: hidden; border: none; box-shadow: 0 8px 30px rgba(0,0,0,0.15);">
			<div class="modal-body text-center px-4 py-4">
				<div id="order-mode-dialog-icon" style="font-size: 2.5rem; margin-bottom: 0.5rem;"></div>
				<p id="order-mode-dialog-msg" style="font-size: 1rem; font-weight: 500; color: #333; margin-bottom: 1.25rem;"></p>
				<button type="button" class="btn btn-cancel" style="min-width: 100px; border-radius: 8px; font-weight: 600; padding: 8px 24px; background-color: #e0e0e0; color: #333; border-color: #e0e0e0; margin-right: 8px; display: none;">No</button>
				<button type="button" class="btn btn-ok" style="min-width: 100px; border-radius: 8px; font-weight: 600; padding: 8px 24px;">OK</button>
			</div>
		</div>
	</div>
</div>