<?php
/**
 * Единый header для всех страниц AETERNA
 * Подключение: require_once 'includes/header.php';
 */

// Запускаем сессию если еще не запущена
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}

// Определяем текущую страницу
$currentPage = basename($_SERVER['PHP_SELF'], '.php');

// Проверяем авторизацию
$isLoggedIn = isset($_SESSION['isLoggedIn']) && $_SESSION['isLoggedIn'] === true;
$isAdmin = isset($_SESSION['isAdmin']) && $_SESSION['isAdmin'] === true;
$userEmail = $_SESSION['user_email'] ?? '';
$fullName = $_SESSION['full_name'] ?? $userEmail;
?>
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AETERNA - <?= $pageTitle ?? 'Мебель и Интерьер' ?></title>
    <link rel="stylesheet/less" type="text/css" href="assets/less/style.less">
    <script src="https://cdn.jsdelivr.net/npm/less"></script>
    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <style>
        /* Стили для профиля пользователя */
        .user-profile-dropdown { position: relative; display: inline-block; }
        .user-profile-toggle { display: flex; align-items: center; gap: 10px; cursor: pointer; padding: 8px 12px; border-radius: 4px; transition: all 0.3s ease; }
        .user-profile-toggle:hover { background-color: rgba(0, 0, 0, 0.05); }
        .user-avatar { width: 36px; height: 36px; border-radius: 50%; background: linear-gradient(135deg, #617365 0%, #453227 100%); color: white; display: flex; align-items: center; justify-content: center; font-weight: bold; font-size: 16px; }
        .user-info { display: flex; flex-direction: column; }
        .user-email { font-size: 12px; color: #666; max-width: 120px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
        .user-status { font-size: 10px; padding: 2px 8px; border-radius: 12px; text-transform: uppercase; font-weight: bold; text-align: center; margin-top: 2px; }
        .user-status.admin { background-color: #617365; color: white; }
        .user-status.user { background-color: #28a745; color: white; }
        .user-profile-menu { display: none; position: absolute; top: 100%; right: 0; background: white; min-width: 280px; border-radius: 8px; box-shadow: 0 5px 20px rgba(0,0,0,0.15); z-index: 1000; padding-top: 10px; border: 1px solid #e0e0e0; overflow: visible; }
        .user-profile-menu::before { content: ''; position: absolute; top: 0; left: 0; right: 0; height: 10px; background: transparent; }
        .user-profile-dropdown:hover .user-profile-menu { display: block; }
        .user-profile-header { padding: 15px; background: #f8f9fa; border-bottom: 1px solid #e0e0e0; }
        .user-profile-name { font-weight: bold; margin-bottom: 5px; color: #333; display: flex; align-items: center; gap: 8px; }
        .user-profile-links { list-style: none; padding: 10px 0; margin: 0; }
        .user-profile-links a { display: flex; align-items: center; gap: 10px; padding: 10px 15px; color: #333; text-decoration: none; transition: all 0.3s ease; border-left: 3px solid transparent; }
        .user-profile-links a:hover { background-color: #f5f5f5; border-left-color: #453227; color: #453227; }
        .logout-link { color: #dc3545 !important; }
        .logout-link:hover { background-color: #ffe6e6 !important; border-left-color: #dc3545 !important; }
        .cart-icon { position: relative; margin-right: 15px; }
        .cart-count { position: absolute; top: -8px; right: -8px; background: #dc3545; color: white; border-radius: 50%; width: 18px; height: 18px; font-size: 11px; display: flex; align-items: center; justify-content: center; }
    </style>
    <?php if (isset($additionalStyles)): ?>
    <style><?= $additionalStyles ?></style>
    <?php endif; ?>
</head>
<body>
<header class="header">
    <div class="header__top">
        <div class="container header__top-content">
            <div class="logo"><a href="index.php" style="text-decoration: none; color: inherit;">AETERNA</a></div>

            <div class="search-catalog">
                <div class="catalog-dropdown">
                    Все категории <span>&#9660;</span>
                    <div class="catalog-dropdown__menu">
                        <ul>
                            <li><a href="catalog.php">Все товары</a></li>
                            <li><a href="catalog.php?category=1">Диваны</a></li>
                            <li><a href="catalog.php?category=2">Кресла</a></li>
                            <li><a href="catalog.php?category=3">Кровати</a></li>
                            <li><a href="catalog.php?category=4">Столы</a></li>
                            <li><a href="catalog.php?category=5">Стулья</a></li>
                        </ul>
                    </div>
                </div>
                <div class="search-box">
                    <form method="GET" action="catalog.php" style="display: flex; width: 100%;">
                        <input type="text" name="search" placeholder="Поиск товаров" style="border: none; width: 100%; padding: 10px;">
                        <button type="submit" style="background: none; border: none; cursor: pointer;">
                            <span class="search-icon"><i class="fas fa-search"></i></span>
                        </button>
                    </form>
                </div>
            </div>

            <div class="header__icons--top">
                <?php if ($isLoggedIn): ?>
                <!-- Иконка корзины -->
                <a href="checkout.php" class="icon cart-icon">
                    <i class="fas fa-shopping-cart"></i>
                    <span class="cart-count" id="cartCount">0</span>
                </a>

                <!-- Блок профиля -->
                <div class="user-profile-dropdown">
                    <div class="user-profile-toggle" id="profileToggle">
                        <div class="user-avatar"><?= !empty($userEmail) ? strtoupper(substr($userEmail, 0, 1)) : 'U' ?></div>
                        <div class="user-info">
                            <div class="user-email"><?= htmlspecialchars($userEmail) ?></div>
                            <div class="user-status <?= $isAdmin ? 'admin' : 'user' ?>"><?= $isAdmin ? 'Админ' : 'Пользователь' ?></div>
                        </div>
                        <i class="fas fa-chevron-down" style="font-size: 12px; color: #666;"></i>
                    </div>

                    <div class="user-profile-menu" id="profileMenu">
                        <div class="user-profile-header">
                            <div class="user-profile-name"><i class="fas fa-user"></i> <?= htmlspecialchars($fullName) ?></div>
                        </div>
                        <ul class="user-profile-links">
                            <li><a href="profile.php"><i class="fas fa-user-cog"></i> Мой профиль</a></li>
                            <li><a href="checkout.php"><i class="fas fa-shopping-bag"></i> Мои заказы</a></li>
                            <?php if ($isAdmin): ?>
                            <li><a href="admin/index.php"><i class="fas fa-user-shield"></i> Админ-панель</a></li>
                            <?php endif; ?>
                            <li><a href="logout.php" class="logout-link"><i class="fas fa-sign-out-alt"></i> Выйти</a></li>
                        </ul>
                    </div>
                </div>
                <?php else: ?>
                <a href="login.php" class="icon"><i class="far fa-user"></i></a>
                <a href="login.php" style="font-size: 12px; color: #666; margin-left: 5px;">Войти</a>
                <?php endif; ?>
            </div>
        </div>
    </div>

    <div class="header__bottom">
        <div class="container header__bottom-content">
            <div class="catalog-menu">
                <a href="catalog.php" class="catalog-link <?= $currentPage === 'catalog' ? 'active' : '' ?>">
                    <span class="catalog-lines">☰</span> Каталог
                </a>
            </div>

            <nav class="nav">
                <ul class="nav-list">
                    <li><a href="index.php" class="<?= $currentPage === 'index' || $currentPage === 'cite_mebel' ? 'active' : '' ?>">Главная</a></li>
                    <li><a href="services.php" class="<?= $currentPage === 'services' ? 'active' : '' ?>">Услуги</a></li>
                    <li><a href="delivery.php" class="<?= $currentPage === 'delivery' ? 'active' : '' ?>">Доставка и оплата</a></li>
                    <li><a href="warranty.php" class="<?= $currentPage === 'warranty' ? 'active' : '' ?>">Гарантия</a></li>
                    <li><a href="#footer">Контакты</a></li>
                </ul>
            </nav>
            <div class="header-phone">+7(912)999-12-23</div>
        </div>
    </div>
</header>

<script>
$(document).ready(function() {
    // Профиль пользователя - открытие/закрытие
    $('#profileToggle').click(function(e) {
        e.stopPropagation();
        $('#profileMenu').toggle();
    });
    
    $(document).click(function(e) {
        if (!$(e.target).closest('.user-profile-dropdown').length) {
            $('#profileMenu').hide();
        }
    });

    // Обновление счетчика корзины
    <?php if ($isLoggedIn): ?>
    $.ajax({
        url: 'api/cart.php?action=count',
        method: 'GET',
        success: function(response) {
            try {
                const result = JSON.parse(response);
                if (result.success) {
                    $('#cartCount').text(result.count);
                }
            } catch(e) {}
        }
    });
    <?php endif; ?>
});
</script>

