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

$isLoggedIn = isset($_SESSION['user_id']);
$role = $_SESSION['role'] ?? null;

$siteName = $siteName ?? 'Розклад занять';
$pageTitle = $pageTitle ?? $siteName;

/**
 * Можна передати масив CSS для конкретної сторінки:
 * $pageCss = ['/css/home.css'];
 */
$pageCss = $pageCss ?? [];

$currentPath = parse_url($_SERVER['REQUEST_URI'] ?? '/', PHP_URL_PATH) ?: '/';

/**
 * Базові пункти меню (видимі всім)
 */
$menuItems = [
    ['title' => 'Головна',            'href' => '/index.php'],
    ['title' => 'Консультації',       'href' => '/rozklad/consultations.php'],
    ['title' => 'Профілі викладачів', 'href' => '/users/teachers.php'],
];

if ($isLoggedIn) {
    $menuItems[] = ['title' => 'Архів розкладів', 'href' => '/rozklad/schedule_archive.php'];

    if (in_array($role, ['admin', 'teacher'], true)) {
        $menuItems[] = ['title' => 'Адмінпанель', 'href' => '/admin/dashboard.php'];
    }

    $menuItems[] = ['title' => 'Вийти', 'href' => '/logout.php'];
} else {
    $menuItems[] = ['title' => 'Увійти',          'href' => '/login.php'];
    $menuItems[] = ['title' => 'Зареєструватися', 'href' => '/register.php'];
}

function is_active_menu(string $currentPath, string $href): bool {
    $a = rtrim((string)$currentPath, '/');
    $b = rtrim((string)(parse_url($href, PHP_URL_PATH) ?: ''), '/');
    if ($a === '') $a = '/';
    if ($b === '') $b = '/';
    return $a === $b;
}
?>
<!DOCTYPE html>
<html lang="uk">
<head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title><?= htmlspecialchars($pageTitle, ENT_QUOTES, 'UTF-8') ?></title>

    <!-- Цвета в стиле КПКІТП -->
    <meta name="theme-color" content="#47CFC2">

    <style>
        :root{
            /* BRAND (KPKITP) */
            --kp-mint: #9FE7DD;
            --kp-mint-2: #6FD9CD;
            --kp-violet: #3B1F5E;
            --kp-violet-2: #2B1248;
            --kp-white: #FFFFFF;

            /* UI */
            --bg: #F6FFFD;
            --paper: #FFFFFF;
            --text: #1E1B22;
            --muted: rgba(30, 27, 34, .68);
            --border: rgba(59, 31, 94, .14);

            --shadow: 0 10px 30px rgba(16, 24, 40, .10);

            --radius: 18px;
            --radius-sm: 14px;

            --container: 1180px;

            /* header helpers */
            --header-bg: linear-gradient(180deg, var(--kp-mint) 0%, #B7F0EA 100%);
            --header-ink: var(--kp-violet);
        }

        *{ box-sizing: border-box; }
        html,body{ margin:0; padding:0; }
        body{
            background: var(--bg);
            color: var(--text);
            font-family: system-ui,-apple-system,Segoe UI,Roboto,Ubuntu,'Noto Sans',sans-serif;
        }

        .kp-container{
            max-width: var(--container);
            margin: 0 auto;
            padding: 0 14px;
        }
    </style>

    <link rel="preload" href="/css/header.css" as="style">
    <link rel="stylesheet" href="/css/header.css">

    <?php if (is_array($pageCss) && !empty($pageCss)): ?>
        <?php foreach ($pageCss as $css): ?>
            <link rel="stylesheet" href="<?= htmlspecialchars((string)$css, ENT_QUOTES, 'UTF-8') ?>">
        <?php endforeach; ?>
    <?php endif; ?>
</head>
<body id="top">
<header class="site-header site-header--rozklad" role="banner">
    <div class="kp-container">
        <div class="header-inner">
            <a class="site-logo" href="/index.php" aria-label="На головну">
                <img src="/img/logo.png" alt="Логотип сайту">
            </a>

            <a class="site-title" href="/index.php">
                <span class="site-title-text"><?= htmlspecialchars($siteName, ENT_QUOTES, 'UTF-8') ?></span>
            </a>

            <button
                class="nav-toggle"
                id="navToggle"
                aria-label="Перемкнути меню"
                aria-expanded="false"
                aria-controls="mainNav"
                type="button"
            >
                <span class="nav-toggle-bar"></span>
                <span class="nav-toggle-bar"></span>
                <span class="nav-toggle-bar"></span>
            </button>

            <nav class="main-nav" id="mainNav" aria-label="Головне меню">
                <ul>
                    <?php foreach ($menuItems as $item):
                        $active = is_active_menu($currentPath, (string)$item['href']);
                    ?>
                        <li>
                            <a
                                href="<?= htmlspecialchars((string)$item['href'], ENT_QUOTES, 'UTF-8') ?>"
                                class="<?= $active ? 'active' : '' ?>"
                                <?= $active ? 'aria-current="page"' : '' ?>
                            >
                                <?= htmlspecialchars((string)$item['title'], ENT_QUOTES, 'UTF-8') ?>
                            </a>
                        </li>
                    <?php endforeach; ?>
                </ul>
            </nav>
        </div>
    </div>
</header>

<script>
(function () {
    const btn = document.getElementById('navToggle');
    const nav = document.getElementById('mainNav');

    if (!btn || !nav) return;

    function setOpen(isOpen){
        nav.classList.toggle('open', isOpen);
        btn.setAttribute('aria-expanded', String(isOpen));
        if (isOpen) {
            setTimeout(() => document.addEventListener('click', closeOnOutsideClick), 0);
        } else {
            document.removeEventListener('click', closeOnOutsideClick);
        }
    }

    function closeOnOutsideClick(e) {
        if (!nav.contains(e.target) && !btn.contains(e.target)) setOpen(false);
    }

    btn.addEventListener('click', function () {
        setOpen(!nav.classList.contains('open'));
    });

    document.addEventListener('keydown', function (e) {
        if (e.key === 'Escape') setOpen(false);
    });

    nav.addEventListener('click', function(e){
        const a = e.target && e.target.closest ? e.target.closest('a') : null;
        if (a) setOpen(false);
    });
})();
</script>
