<?php
if (!defined('LUNA_APP')) {
    define('LUNA_APP', true);
}
if (session_status() === PHP_SESSION_NONE) {
	session_start();
}
require_once __DIR__ . '/config/messages.php';
$messages = load_messages();
// Prepare flash data for pages that use it directly (dashboard). For login page,
// we must not clear flashes here because login.php will read and display them.
$flashData = [
    'success' => $_SESSION['flash']['success'] ?? null,
    'error' => $_SESSION['flash']['error'] ?? null,
];
// Clear flash after reading so it doesn't persist across refresh
if (isset($_SESSION['flash'])) {
    unset($_SESSION['flash']['success'], $_SESSION['flash']['error']);
    if (empty($_SESSION['flash'])) { unset($_SESSION['flash']); }
}

$isLoggedIn = isset($_SESSION['user']);

// Route based on query string
// Simple router via query string
$page = null;
if (isset($_GET['dashboard'])) {
    $page = 'dashboard';
} elseif (isset($_GET['company'])) {
    $page = 'company';
} elseif (isset($_GET['category'])) {
    $page = 'category';
} elseif (isset($_GET['outgoing'])) {
    $page = 'outgoing';
} elseif (isset($_GET['incoming'])) {
    // Check if it's the log viewer
    if ($_GET['incoming'] === 'log') {
        $page = 'incoming_log';
    } else {
        $page = 'incoming';
    }
} elseif (isset($_GET['zalo'])) {
    // Check if it's the log viewer
    if ($_GET['zalo'] === 'log') {
        $page = 'zalo_log';
    } else {
        $page = 'zalo';
    }
} elseif (isset($_GET['attendance'])) {
    $page = 'attendance';
} elseif (isset($_GET['profile'])) {
    $page = 'profile';
}

if (!$isLoggedIn) {
	// Not logged in -> show login UI
	require __DIR__ . '/login.php';
	exit;
}

// Logged in: render shell and include sections
?>
<!DOCTYPE html>
<html lang="vi">
<head>
	<meta charset="utf-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />
	<title>Luna HR</title>
	<style>
	/* Critical CSS to prevent white box flash - must be inline in head */
	html, body {
		margin: 0;
		padding: 0;
		background: linear-gradient(170deg, #07181f 0%, #0e252b 45%, #143742 100%) !important;
		min-height: 100vh;
	}
	#page-loader {
		display: none !important;
		visibility: hidden !important;
		opacity: 0 !important;
		position: fixed;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
		z-index: 99999;
		background: transparent !important;
	}
	.modal-backdrop,
	.modal-overlay {
		display: none !important;
		visibility: hidden !important;
		opacity: 0 !important;
	}
	/* Prevent sidebar and layout white flash - hide until CSS loads */
	.dashboard-layout {
		opacity: 0 !important;
		visibility: hidden !important;
	}
	.dashboard-layout.css-loaded {
		opacity: 1 !important;
		visibility: visible !important;
		transition: opacity 0.1s ease !important;
	}
	.dashboard-sidebar {
		background: rgba(11, 31, 34, 0.92) !important;
		background-color: rgba(11, 31, 34, 0.92) !important;
		position: relative !important;
		z-index: 1 !important;
		opacity: 0 !important;
		visibility: hidden !important;
	}
	.dashboard-layout.css-loaded .dashboard-sidebar {
		opacity: 1 !important;
		visibility: visible !important;
		transition: opacity 0.15s ease !important;
	}
	/* Force all potential white backgrounds to be dark */
	aside, .dashboard-sidebar, .sidebar-brand, .sidebar-nav, .sidebar-footer {
		background: rgba(11, 31, 34, 0.92) !important;
		background-color: rgba(11, 31, 34, 0.92) !important;
	}
	.dashboard-main {
		background: transparent !important;
	}
	.dashboard-topbar {
		background: rgba(17, 46, 51, 0.9) !important;
	}
	body.reloading #page-loader,
	body.reloading .modal-backdrop,
	body.reloading .modal-overlay,
	body.reloading .user-actions-dropdown {
		display: none !important;
		visibility: hidden !important;
		opacity: 0 !important;
	}
	body.reloading * {
		transition: none !important;
		animation: none !important;
	}
	</style>
	<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" />
	<link rel="stylesheet" href="assets/css/pdfjs.css" />
</head>
<body class="dashboard-body">
    <div id="page-loader" class="page-loader" style="display: none !important; visibility: hidden !important; opacity: 0 !important;">
        <div class="loader-spinner" aria-hidden="true"></div>
    </div>
    <script>
    // Hide page loader immediately to prevent white box flash
    (function() {
        var loader = document.getElementById('page-loader');
        if (loader) {
            loader.style.display = 'none';
            loader.style.visibility = 'hidden';
            loader.style.opacity = '0';
        }
        // Ensure sidebar has correct background immediately
        var sidebar = document.querySelector('.dashboard-sidebar');
        if (sidebar) {
            sidebar.style.setProperty('background', 'rgba(11, 31, 34, 0.92)', 'important');
            sidebar.style.setProperty('background-color', 'rgba(11, 31, 34, 0.92)', 'important');
            // Force reflow
            void sidebar.offsetHeight;
        }
        var layout = document.querySelector('.dashboard-layout');
        if (layout) {
            layout.style.background = 'transparent';
        }
        var main = document.querySelector('.dashboard-main');
        if (main) {
            main.style.background = 'transparent';
        }
        // Show layout when CSS is loaded
        function showLayout() {
            var layout = document.querySelector('.dashboard-layout');
            if (layout) {
                layout.classList.add('css-loaded');
                layout.style.opacity = '1';
                layout.style.visibility = 'visible';
            }
        }
        // Try to show immediately if CSS already loaded
        if (document.readyState === 'complete' || document.readyState === 'interactive') {
            setTimeout(showLayout, 10);
        } else {
            window.addEventListener('load', showLayout);
            document.addEventListener('DOMContentLoaded', function() {
                setTimeout(showLayout, 50);
            });
        }
    })();
    </script>
	<div class="dashboard-layout" style="background: transparent !important; opacity: 0; visibility: hidden;">
		<?php if (!defined('LUNA_APP')) define('LUNA_APP', true); include __DIR__ . '/control_menu.php'; ?>
		<div class="dashboard-main">
			<?php include __DIR__ . '/control_header.php'; ?>
			<?php
			if (!defined('LUNA_APP')) define('LUNA_APP', true);
            if ($page === 'company') {
                include __DIR__ . '/profile_conpany.php';
            } elseif ($page === 'category') {
                include __DIR__ . '/profile_category.php';
            } elseif ($page === 'outgoing') {
                include __DIR__ . '/profile_outgoing.php';
            } elseif ($page === 'incoming') {
                include __DIR__ . '/profile_incoming.php';
            } elseif ($page === 'incoming_log') {
                include __DIR__ . '/profile_incoming_log.php';
            } elseif ($page === 'zalo') {
                include __DIR__ . '/profile_zalo.php';
            } elseif ($page === 'zalo_log') {
                include __DIR__ . '/profile_zalo_log.php';
            } elseif ($page === 'attendance') {
                include __DIR__ . '/profile_attendance.php';
            } elseif ($page === 'profile') {
                include __DIR__ . '/profile_personal.php';
            } else {
				include __DIR__ . '/dashboard.php';
			}
			?>
		</div>
	</div>
    <script src="assets/js/app.js?v=<?php echo time(); ?>"></script>
    <script>
    window.__FLASH__ = <?php echo json_encode($flashData, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;
    window.__MESSAGES__ = <?php echo json_encode($messages, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>;
    </script>
    <script>
    // Hide loader when page is fully ready
    function hideLoader() {
        var loader = document.getElementById('page-loader');
        if (loader) {
            loader.classList.remove('show');
            loader.style.display = 'none';
            loader.style.visibility = 'hidden';
            loader.style.opacity = '0';
        }
    }

    // Hide loader immediately when DOM is ready (before images load)
    document.addEventListener('DOMContentLoaded', function() {
        hideLoader();
    });

    // Hide loader when page is fully ready
    window.addEventListener('load', hideLoader);

    // Hide loader when page is shown from bfcache (back/forward button)
    window.addEventListener('pageshow', function(event) {
        // The event.persisted property is true if the page is loaded from cache
        if (event.persisted) {
            hideLoader();
        }
    });

    // Show loader on navigation clicks to simulate loading state
    (function () {
        var loader = document.getElementById('page-loader');
        function show() { 
            // Don't show loader if body is marked as reloading
            if (document.body.classList.contains('reloading')) {
                return;
            }
            if (loader) {
                loader.style.display = 'flex';
                loader.style.visibility = 'visible';
                loader.style.opacity = '1';
                loader.classList.add('show');
            }
        }
        // Delegate for internal links
        document.addEventListener('click', function (e) {
            var link = e.target.closest('a');
            if (!link) return;
            var href = link.getAttribute('href') || '';
            var isInternal = href && !/^https?:\/\//i.test(href) && !href.startsWith('mailto:') && !href.startsWith('#');
            if (isInternal) {
                show();
            }
        }, true);
    })();
    </script>
</body>
</html>





