<?php
// Determine locale first
$currentLocale = $_SESSION['lang'] ?? 'vn';

// Force reload messages with correct locale
require_once __DIR__ . '/config/messages.php';
$messages = load_messages($currentLocale);

$headerUsername = $username ?? null;
$headerInitials = $userInitials ?? null;

if (!is_string($headerUsername) || $headerUsername === '' || !is_string($headerInitials) || $headerInitials === '') {
	// Don't override currentLocale - it's already set at the top
	
	// Get name based on language
	$rawName = '';
	$username = $_SESSION['user']['username'] ?? '';
	
	if ($currentLocale === 'eng' && !empty($_SESSION['user']['name'])) {
		$rawName = $_SESSION['user']['name'];
	} elseif (!empty($_SESSION['user']['hoten'])) {
		$rawName = $_SESSION['user']['hoten'];
	} else {
		$rawName = $username;
	}
	
	// Don't prepend username to the name - show only the actual name
	
	$headerUsername = htmlspecialchars($rawName, ENT_QUOTES, 'UTF-8');
	
	// Use employee code (username) for avatar instead of name initials
	$employeeCode = $_SESSION['user']['username'] ?? '';
	if ($employeeCode === '') {
		$employeeCode = '00';
	}
	$headerInitials = htmlspecialchars($employeeCode, ENT_QUOTES, 'UTF-8');
} else {
	$headerUsername = (string) $headerUsername;
	$headerInitials = (string) $headerInitials;
}

$displayUsername = htmlspecialchars(htmlspecialchars_decode($headerUsername, ENT_QUOTES), ENT_QUOTES, 'UTF-8');
$displayInitials = htmlspecialchars(htmlspecialchars_decode($headerInitials, ENT_QUOTES), ENT_QUOTES, 'UTF-8');
// Get role based on permission from database

$toggleCollapseLabel = htmlspecialchars($messages['control_header_toggle_collapse'], ENT_QUOTES, 'UTF-8');
$toggleExpandLabel = htmlspecialchars($messages['control_header_toggle_expand'], ENT_QUOTES, 'UTF-8');

$headerRole = '';
$permissionId = $_SESSION['user']['permisson'] ?? 0;

if ($currentLocale === 'eng' && !empty($_SESSION['user']['permisson_name_eng'])) {
	$headerRole = htmlspecialchars($_SESSION['user']['permisson_name_eng'], ENT_QUOTES, 'UTF-8');
} elseif (!empty($_SESSION['user']['permisson_name_vn'])) {
	$headerRole = htmlspecialchars($_SESSION['user']['permisson_name_vn'], ENT_QUOTES, 'UTF-8');
} else {
	$headerRole = htmlspecialchars($messages['control_header_role'] ?? 'Chưa xác định', ENT_QUOTES, 'UTF-8');
}

// Add CSS class based on permission level
$permissionClass = 'permission-' . $permissionId;
$logoutText = htmlspecialchars($messages['control_header_logout'], ENT_QUOTES, 'UTF-8');
$profileText = htmlspecialchars($messages['control_header_profile'], ENT_QUOTES, 'UTF-8');
$changePasswordText = htmlspecialchars($messages['control_header_change_password'], ENT_QUOTES, 'UTF-8');
$notificationsText = htmlspecialchars($messages['control_header_notifications'], ENT_QUOTES, 'UTF-8');
$userMenuText = htmlspecialchars($messages['control_header_user_menu'], ENT_QUOTES, 'UTF-8');
?>
<header class="dashboard-topbar">
	<button class="topbar-menu" type="button"
		data-sidebar-toggle="true"
		data-label-collapse="<?= $toggleCollapseLabel ?>"
		data-label-expand="<?= $toggleExpandLabel ?>"
		aria-expanded="true"
		aria-label="<?= $toggleCollapseLabel ?>"
		title="<?= $toggleCollapseLabel ?>">
		<span></span><span></span><span></span>
	</button>
	<div class="topbar-user">
		<div class="user-avatar"><?= $displayInitials ?></div>
		<div class="user-meta">
			<strong><?= $displayUsername ?></strong>
			<span class="user-role <?= $permissionClass ?>"><?= $headerRole ?></span>
		</div>
	</div>
	
	<!-- Notifications Button -->
	<button class="topbar-notifications" type="button" 
		aria-label="<?= $notificationsText ?>" 
		title="<?= $notificationsText ?>">
		<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
			<path d="M18 8A6 6 0 0 0 6 8c0 7-3 9-3 9h18s-3-2-3-9"></path>
			<path d="M13.73 21a2 2 0 0 1-3.46 0"></path>
		</svg>
		<span class="notification-badge">3</span>
	</button>
	
	<!-- User Actions Dropdown -->
	<div class="topbar-user-actions">
		<button class="user-actions-toggle" type="button" 
			aria-label="<?= $userMenuText ?>" 
			title="<?= $userMenuText ?>">
			<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
				<circle cx="12" cy="12" r="1"></circle>
				<circle cx="12" cy="5" r="1"></circle>
				<circle cx="12" cy="19" r="1"></circle>
			</svg>
		</button>
		<div class="user-actions-dropdown">
			<a href="#" class="dropdown-item">
				<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
					<path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"></path>
					<circle cx="12" cy="7" r="4"></circle>
				</svg>
				<span><?= $profileText ?></span>
			</a>
			<a href="#" class="dropdown-item">
				<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
					<rect x="3" y="11" width="18" height="11" rx="2" ry="2"></rect>
					<circle cx="12" cy="16" r="1"></circle>
					<path d="M7 11V7a5 5 0 0 1 10 0v4"></path>
				</svg>
				<span><?= $changePasswordText ?></span>
			</a>
			<div class="dropdown-divider"></div>
			<form method="post" action="logout.php" class="dropdown-form">
				<button class="dropdown-item logout-item" type="submit">
					<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2">
						<path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"></path>
						<polyline points="16,17 21,12 16,7"></polyline>
						<line x1="21" y1="12" x2="9" y2="12"></line>
					</svg>
					<span><?= $logoutText ?></span>
				</button>
			</form>
		</div>
	</div>
</header>
<script>
(function () {
	const root = document.body;
	const toggle = document.querySelector('[data-sidebar-toggle]');
	if (!root || !toggle) {
		return;
	}

	const collapsedClass = 'sidebar-collapsed';
	const storageKey = 'luna.sidebarCollapsed';
	const collapseLabel = toggle.dataset.labelCollapse || '';
	const expandLabel = toggle.dataset.labelExpand || collapseLabel;

	const applyState = (isCollapsed) => {
		toggle.setAttribute('aria-expanded', String(!isCollapsed));
		const label = isCollapsed ? expandLabel : collapseLabel;
		toggle.setAttribute('aria-label', label);
		toggle.setAttribute('title', label);
		toggle.classList.toggle('is-collapsed', isCollapsed);
	};

	let shouldCollapse = false;
	try {
		shouldCollapse = window.localStorage.getItem(storageKey) === '1';
	} catch (error) {
		shouldCollapse = false;
	}

	if (shouldCollapse) {
		root.classList.add(collapsedClass);
	}

	applyState(root.classList.contains(collapsedClass));

	toggle.addEventListener('click', () => {
		const isCollapsed = root.classList.toggle(collapsedClass);
		applyState(isCollapsed);
		try {
			window.localStorage.setItem(storageKey, isCollapsed ? '1' : '0');
		} catch (error) {
			// ignore persistence errors
		}
	});
})();

// User Actions Dropdown
(function () {
	const userActionsToggle = document.querySelector('.user-actions-toggle');
	const userActionsDropdown = document.querySelector('.user-actions-dropdown');
	
	if (!userActionsToggle || !userActionsDropdown) {
		return;
	}
	
	let isOpen = false;
	
	const updateDropdownPosition = () => {
		const toggleRect = userActionsToggle.getBoundingClientRect();
		const dropdownHeight = 200; // Approximate height
		const viewportHeight = window.innerHeight;
		
		// Calculate position
		let top = toggleRect.bottom + 8;
		let right = window.innerWidth - toggleRect.right;
		
		// Check if dropdown would go off screen
		if (top + dropdownHeight > viewportHeight) {
			top = toggleRect.top - dropdownHeight - 8;
		}
		
		// Ensure minimum distance from edges
		if (right < 20) {
			right = 20;
		}
		
		userActionsDropdown.style.top = top + 'px';
		userActionsDropdown.style.right = right + 'px';
	};
	
	const toggleDropdown = () => {
		isOpen = !isOpen;
		if (isOpen) {
			updateDropdownPosition();
		}
		userActionsDropdown.classList.toggle('show', isOpen);
		userActionsToggle.setAttribute('aria-expanded', String(isOpen));
	};
	
	const closeDropdown = () => {
		isOpen = false;
		userActionsDropdown.classList.remove('show');
		userActionsToggle.setAttribute('aria-expanded', 'false');
	};
	
	userActionsToggle.addEventListener('click', (e) => {
		e.stopPropagation();
		toggleDropdown();
	});
	
	// Close dropdown when clicking outside
	document.addEventListener('click', (e) => {
		if (!userActionsToggle.contains(e.target) && !userActionsDropdown.contains(e.target)) {
			closeDropdown();
		}
	});
	
	// Close dropdown on escape key
	document.addEventListener('keydown', (e) => {
		if (e.key === 'Escape' && isOpen) {
			closeDropdown();
		}
	});
	
	// Update position on window resize
	window.addEventListener('resize', () => {
		if (isOpen) {
			updateDropdownPosition();
		}
	});
})();
</script>




