<?php
// Prevent direct access when user already authenticated via app shell
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
if (isset($_SESSION['user'])) {
    header('Location: index.php');
    exit;
}
require_once __DIR__ . '/config/messages.php';
$currentLocale = determine_locale();
$messages = load_messages($currentLocale);

$languageOptions = [
	'vn' => [
		'label' => $messages['language_vietnamese'],
		'icon' => 'assets/img/icons/flags/vn.svg',
	],
	'eng' => [
		'label' => $messages['language_english'],
		'icon' => 'assets/img/icons/flags/us.svg',
	],
];

$currentLanguageOption = $languageOptions[$currentLocale] ?? $languageOptions['vn'];
$currentFlagIcon = $currentLanguageOption['icon'];
$currentFlagAlt = $currentLanguageOption['label'];

if (empty($_SESSION['csrf_token'])) {
	$_SESSION['csrf_token'] = bin2hex(random_bytes(32));
}

function flash_pop(string $key): ?string {
	if (!isset($_SESSION['flash'][$key])) {
		return null;
	}
	$value = $_SESSION['flash'][$key];
	unset($_SESSION['flash'][$key]);
	return $value;
}

$flashError = flash_pop('error');
$flashSuccess = flash_pop('success');
?>
<!DOCTYPE html>
<html lang="<?= $currentLocale === 'eng' ? 'en' : 'vi' ?>">
<head>
	<meta charset="utf-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
	<title><?= htmlspecialchars($messages['page_title'], ENT_QUOTES, 'UTF-8') ?></title>
	<link rel="preconnect" href="https://fonts.googleapis.com">
	<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
	<link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&display=swap" rel="stylesheet">
	<link rel="stylesheet" href="assets/css/style.css" />
	<meta name="theme-color" content="#0e252b" />
	<link rel="apple-touch-icon" sizes="180x180" href="assets/img/icons/apple-touch-icon.png" />
	<link rel="icon" type="image/png" sizes="32x32" href="assets/img/icons/favicon-32x32.png" />
	<link rel="icon" type="image/png" sizes="16x16" href="assets/img/icons/favicon-16x16.png" />
	<link rel="manifest" href="assets/img/icons/site.webmanifest" />
	<link rel="shortcut icon" href="assets/img/icons/favicon.ico" />
</head>
<body>
	<div class="bg"></div>
	<main class="container">
		<section class="card">
			<div class="card-header header-center">
				<div class="hero-logo"><img src="assets/img/logo.png" alt="Luna Human Resource Management" /></div>
				<div class="brand-text text-center">
					<h1><?= htmlspecialchars($messages['brand_heading'], ENT_QUOTES, 'UTF-8') ?></h1>
					<p><?= htmlspecialchars($messages['brand_subheading'], ENT_QUOTES, 'UTF-8') ?></p>
				</div>
			</div>

			<?php /* Inline alerts removed; using global toast system instead */ ?>

			<form class="form" method="post" action="modules/auth/login.php" novalidate>
				<input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token'], ENT_QUOTES, 'UTF-8') ?>" />
				<div class="field">
					<label for="employee_code"><?= htmlspecialchars($messages['employee_code_label'], ENT_QUOTES, 'UTF-8') ?></label>
					<div class="input-wrap">
						<input id="employee_code" name="employee_code" type="text" autocomplete="username" placeholder="<?= htmlspecialchars($messages['employee_code_placeholder'], ENT_QUOTES, 'UTF-8') ?>" required />
						<span class="icon icon-user" aria-hidden="true">
							<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" aria-hidden="true">
								<path d="M15.75 6.75a3.75 3.75 0 1 1-7.5 0 3.75 3.75 0 0 1 7.5 0Z" />
								<path d="M4.5 20.25a7.5 7.5 0 0 1 15 0" />
							</svg>
						</span>
					</div>
				</div>
				<div class="field">
					<label for="password"><?= htmlspecialchars($messages['password_label'], ENT_QUOTES, 'UTF-8') ?></label>
					<div class="input-wrap">
						<input id="password" name="password" type="password" autocomplete="current-password" placeholder="<?= htmlspecialchars($messages['password_placeholder'], ENT_QUOTES, 'UTF-8') ?>" required />
						<span class="icon icon-lock" aria-hidden="true">
							<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" aria-hidden="true">
								<path d="M16.5 10.5V6.75a4.5 4.5 0 1 0-9 0V10.5" />
								<path d="M7.5 10.5h9a1.5 1.5 0 0 1 1.5 1.5v6a1.5 1.5 0 0 1-1.5 1.5h-9a1.5 1.5 0 0 1-1.5-1.5v-6a1.5 1.5 0 0 1 1.5-1.5Z" />
								<path d="M12 14.25v2.25" />
							</svg>
						</span>
						<button type="button" class="toggle-pass" aria-label="<?= htmlspecialchars($messages['toggle_password_show'], ENT_QUOTES, 'UTF-8') ?>" title="<?= htmlspecialchars($messages['toggle_password_show'], ENT_QUOTES, 'UTF-8') ?>" data-state="hidden" data-show-label="<?= htmlspecialchars($messages['toggle_password_show'], ENT_QUOTES, 'UTF-8') ?>" data-hide-label="<?= htmlspecialchars($messages['toggle_password_hide'], ENT_QUOTES, 'UTF-8') ?>">
							<span class="visually-hidden"><?= htmlspecialchars($messages['toggle_password_show'], ENT_QUOTES, 'UTF-8') ?></span>
							<svg class="icon-eye icon-eye-open" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" aria-hidden="true">
								<path d="M2.036 12.322a1.012 1.012 0 0 1 0-.644C3.423 7.51 7.272 4.5 12 4.5c4.728 0 8.577 3.01 9.964 7.178a1.012 1.012 0 0 1 0 .644C20.577 16.49 16.728 19.5 12 19.5c-4.728 0-8.577-3.01-9.964-7.178Z" />
								<path d="M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z" />
							</svg>
							<svg class="icon-eye icon-eye-closed" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6" aria-hidden="true">
								<path d="M2.036 12.322a1.012 1.012 0 0 1 0-.644C3.423 7.51 7.272 4.5 12 4.5c4.728 0 8.577 3.01 9.964 7.178a1.012 1.012 0 0 1 0 .644C20.577 16.49 16.728 19.5 12 19.5c-4.728 0-8.577-3.01-9.964-7.178Z" />
								<path d="M15 12a3 3 0 1 1-6 0 3 3 0 0 1 6 0Z" />
								<path d="M4 5l16 16" />
							</svg>
						</button>
					</div>
				</div>
				<div class="actions">
					<button class="btn btn-primary" type="submit"><?= htmlspecialchars($messages['login_button'], ENT_QUOTES, 'UTF-8') ?></button>
					<a class="link" href="#" onclick="return false;"><?= htmlspecialchars($messages['forgot_link'], ENT_QUOTES, 'UTF-8') ?></a>
				</div>
				<!--<p class="hint"><?= $messages['demo_hint'] ?></p>-->
			</form>
			<form method="get" class="language-switch" aria-label="<?= htmlspecialchars($messages['language_label'], ENT_QUOTES, 'UTF-8') ?>">
				<label for="site-language"><?= htmlspecialchars($messages['language_label'], ENT_QUOTES, 'UTF-8') ?></label>
				<div class="custom-select" id="language-custom-select">
					<button style="width: 160px;display: inline-flex;height: 35px;" type="button" class="custom-select-toggle" data-placeholder="<?= htmlspecialchars($currentLanguageOption['label'], ENT_QUOTES, 'UTF-8') ?>">
						<img src="<?= htmlspecialchars($currentFlagIcon, ENT_QUOTES, 'UTF-8') ?>" alt="<?= htmlspecialchars($currentFlagAlt, ENT_QUOTES, 'UTF-8') ?>" height="20" width="28" loading="lazy" style="margin-right: 8px;" />
						<?= htmlspecialchars($currentLanguageOption['label'], ENT_QUOTES, 'UTF-8') ?>
					</button>
					<div class="custom-select-menu" role="listbox">
						<?php foreach ($languageOptions as $code => $option): ?>
							<div class="custom-select-option" role="option" data-value="<?= htmlspecialchars($code, ENT_QUOTES, 'UTF-8') ?>" <?= $code === $currentLocale ? 'class="custom-select-option is-selected"' : 'class="custom-select-option"' ?>>
								<img src="<?= htmlspecialchars($option['icon'], ENT_QUOTES, 'UTF-8') ?>" alt="<?= htmlspecialchars($option['label'], ENT_QUOTES, 'UTF-8') ?>" height="20" width="28" loading="lazy" style="margin-right: 8px;" />
								<?= htmlspecialchars($option['label'], ENT_QUOTES, 'UTF-8') ?>
							</div>
						<?php endforeach; ?>
					</div>
					<input type="hidden" name="lang" id="site-language" value="<?= htmlspecialchars($currentLocale, ENT_QUOTES, 'UTF-8') ?>">
				</div>
			</form>

		</section>
	</main>

    <script>
    window.__MESSAGES__ = <?php echo json_encode($messages, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;
    </script>
    <script src="assets/js/app.js"></script>
    <script>
    // Handle login form with AJAX
    document.addEventListener('DOMContentLoaded', function() {
        var loginForm = document.querySelector('.form[action="modules/auth/login.php"]');
        if (!loginForm) return;
        
        loginForm.addEventListener('submit', function(e) {
            e.preventDefault();
            
            var submitBtn = loginForm.querySelector('button[type="submit"]');
            var originalText = submitBtn ? submitBtn.textContent : '';
            
            // Disable submit button
            if (submitBtn) {
                submitBtn.disabled = true;
                submitBtn.textContent = '<?= htmlspecialchars($messages['loading'] ?? 'Đang xử lý...', ENT_QUOTES, 'UTF-8') ?>';
            }
            
            var formData = new FormData(loginForm);
            
            fetch('modules/auth/login.php', {
                method: 'POST',
                headers: {
                    'X-Requested-With': 'XMLHttpRequest'
                },
                body: formData
            })
            .then(function(response) {
                return response.json();
            })
            .then(function(data) {
                if (data.success) {
                    // Show success message
                    if (typeof window.showToast === 'function' && data.message) {
                        var successTitle = (window.__MESSAGES__ && window.__MESSAGES__['success_notification_title']) ? window.__MESSAGES__['success_notification_title'] : 'THÔNG BÁO';
                        var successWithHeader = '<div class="success-header">' + successTitle + '</div>' + data.message;
                        window.showToast('success', successWithHeader);
                    }
                    // Redirect after short delay
                    setTimeout(function() {
                        window.location.href = data.redirect || 'index.php';
                    }, 500);
                } else {
                    // Show error message
                    if (typeof window.showToast === 'function' && data.message) {
                        var errorTitle = (window.__MESSAGES__ && window.__MESSAGES__['error_notification_title']) ? window.__MESSAGES__['error_notification_title'] : 'THÔNG BÁO';
                        var errorWithHeader = '<div class="error-header">' + errorTitle + '</div>' + data.message;
                        window.showToast('error', errorWithHeader);
                    }
                    // Re-enable submit button
                    if (submitBtn) {
                        submitBtn.disabled = false;
                        submitBtn.textContent = originalText;
                    }
                }
            })
            .catch(function(error) {
                console.error('Login error:', error);
                // Show generic error
                if (typeof window.showToast === 'function') {
                    var errorTitle = (window.__MESSAGES__ && window.__MESSAGES__['error_notification_title']) ? window.__MESSAGES__['error_notification_title'] : 'THÔNG BÁO';
                    var errorMsg = (window.__MESSAGES__ && window.__MESSAGES__['generic_error']) ? window.__MESSAGES__['generic_error'] : 'Đã xảy ra lỗi. Vui lòng thử lại.';
                    var errorWithHeader = '<div class="error-header">' + errorTitle + '</div>' + errorMsg;
                    window.showToast('error', errorWithHeader);
                }
                // Re-enable submit button
                if (submitBtn) {
                    submitBtn.disabled = false;
                    submitBtn.textContent = originalText;
                }
            });
        });
    });
    </script>
    <script>
    (function(){
        var err = <?php echo json_encode($flashError, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;
        var ok = <?php echo json_encode($flashSuccess, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;
        if (typeof window.showToast === 'function') {
            if (ok) { 
                // Add success header like error notifications
                var successTitle = (window.__MESSAGES__ && window.__MESSAGES__['success_notification_title']) ? window.__MESSAGES__['success_notification_title'] : 'THÔNG BÁO';
                var successWithHeader = '<div class="success-header">' + successTitle + '</div>' + ok;
                window.showToast('success', successWithHeader); 
            }
            if (err) { 
                // Add error header like other pages
                var errorTitle = (window.__MESSAGES__ && window.__MESSAGES__['error_notification_title']) ? window.__MESSAGES__['error_notification_title'] : 'THÔNG BÁO';
                var errorWithHeader = '<div class="error-header">' + errorTitle + '</div>' + err;
                window.showToast('error', errorWithHeader); 
            }
        }
    })();
    </script>
    
    <script>
    // Setup custom select for language selector
    function setupLanguageCustomSelect() {
        var custom = document.getElementById('language-custom-select');
        if (!custom) return;
        
        var toggle = custom.querySelector('.custom-select-toggle');
        var menu = custom.querySelector('.custom-select-menu');
        var hidden = document.getElementById('site-language');
        if (!toggle || !menu) return;
        
        var placeholder = toggle.getAttribute('data-placeholder') || 'Chọn ngôn ngữ';
        var closeOnScroll = null; 
        var closeOnResize = null;

        var anchorParent = null; 
        var anchorNext = null; 
        var isPortaled = false;
        
        function mountMenu(){
            if (isPortaled) return;
            anchorParent = menu.parentNode;
            anchorNext = menu.nextSibling;
            document.body.appendChild(menu);
            isPortaled = true;
        }
        
        function unmountMenu(){
            if (!isPortaled) return;
            if (anchorParent) {
                if (anchorNext) { 
                    anchorParent.insertBefore(menu, anchorNext); 
                } else { 
                    anchorParent.appendChild(menu); 
                }
            }
            isPortaled = false;
        }
        
        function positionMenu(){
            var r = toggle.getBoundingClientRect();
            var viewportH = window.innerHeight || document.documentElement.clientHeight;
            var spaceBelow = viewportH - r.bottom - 8; // space from toggle bottom to viewport bottom
            var spaceAbove = r.top - 8;                // space from viewport top to toggle top
            var desiredWidth = Math.round(r.width);
            var left = Math.round(r.left);
            var pad = 12;
            if (left < pad) left = pad;
            if (left + desiredWidth + pad > window.innerWidth) {
                left = Math.max(pad, window.innerWidth - desiredWidth - pad);
            }
            console.log(window.innerWidth);
            // Decide whether to open below or above based on available space
            var openUpwards = true; // Always open upwards on login page
            var maxH;
            if (openUpwards) {
                maxH = Math.max(88, Math.min(220, Math.floor(spaceAbove))); // clamp height to available space above
            } else {
                maxH = Math.max(88, Math.min(220, Math.floor(spaceBelow))); // clamp height to available space below
            }

            menu.style.position = 'fixed';
            menu.style.left = left + 'px';
            menu.style.width = desiredWidth + 'px';
            menu.style.minWidth = desiredWidth + 'px';
            menu.style.maxWidth = desiredWidth + 'px';
            menu.style.maxHeight = maxH + 'px';
            menu.style.zIndex = '2147483000';
            menu.style.display = 'block';
            menu.style.top = openUpwards ? Math.round(r.top - maxH - 6 + 133) + 'px' : Math.round(r.bottom + 6 + 133) + 'px';
            
        }
        
        function clearMenuStyles(){
            menu.style.position = '';
            menu.style.left = '';
            menu.style.top = '';
            menu.style.width = '';
            menu.style.minWidth = '';
            menu.style.maxWidth = '';
            menu.style.maxHeight = '';
            menu.style.zIndex = '';
            menu.style.display = '';
        }
        
        function closeAll(){
            custom.classList.remove('open');
            clearMenuStyles();
            unmountMenu();
            if (closeOnScroll) { 
                window.removeEventListener('scroll', closeOnScroll, true); 
                closeOnScroll = null; 
            }
            if (closeOnResize) { 
                window.removeEventListener('resize', closeOnResize); 
                closeOnResize = null; 
            }
        }

        // Keep menu open when scrolling inside it
        menu.addEventListener('wheel', function(e){ e.stopPropagation(); }, { passive: true });
        menu.addEventListener('touchmove', function(e){ e.stopPropagation(); }, { passive: true });
        menu.addEventListener('mousedown', function(e){ e.stopPropagation(); });

        toggle.addEventListener('click', function(e){
            e.stopPropagation();
            var willOpen = !custom.classList.contains('open');
            custom.classList.toggle('open');
            if (willOpen) {
                mountMenu();
                positionMenu();
                // Ensure the toggle is visible when menu opens (mobile small screens)
                try { toggle.scrollIntoView({ block: 'nearest', behavior: 'smooth' }); } catch(_) {}
                closeOnScroll = function(ev){ 
                    if (menu.contains(ev.target)) return; 
                    closeAll(); 
                };
                closeOnResize = function(){ closeAll(); };
                window.addEventListener('scroll', closeOnScroll, true);
                window.addEventListener('resize', closeOnResize);
            } else {
                closeAll();
            }
        });
        
        menu.addEventListener('click', function(e){
            var opt = e.target.closest('.custom-select-option');
            if (!opt) return;
            e.stopPropagation();
            var value = opt.getAttribute('data-value') || '';
            var label = opt.textContent.trim();
            var flagImg = opt.querySelector('img');
            
            if (hidden) hidden.value = value;
            toggle.textContent = label;
            
            // Update flag icon
            var toggleImg = toggle.querySelector('img');
            if (toggleImg && flagImg) {
                toggleImg.src = flagImg.src;
                toggleImg.alt = flagImg.alt;
            }
            
            var items = menu.querySelectorAll('.custom-select-option');
            items.forEach(function(it){ 
                it.classList.toggle('is-selected', it === opt); 
            });
            
            closeAll();
            
            // Submit form to change language
            var form = custom.closest('form');
            if (form) {
                form.submit();
            }
        });

        // Close on outside click
        document.addEventListener('click', function(e){
            if (!custom.contains(e.target)) {
                closeAll();
            }
        });
    }
    
    // Initialize when DOM is ready
    document.addEventListener('DOMContentLoaded', function() {
        setupLanguageCustomSelect();
    });
    </script>
</body>
</html>


