<?php
require_once __DIR__ . '/config.php';
require_once __DIR__ . '/metrics.php';
if (empty($GLOBALS['__metrics_tracked'])) {
    metrics_track_pageview();
}

$is_logged_in      = false;
$logged_first_name = '';
$logged_role       = 'member';
if (file_exists(__DIR__ . '/auth.php')) {
    try {
        require_once __DIR__ . '/auth.php';
        // Admin session takes precedence (admin opening the public site)
        if (function_exists('auth_admin_check') && auth_admin_check()) {
            $a = auth_admin_user();
            if ($a && is_array($a)) {
                $is_logged_in      = true;
                $logged_first_name = $a['first_name'] ?? 'Admin';
                $logged_role       = 'admin';
            }
        } elseif (auth_member_check()) {
            $u = auth_member_user();
            if ($u && is_array($u)) {
                $is_logged_in      = true;
                $logged_first_name = $u['first_name'] ?? '';
                $logged_role       = 'member';
            }
        }
    } catch (Throwable $e) { /* DB not ready — ignore */ }
}

$current = basename($_SERVER['PHP_SELF']);

// Only the homepage has the transparent video hero. Everything else gets a solid dark nav.
$has_hero = ($current === 'index.php');

// Detect subdirectory depth for asset paths (member/, admin/, etc. are one level deep)
$script_path = $_SERVER['PHP_SELF'];
$depth = substr_count(trim(str_replace('/buylocal/', '/', $script_path), '/'), '/');
$base  = str_repeat('../', $depth);

function nav_link($href, $label, $current_page, $base = '') {
    $filename = basename(parse_url($href, PHP_URL_PATH) ?? $href);
    $class = ($current_page === $filename) ? 'current' : '';
    return "<li><a href=\"{$base}{$href}\" class=\"$class\">$label</a></li>";
}
?><!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title><?= htmlspecialchars($page_title ?? SITE_NAME) ?> &mdash; <?= htmlspecialchars(SITE_NAME) ?></title>
    <?php if (!empty($page_description)): ?>
        <meta name="description" content="<?= htmlspecialchars($page_description) ?>">
    <?php endif; ?>

    <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=Montserrat:wght@300;400;500;600;700&family=Playfair+Display:ital,wght@0,400;0,500;0,600;0,700;1,400&display=swap" rel="stylesheet">

    <link rel="stylesheet" href="<?= $base ?>assets/css/style.css">
</head>
<body class="<?= $has_hero ? 'has-hero' : 'has-dark-nav' ?>">

<header class="site-header" id="site-header">
    <div class="container">
        <a href="<?= $base ?>index.php" class="site-logo">
            <img src="<?= $base ?>assets/img/buylocal-stamp.png"
                 alt="Buy Local Lowveld" class="logo-img">
            <span>Buy Local Lowveld</span>
        </a>

        <button class="nav-toggle" id="nav-toggle" aria-expanded="false" aria-label="Toggle menu">☰</button>

        <nav class="main-nav" id="main-nav" aria-label="Main">
            <ul>
                <?= nav_link('index.php',               'Home',             $current, $base) ?>
                <?= nav_link('learn-more.php',          'Learn More',       $current, $base) ?>
                <?= nav_link('directory.php',           'Our Directory',    $current, $base) ?>
                <?= nav_link('become-member.php',       'Become a Member',  $current, $base) ?>
                <?= nav_link('additional-branding.php', 'Additional Branding', $current, $base) ?>
                <?= nav_link('blog.php',                'Blog',             $current, $base) ?>
                <?= nav_link('contact.php',             'Contact',          $current, $base) ?>
                <?php if ($is_logged_in): ?>
                    <?php
                    $dashboard_url = ($logged_role === 'admin')
                        ? $base . 'admin/dashboard.php'
                        : $base . 'member/welcome.php';
                    $logout_url = ($logged_role === 'admin')
                        ? $base . 'admin/logout.php'
                        : $base . 'logout.php';
                    ?>
                    <li><a href="<?= htmlspecialchars($dashboard_url) ?>">Dashboard</a></li>
                    <li><a href="<?= htmlspecialchars($logout_url) ?>" class="login-btn">Log out</a></li>
                <?php else: ?>
                    <li><a href="<?= $base ?>login.php" class="login-btn">Login</a></li>
                <?php endif; ?>
            </ul>
        </nav>
    </div>
</header>

<script>
// Sticky header after scroll on homepage only
(function () {
    const header = document.getElementById('site-header');
    const toggle = document.getElementById('nav-toggle');
    const nav    = document.getElementById('main-nav');
    const hasHero = document.body.classList.contains('has-hero');

    if (hasHero) {
        window.addEventListener('scroll', () => {
            header.classList.toggle('sticky', window.scrollY > 80);
        }, { passive: true });
    }
    if (toggle) toggle.addEventListener('click', () => nav.classList.toggle('open'));
})();
</script>

<main>