<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

/*
|--------------------------------------------------------------------------
| USER LOGIN CHECK
|--------------------------------------------------------------------------
|
| Adjust these session names according to your system.
|
*/
$isLoggedIn = isset($_SESSION['user_id']);
$siteIdentity = function_exists('get_site_identity') ? get_site_identity() : ['business_name' => APP_NAME, 'logo_url' => ''];
$siteName = $siteIdentity['business_name'] ?? APP_NAME;
$siteLogoUrl = $siteIdentity['logo_url'] ?? '';
	
$userRole = $_SESSION['user_role'] ?? ($_SESSION['user_type'] ?? 'client');
$dashboardUrl = app_url('client/client-dashboard.php');

if ($isLoggedIn) {
    if ($userRole === 'admin') {
        $dashboardUrl = app_url('admin/admin-dashboard.php');
    } elseif ($userRole === 'seller') {
        $dashboardUrl = app_url('seller/seller-dashboard.php');
    }
}

/*
|--------------------------------------------------------------------------
| LOAD CATEGORIES
|--------------------------------------------------------------------------
*/
$categories = [];

try {
    $stmt = $pdo->query("
        SELECT id, category_name, slug
        FROM categories
        ORDER BY category_name ASC
    ");

    $categories = $stmt->fetchAll(PDO::FETCH_ASSOC);

} catch (Exception $e) {
    $categories = [];
}
?>

<header class="navbar fixed top-0 w-full z-50 transition-all duration-300">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 h-20 flex items-center justify-between">

        <!-- Logo -->
        <div class="flex items-center space-x-3 cursor-pointer"
	             onclick="window.location.href='<?php echo htmlspecialchars(app_url('index.php'), ENT_QUOTES, 'UTF-8'); ?>'">
	
	            <?php if (!empty($siteLogoUrl)): ?>
	                <div class="h-12 max-w-[180px] flex items-center">
	                    <img src="<?php echo htmlspecialchars($siteLogoUrl, ENT_QUOTES, 'UTF-8'); ?>" alt="<?php echo htmlspecialchars($siteName, ENT_QUOTES, 'UTF-8'); ?> Logo" class="max-h-full max-w-full object-contain">
	                </div>
	            <?php else: ?>
	                <div class="w-10 h-10 bg-gradient-to-tr from-nftAccentCyan to-nftAccentPurple rounded-xl flex items-center justify-center font-bold text-xl tracking-wider shadow-lg shadow-cyan-500/20">
	                    <?php echo htmlspecialchars(strtoupper(substr($siteName, 0, 1)), ENT_QUOTES, 'UTF-8'); ?>
	                </div>
		
	                <div class="flex flex-col min-w-0">
	                    <span class="text-2xl font-extrabold tracking-tight bg-clip-text text-transparent bg-gradient-to-r from-white via-white to-nftAccentCyan leading-none max-w-[180px] truncate">
	                        <?php echo htmlspecialchars($siteName, ENT_QUOTES, 'UTF-8'); ?>
	                    </span>
		
	                    <span class="text-[10px] tracking-widest text-nftAccentPurple uppercase font-bold mt-1">
	                        Marketplace
	                    </span>
	                </div>
	            <?php endif; ?>
	        </div>

        <!-- Desktop Navigation -->
        <nav class="hidden md:flex items-center space-x-8 text-sm font-medium">

            <a href="<?php echo htmlspecialchars(app_url('index.php'), ENT_QUOTES, 'UTF-8'); ?>"
               class="text-nftTextGray hover:text-white transition-colors">
                Home
            </a>

            <a href="<?php echo htmlspecialchars(app_url('items.php'), ENT_QUOTES, 'UTF-8'); ?>"
               class="text-nftTextGray hover:text-white transition-colors">
                All Items
            </a>

            <!-- Categories Dropdown -->
            <div class="relative group">

                <button class="text-nftTextGray hover:text-white transition-colors flex items-center gap-2">
                    Categories
                    <i class="fa-solid fa-chevron-down text-xs"></i>
                </button>

                <div class="absolute left-0 mt-3 w-72 bg-nftCard border border-slate-800 rounded-xl shadow-2xl opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200 max-h-96 overflow-y-auto">

                    <?php if (!empty($categories)): ?>
                        <?php foreach ($categories as $category): ?>

                            <a href="<?php echo htmlspecialchars(app_url('category-items/' . (int)$category['id']), ENT_QUOTES, 'UTF-8'); ?>"
                               class="block px-4 py-3 text-sm text-slate-300 hover:bg-slate-800 hover:text-white border-b border-slate-800 last:border-0">

                                <?php echo htmlspecialchars($category['category_name']); ?>

                            </a>

                        <?php endforeach; ?>
                    <?php else: ?>

                        <div class="px-4 py-3 text-slate-400 text-sm">
                            No categories found
                        </div>

                    <?php endif; ?>

                </div>
            </div>

        </nav>

        <!-- Right Side -->
        <div class="flex items-center space-x-4">

            <!-- Search -->
            <div class="relative hidden lg:block">

                <form action="<?php echo htmlspecialchars(app_url('search.php'), ENT_QUOTES, 'UTF-8'); ?>" method="GET" data-search-base="<?php echo htmlspecialchars(app_url('search/'), ENT_QUOTES, 'UTF-8'); ?>">

                    <input
                        type="text"
                        name="q"
                        placeholder="Search AI components, prompts, tools..."
                        class="bg-nftCard/80 border border-slate-800 text-sm rounded-full pl-4 pr-10 py-2 focus:outline-none focus:border-nftAccentCyan transition-all w-72 text-slate-200">

                    <button type="submit">
                        <i class="fa-solid fa-magnifying-glass absolute right-4 top-3 text-xs text-nftTextGray"></i>
                    </button>

                </form>

            </div>

            <?php if (!$isLoggedIn): ?>

                <!-- Login / Join -->
                <a href="<?php echo htmlspecialchars(app_url('login.php'), ENT_QUOTES, 'UTF-8'); ?>"
                   class="text-nftTextGray hover:text-white text-sm font-medium">
                    Login
                </a>

                <a href="<?php echo htmlspecialchars(app_url('register.php'), ENT_QUOTES, 'UTF-8'); ?>"
                   class="text-nftTextGray hover:text-white text-sm font-medium">
                    Join
                </a>

            <?php else: ?>

                <!-- Profile Dropdown -->
                <div class="relative group">

                    <button class="w-10 h-10 rounded-full bg-gradient-to-r from-nftAccentCyan to-nftAccentPurple flex items-center justify-center text-white font-bold">

                        <?php
                        echo strtoupper(substr($_SESSION['user_name'] ?? $_SESSION['name'] ?? 'U', 0, 1));
                        ?>

                    </button>

                    <div class="absolute right-0 mt-3 w-56 bg-nftCard border border-slate-800 rounded-xl shadow-xl opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200">

                        <a href="<?php echo htmlspecialchars($dashboardUrl, ENT_QUOTES, 'UTF-8'); ?>"
                           class="block px-4 py-3 text-sm text-slate-300 hover:bg-slate-800 hover:text-white">

                            Dashboard

                        </a>

                        <a href="<?php echo htmlspecialchars(app_url('logout.php'), ENT_QUOTES, 'UTF-8'); ?>"
                           class="block px-4 py-3 text-sm text-red-400 hover:bg-slate-800">

                            Logout

                        </a>

                    </div>

                </div>

            <?php endif; ?>

            <!-- Start Selling -->
            <a href="<?php echo htmlspecialchars(app_url('seller/seller-dashboard.php'), ENT_QUOTES, 'UTF-8'); ?>"
               class="btn-gradient px-6 py-2.5 rounded-full text-sm font-semibold shadow-lg transition-all duration-300 inline-block text-center">

                Start Selling

            </a>

        </div>

    </div>
</header>

<script>
    document.addEventListener("DOMContentLoaded", function () {
        document.querySelectorAll("form[data-search-base]").forEach(function (searchForm) {
            searchForm.addEventListener("submit", function (event) {
                const queryInput = searchForm.querySelector('input[name="q"]');
                const queryValue = queryInput ? queryInput.value.trim() : "";

                if (queryValue === "") {
                    return;
                }

                event.preventDefault();
                window.location.href = searchForm.dataset.searchBase + encodeURIComponent(queryValue);
            });
        });
    });
</script>
