<?php
session_start();
require_once __DIR__ . '/config/database.php';

if (!isset($_SESSION['isLoggedIn']) || $_SESSION['isLoggedIn'] !== true) {
    header('Location: login.php?error=auth_required&redirect=' . urlencode($_SERVER['REQUEST_URI']));
    exit();
}

$db = Database::getInstance()->getConnection();

$category_id = $_GET['category'] ?? 0;
$search = $_GET['search'] ?? '';
$min_price = $_GET['min_price'] ?? 0;
$max_price = $_GET['max_price'] ?? 1000000;
$colors = isset($_GET['colors']) ? (array)$_GET['colors'] : [];
$materials = isset($_GET['materials']) ? (array)$_GET['materials'] : [];
$show_all = isset($_GET['show_all']) && $_GET['show_all'] == '1';

$success_message = $_GET['success'] ?? '';
$error_message = $_GET['error'] ?? '';

try {

    $user_id = $_SESSION['user_id'] ?? 0;
    $userStmt = $db->prepare("SELECT * FROM users WHERE user_id = ?");
    $userStmt->execute([$user_id]);
    $user = $userStmt->fetch();

    $isAdmin = isset($_SESSION['isAdmin']) && $_SESSION['isAdmin'] === true;
    $userEmail = $_SESSION['user_email'] ?? '';
    $fullName = $_SESSION['full_name'] ?? $userEmail;
    $loginTime = $_SESSION['login_time'] ?? time();

    try {
        $categoriesStmt = $db->prepare("
            SELECT * FROM categories
            WHERE is_active = TRUE
            ORDER BY sort_order, name
        ");
        $categoriesStmt->execute();
        $categories = $categoriesStmt->fetchAll();
    } catch (PDOException $e) {
        $categories = [];
        error_log("Ошибка получения категорий: " . $e->getMessage());
    }

    $subcategories = [];
    if ($category_id > 0) {
        $subStmt = $db->prepare("
            SELECT * FROM subcategories
            WHERE category_id = ? AND is_active = TRUE
            ORDER BY sort_order, name
        ");
        $subStmt->execute([$category_id]);
        $subcategories = $subStmt->fetchAll();
    }

    $checkColumns = $db->query("
        SELECT column_name
        FROM information_schema.columns
        WHERE table_name = 'products'
        AND column_name IN ('color', 'material')
    ");
    $existingColumns = $checkColumns->fetchAll(PDO::FETCH_COLUMN);

    $hasColorColumn = in_array('color', $existingColumns);
    $hasMaterialColumn = in_array('material', $existingColumns);

    $availableColors = [];
    if ($hasColorColumn) {
        $colorsStmt = $db->query("
            SELECT DISTINCT color FROM products
            WHERE color IS NOT NULL AND color != '' AND is_available = TRUE
            ORDER BY color
        ");
        $availableColors = $colorsStmt->fetchAll(PDO::FETCH_COLUMN);
    }

    $availableMaterials = [];
    if ($hasMaterialColumn) {
        $materialsStmt = $db->query("
            SELECT DISTINCT material FROM products
            WHERE material IS NOT NULL AND material != '' AND is_available = TRUE
            ORDER BY material
        ");
        $availableMaterials = $materialsStmt->fetchAll(PDO::FETCH_COLUMN);
    }

    $sql = "SELECT p.*, c.name as category_name
            FROM products p
            LEFT JOIN categories c ON p.category_id = c.category_id
            WHERE 1=1";

    $params = [];

    if (!$show_all && !$isAdmin) {
        $sql .= " AND p.is_available = TRUE";
    }

    if ($category_id > 0) {
        $sql .= " AND p.category_id = ?";
        $params[] = $category_id;
    }

    if ($min_price > 0 || $max_price < 1000000) {
        $sql .= " AND p.price BETWEEN ? AND ?";
        $params[] = $min_price;
        $params[] = $max_price;
    }

    if ($hasColorColumn && !empty($colors)) {
        $placeholders = implode(',', array_fill(0, count($colors), '?'));
        $sql .= " AND p.color IN ($placeholders)";
        $params = array_merge($params, $colors);
    }

    if ($hasMaterialColumn && !empty($materials)) {
        $placeholders = implode(',', array_fill(0, count($materials), '?'));
        $sql .= " AND p.material IN ($placeholders)";
        $params = array_merge($params, $materials);
    }

    if (!empty($search)) {
        $sql .= " AND (p.name LIKE ? OR p.description LIKE ?)";
        $params[] = "%$search%";
        $params[] = "%$search%";
    }

    $sql .= " ORDER BY p.product_id ASC LIMIT 50";

    $stmt = $db->prepare($sql);
    $stmt->execute($params);
    $filteredProducts = $stmt->fetchAll();

    $originalSizes = [
        1 => 'small',
        2 => 'large',
        3 => 'tall align-right',
        4 => 'wide',
        5 => 'small1',
        6 => 'wide2',
        7 => 'wide3',
        8 => 'wide2_1',
        9 => 'full-width'
    ];

    $imgClasses = ['small1', 'wide2', 'wide3', 'wide2_1'];

} catch (PDOException $e) {
    die("Ошибка базы данных: " . $e->getMessage());
}
?>

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <base href="/cite_practica/">
    <title>AETERNA - Каталог</title>
    <link rel="stylesheet/less" type="text/css" href="style_for_cite.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>

        .catalog-dropdown__menu {
            max-height: 400px;
            overflow-y: auto;
            width: 250px;
            background: white;
            border-radius: 8px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }

        .catalog-dropdown__menu ul {
            padding: 10px 0;
        }

        .catalog-dropdown__menu li {
            padding: 8px 15px;
            transition: all 0.3s ease;
        }

        .catalog-dropdown__menu li:hover {
            background: #f5f5f5;
        }

        .catalog-dropdown__menu a {
            color: #333;
            display: block;
            text-decoration: none;
        }

        .catalog-dropdown__menu a:hover {
            color: #453227;
        }

        .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;
        }

        .admin-panel {
            background: #f8f9fa;
            padding: 15px;
            margin: 20px 0;
            border-radius: 8px;
            border-left: 4px solid #617365;
        }

        .admin-btn {
            background: #617365;
            color: white;
            padding: 8px 15px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            margin: 0 5px 5px 0;
            text-decoration: none;
            display: inline-block;
        }

        .admin-btn:hover {
            background: #453227;
            color: white;
        }

        .delete-btn {
            background: #dc3545;
        }

        .delete-btn:hover {
            background: #c82333;
        }

        .user-welcome {
            background: #e8f5e9;
            padding: 15px;
            border-radius: 8px;
            margin-bottom: 20px;
        }

        .user-profile-menu {
            display: none;
            position: absolute;
            background: white;
            padding: 15px;
            border-radius: 8px;
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
            min-width: 250px;
            z-index: 1000;
            right: 0;
            top: 50px;
            border: 1px solid #eee;
        }

        .user-profile-header {
            margin-bottom: 15px;
            padding-bottom: 15px;
            border-bottom: 1px solid #eee;
        }

        .user-profile-name {
            font-weight: bold;
            margin-bottom: 5px;
            color: #333;
        }

        .user-profile-email {
            font-size: 12px;
            color: #666;
            margin-bottom: 5px;
        }

        .user-profile-details {
            font-size: 11px;
            color: #999;
        }

        .user-profile-links {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .user-profile-links li {
            margin-bottom: 5px;
        }

        .user-profile-links a {
            display: block;
            padding: 8px 10px;
            color: #333;
            text-decoration: none;
            border-radius: 4px;
            transition: all 0.3s ease;
        }

        .user-profile-links a:hover {
            background-color: #f5f5f5;
            color: #617365;
        }

        .logout-link {
            color: #dc3545 !important;
            border-top: 1px solid #eee;
            margin-top: 10px;
            padding-top: 12px !important;
        }

        .logout-link:hover {
            background-color: #ffe6e6 !important;
        }

        .sub-categories {
            margin-top: 10px;
        }

        .product-img1 {
            width: 100%;
            height: auto;
            object-fit: cover;
        }

        .product-img {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }

        .align-right {
            text-align: right;
        }

        .product-name-overlay {
            position: absolute;
            left: 15px;
            bottom: 15px;
            z-index: 3;
            max-width: 70%;
            background: transparent !important;
            padding: 0 !important;
            border: none !important;
            box-shadow: none !important;
            backdrop-filter: none !important;
            border-radius: 0 !important;
            border-left: none !important;
            text-align: left !important;
        }

        .product-name-overlay .name {
            font-size: 18px;
            font-weight: bold;
            color: #453227;
            margin: 0;
            line-height: 1.2;
            text-shadow: 1px 1px 3px rgba(255, 255, 255, 0.8);
            text-align: left !important;
        }

        .product-name-overlay .price {
            font-size: 16px;
            color: #617365;
            margin-top: 5px;
            font-weight: 600;
            text-shadow: 1px 1px 2px rgba(255, 255, 255, 0.6);
            text-align: left !important;
        }

        .product-name-overlay.lonki-right {
            left: auto !important;
            right: 15px !important;
            bottom: 15px !important;
            text-align: right !important;
        }

        .product-name-overlay.lonki-right .name,
        .product-name-overlay.lonki-right .price {
            text-align: right !important;
        }

        .product-name-overlay.compact-top-left {
            left: 15px !important;
            top: 15px !important;
            bottom: auto !important;
            text-align: left !important;
        }

        .product-name-overlay.compact-top-left .name,
        .product-name-overlay.compact-top-left .price {
            text-align: left !important;
        }

        .product-wishlist-icon {
            position: absolute;
            bottom: 15px;
            right: 15px;
            background: rgba(255, 255, 255, 0.9);
            width: 40px;
            height: 40px;
            border-radius: 50%;
            display: flex;
            align-items: center;
            justify-content: center;
            cursor: pointer;
            z-index: 4;
            transition: all 0.3s ease;
            color: #453227;
            border: 1px solid #eee;
        }

        .product-wishlist-icon:hover {
            background: #453227;
            color: white;
            transform: scale(1.1);
        }

        .product-image-container {
            position: relative;
            width: 100%;
            height: 100%;
            overflow: hidden;
        }

        .product-card {
            position: relative;
            cursor: pointer;
        }

        .product-card:hover {
            transform: translateY(-5px);
            transition: transform 0.3s ease;
        }

        .product-info-overlay {
            display: none;
        }

        .product-card .product-discount {
            position: absolute;
            top: 15px;
            right: 15px;
            background: #dc3545;
            color: white;
            padding: 4px 8px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: bold;
            z-index: 3;
        }

        .product-card.unavailable {
            opacity: 0.6;
            filter: grayscale(0.7);
            position: relative;
        }

        .product-card.unavailable::before {
            content: "ТОВАР ЗАКОНЧИЛСЯ";
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background: rgba(0, 0, 0, 0.85);
            color: white;
            padding: 15px 25px;
            border-radius: 5px;
            font-weight: bold;
            font-size: 16px;
            text-align: center;
            z-index: 10;
            white-space: nowrap;
            pointer-events: none;
            box-shadow: 0 4px 12px rgba(0,0,0,0.3);
        }

        .product-card.unavailable .product-name-overlay .name,
        .product-card.unavailable .product-name-overlay .price {
            color: #999 !important;
            text-shadow: none !important;
        }

        .product-card.unavailable .add-to-cart-btn {
            display: none;
        }

        .product-card.unavailable .product-wishlist-icon {
            display: none;
        }

        .out-of-stock-badge {
            position: absolute;
            top: 10px;
            left: 10px;
            background: #6c757d;
            color: white;
            padding: 5px 10px;
            border-radius: 4px;
            font-size: 12px;
            font-weight: bold;
            z-index: 10;
        }

        .admin-tools {
            background: #f8f9fa;
            padding: 15px;
            margin-bottom: 20px;
            border-radius: 8px;
            border-left: 4px solid #617365;
        }

        @media (max-width: 768px) {
            .product-name-overlay {
                left: 10px;
                bottom: 10px;
                max-width: 60%;
            }

            .product-name-overlay .name {
                font-size: 14px;
            }

            .product-name-overlay .price {
                font-size: 12px;
            }

            .product-card.unavailable::before {
                font-size: 12px;
                padding: 10px 15px;
                white-space: normal;
                width: 90%;
                text-align: center;
            }
        }

        .filter-options {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .filter-options li {
            margin-bottom: 8px;
        }

        .filter-options input[type="checkbox"] {
            margin-right: 8px;
        }

        .filter-options label {
            cursor: pointer;
            color: #453227;
            font-size: 14px;
        }

        .filter-apply-btn {
            background: #453227;
            color: white;
            border: none;
            padding: 12px 24px;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
            font-weight: bold;
            width: 100%;
            margin-top: 20px;
            transition: all 0.3s ease;
        }

        .filter-apply-btn:hover {
            background: #617365;
        }

        .filter-title {
            color: #453227;
            font-size: 16px;
            font-weight: bold;
            margin-bottom: 15px;
            border-bottom: 2px solid #453227;
            padding-bottom: 5px;
        }

        .filter-list {
            list-style: none;
            padding: 0;
            margin: 0;
        }

        .filter-list li {
            margin-bottom: 8px;
        }

        .filter-list a {
            color: #453227;
            text-decoration: none;
            font-size: 14px;
            transition: all 0.3s ease;
        }

        .filter-list a:hover {
            color: #617365;
            padding-left: 5px;
        }

        .active-category {
            font-weight: bold !important;
            color: #617365 !important;
        }

        .price-display {
            font-size: 16px;
            font-weight: bold;
            color: #453227;
            margin-top: 10px;
            text-align: center;
        }

        .notification {
            position: fixed;
            top: 20px;
            right: 20px;
            padding: 15px 20px;
            background: #28a745;
            color: white;
            border-radius: 4px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            z-index: 10000;
            transform: translateX(150%);
            transition: transform 0.3s ease;
            max-width: 300px;
        }

        .notification.show {
            transform: translateX(0);
        }

        .notification.error {
            background: #dc3545;
        }

        .notification.info {
            background: #17a2b8;
        }

        .admin-catalog-btn {
            background: #453227;
            color: white;
            padding: 10px 20px;
            border-radius: 4px;
            text-decoration: none;
            display: inline-flex;
            align-items: center;
            gap: 8px;
            margin-top: 10px;
        }

        .admin-catalog-btn:hover {
            background: #617365;
            color: white;
        }
    </style>
</head>
<body>
    <div id="notification" class="notification"></div>

    <header class="header">
        <div class="header__top">
            <div class="container header__top-content">
                <div class="logo">AETERNA</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>
                                <?php foreach ($categories as $category): ?>
                                <li><a href="catalog.php?category=<?= $category['category_id'] ?>">
                                    <?= htmlspecialchars($category['name']) ?>
                                </a></li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                    </div>
                    <div class="search-box">
                        <form method="GET" action="catalog.php" style="display: flex; width: 100%;">
                            <input type="text" name="search" placeholder="Поиск товаров"
                                   value="<?= htmlspecialchars($search) ?>"
                                   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">
                    <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 class="user-profile-email">
                                    <i class="fas fa-envelope"></i> <?= htmlspecialchars($userEmail) ?>
                                </div>
                                <div class="user-profile-details">
                                    <i class="fas fa-clock"></i> Вошел: <?= date('d.m.Y H:i', $loginTime) ?>
                                </div>
                                <?php if (isset($user['created_at'])): ?>
                                <div class="user-profile-details">
                                    <i class="fas fa-calendar"></i> Зарегистрирован: <?= date('d.m.Y', strtotime($user['created_at'])) ?>
                                </div>
                                <?php endif; ?>
                            </div>

                            <ul class="user-profile-links">
                                <li><a href="register.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>
                </div>
            </div>
        </div>

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

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

    <main class="catalog-main">
        <div class="container">
            <div class="breadcrumbs">
                <a href="cite_mebel.php">Главная</a> • <span class="current-page">Каталог</span>
            </div>

            <?php if ($success_message): ?>
            <div class="notification show" style="position: relative; top: 0; right: 0; margin: 20px 0; background: #28a745;">
                <?php
                $messages = [
                    'category_added' => 'Категория успешно добавлена!',
                    'category_updated' => 'Категория успешно обновлена!',
                    'category_deleted' => 'Категория успешно удалена!',
                    'product_added' => 'Товар успешно добавлен!',
                    'product_updated' => 'Товар успешно обновлен!',
                    'product_deleted' => 'Товар успешно удален!'
                ];
                echo $messages[$success_message] ?? 'Операция выполнена успешно!';
                ?>
            </div>
            <?php endif; ?>

            <?php if ($error_message): ?>
            <div class="notification error show" style="position: relative; top: 0; right: 0; margin: 20px 0;">
                Ошибка: <?= htmlspecialchars($error_message) ?>
            </div>
            <?php endif; ?>

            <?php if ($isAdmin): ?>

            <div class="admin-panel">
                <h3 style="margin-bottom: 15px; color: #453227;">
                    <i class="fas fa-user-shield"></i> Панель управления каталогом
                    <span style="font-size: 12px; color: #666; margin-left: 10px;">
                        Вы вошли как администратор
                    </span>
                </h3>
                <div>

                    <a href="admin/index.php?action=catalog" class="admin-btn">
                        <i class="fas fa-boxes"></i> Управление каталогом
                    </a>
                    <a href="admin/index.php?action=add_product" class="admin-btn">
                        <i class="fas fa-plus"></i> Добавить товар
                    </a>

                    <a href="admin/index.php?action=categories" class="admin-btn">
                        <i class="fas fa-tags"></i> Управление категориями
                    </a>
                    <a href="admin/index.php?action=orders" class="admin-btn">
                        <i class="fas fa-shopping-cart"></i> Управление заказами
                    </a>
                    <a href="admin/index.php?action=users" class="admin-btn">
                        <i class="fas fa-users"></i> Управление пользователями
                    </a>
                </div>
            </div>

            <div class="admin-tools">
                <h4 style="margin-bottom: 10px; color: #453227;">
                    <i class="fas fa-eye"></i> Настройки отображения
                </h4>
                <?php if ($show_all): ?>
                <a href="catalog.php?<?= http_build_query(array_merge($_GET, ['show_all' => 0])) ?>"
                   class="btn btn-primary" style="background: #453227; color: white; padding: 8px 15px; border-radius: 4px; text-decoration: none; display: inline-block;">
                    <i class="fas fa-eye-slash"></i> Скрыть недоступные товары
                </a>
                <?php else: ?>
                <a href="catalog.php?<?= http_build_query(array_merge($_GET, ['show_all' => 1])) ?>"
                   class="btn btn-info" style="background: #17a2b8; color: white; padding: 8px 15px; border-radius: 4px; text-decoration: none; display: inline-block;">
                    <i class="fas fa-eye"></i> Показать все товары
                </a>
                <?php endif; ?>
                <span style="margin-left: 15px; color: #666; font-size: 14px;">
                    <i class="fas fa-info-circle"></i> Недоступные товары отмечены серым цветом
                </span>
            </div>
            <?php endif; ?>

            <div class="user-welcome" style="background: #f5e9dc; color: #453227; border-left: 4px solid #453227;">
                <i class="fas fa-user-check"></i> Добро пожаловать, <strong><?= htmlspecialchars($fullName) ?></strong>!
                <?php if ($isAdmin): ?>
                <span style="background: #453227; color: white; padding: 3px 8px; border-radius: 4px; font-size: 12px; margin-left: 10px;">
                    <i class="fas fa-user-shield"></i> Администратор
                </span>
                <?php endif; ?>
                <?php if ($show_all && $isAdmin): ?>
                <span style="background: #17a2b8; color: white; padding: 3px 8px; border-radius: 4px; font-size: 12px; margin-left: 10px;">
                    <i class="fas fa-eye"></i> Показаны все товары
                </span>
                <?php endif; ?>
            </div>

            <div class="catalog-wrapper">
                <aside class="catalog-sidebar">
                    <form method="GET" action="catalog.php" id="filterForm">
                        <?php if ($category_id): ?>
                        <input type="hidden" name="category" value="<?= $category_id ?>">
                        <?php endif; ?>

                        <?php if ($show_all): ?>
                        <input type="hidden" name="show_all" value="1">
                        <?php endif; ?>

                        <div class="filter-group">
                            <h4 class="filter-title">КАТЕГОРИИ</h4>
                            <ul class="filter-list">
                                <li><a href="catalog.php<?= $show_all ? '?show_all=1' : '' ?>"
                                       class="<?= !$category_id ? 'active-category' : '' ?>">
                                    Все товары
                                </a></li>
                                <?php foreach ($categories as $category): ?>
                                <li>
                                    <a href="catalog.php?category=<?= $category['category_id'] ?><?= $show_all ? '&show_all=1' : '' ?>"
                                       class="<?= $category_id == $category['category_id'] ? 'active-category' : '' ?>">
                                        <?= htmlspecialchars($category['name']) ?>
                                    </a>
                                </li>
                                <?php endforeach; ?>
                            </ul>
                        </div>

                        <?php if (!empty($subcategories)): ?>
                        <div class="filter-group sub-categories">
                            <h4 class="filter-title">ПОДКАТЕГОРИИ</h4>
                            <ul class="filter-list">
                                <?php foreach ($subcategories as $sub): ?>
                                <li><a href="catalog.php?category=<?= $category_id ?>&subcategory=<?= $sub['subcategory_id'] ?><?= $show_all ? '&show_all=1' : '' ?>">
                                    <?= htmlspecialchars($sub['name']) ?>
                                </a></li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                        <?php endif; ?>

                        <div class="filter-group">
                            <h4 class="filter-title">СТОИМОСТЬ</h4>
                            <div class="price-range">
                                <div class="range-slider">
                                    <input type="range" min="0" max="100000" value="<?= $max_price ?>"
                                           step="1000" id="priceSlider" name="max_price">
                                </div>
                                <div class="price-display" id="priceDisplay">
                                    До <?= number_format($max_price, 0, '', ' ') ?> ₽
                                </div>
                            </div>
                        </div>

                        <?php if ($hasColorColumn && !empty($availableColors)): ?>
                        <div class="filter-group">
                            <h4 class="filter-title">ЦВЕТ</h4>
                            <ul class="filter-options">
                                <?php foreach ($availableColors as $color): ?>
                                <li>
                                    <input type="checkbox" id="color_<?= preg_replace('/[^a-z0-9]/i', '_', $color) ?>" name="colors[]"
                                           value="<?= htmlspecialchars($color) ?>"
                                           <?= in_array($color, $colors) ? 'checked' : '' ?>>
                                    <label for="color_<?= preg_replace('/[^a-z0-9]/i', '_', $color) ?>"><?= htmlspecialchars($color) ?></label>
                                </li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                        <?php endif; ?>

                        <?php if ($hasMaterialColumn && !empty($availableMaterials)): ?>
                        <div class="filter-group">
                            <h4 class="filter-title">МАТЕРИАЛ</h4>
                            <ul class="filter-options">
                                <?php foreach ($availableMaterials as $material): ?>
                                <li>
                                    <input type="checkbox" id="material_<?= preg_replace('/[^a-z0-9]/i', '_', $material) ?>" name="materials[]"
                                           value="<?= htmlspecialchars($material) ?>"
                                           <?= in_array($material, $materials) ? 'checked' : '' ?>>
                                    <label for="material_<?= preg_replace('/[^a-z0-9]/i', '_', $material) ?>"><?= htmlspecialchars($material) ?></label>
                                </li>
                                <?php endforeach; ?>
                            </ul>
                        </div>
                        <?php endif; ?>

                        <button type="submit" class="filter-apply-btn">
                            ПРИМЕНИТЬ ФИЛЬТРЫ
                        </button>
                    </form>
                </aside>

                <section class="catalog-products">
                    <div style="margin-bottom: 20px;">
                        <h2 style="color: #453227; margin-bottom: 10px;">
                            Каталог мебели
                            <span style="font-size: 14px; color: #666; font-weight: normal;">
                                (<?php
                                $activeCount = 0;
                                foreach ($filteredProducts as $p) {
                                    if ($p['is_available']) $activeCount++;
                                }
                                echo $activeCount . ' активных';
                                if ($show_all) {
                                    echo ', ' . count($filteredProducts) . ' всего';
                                }
                                ?> товаров)
                            </span>
                        </h2>

                        <?php if ($search): ?>
                        <p style="color: #666;">
                            Результаты поиска по запросу: "<strong><?= htmlspecialchars($search) ?></strong>"
                            <a href="catalog.php<?= $show_all ? '?show_all=1' : '' ?>" style="margin-left: 10px; color: #617365; text-decoration: none;">
                                <i class="fas fa-times"></i> Очистить поиск
                            </a>
                        </p>
                        <?php endif; ?>

                        <?php if ($show_all): ?>
                        <div style="background: #e8f4fd; padding: 10px 15px; border-radius: 4px; margin-top: 10px;">
                            <i class="fas fa-info-circle" style="color: #17a2b8;"></i>
                            <span style="color: #0c5460; font-size: 14px;">
                                Показаны все товары, включая недоступные. Недоступные товары отмечены серым цветом.
                            </span>
                        </div>
                        <?php endif; ?>
                    </div>

                    <div class="products-container">
                        <?php

                        $originalProducts = [
                            1 => ['name' => 'Светильник MINNIGHT', 'price' => 7999, 'image' => 'img2/1_2.png', 'size' => 'small'],
                            2 => ['name' => 'Кровать MODER', 'price' => 45999, 'image' => 'img2/3_3.png', 'size' => 'large'],
                            3 => ['name' => 'Торшер MARCIA', 'price' => 11999, 'image' => 'img2/2_2.png', 'size' => 'tall align-right'],
                            4 => ['name' => 'Светильник POLET', 'price' => 5499, 'image' => 'img2/4.jpg', 'size' => 'wide'],
                            5 => ['name' => 'Стол NORD', 'price' => 23999, 'image' => 'img2/5_5.png', 'size' => 'small1'],
                            6 => ['name' => 'Диван ROYALTY', 'price' => 78999, 'image' => 'img2/6_6.png', 'size' => 'wide2'],
                            7 => ['name' => 'Кресло MINIMAL', 'price' => 29999, 'image' => 'img2/7_7.png', 'size' => 'wide3'],
                            8 => ['name' => 'Стол LONKI', 'price' => 34999, 'image' => 'img2/8_8.png', 'size' => 'wide2_1'],
                            9 => ['name' => 'Диван HEMMINS', 'price' => 89999, 'image' => 'img2/9_9.png', 'size' => 'full-width']
                        ];

                        if (empty($filteredProducts)) {
                            foreach ($originalProducts as $id => $product): ?>
                            <div class="product-card <?= $product['size'] ?>"
                                 data-product-id="<?= $id ?>"
                                 data-available="true">
                                <div class="product-image-container">
                                    <img src="<?= $product['image'] ?>"
                                         alt="<?= $product['name'] ?>"
                                         class="<?= strpos($product['size'], 'small1') !== false ? 'product-img1' : 'product-img' ?>">

                                    <div class="product-name-overlay">
                                        <div class="name"><?= $product['name'] ?></div>
                                        <div class="price"><?= number_format($product['price'], 0, '', ' ') ?> ₽</div>
                                    </div>

                                    <i class="fas fa-shopping-cart product-wishlist-icon add-to-cart-btn"
                                       data-product-id="<?= $id ?>"
                                       data-product-name="<?= $product['name'] ?>"
                                       data-product-price="<?= $product['price'] ?>"
                                       title="Добавить в корзину"></i>
                                </div>
                            </div>
                            <?php endforeach;
                        } else {

                            foreach ($filteredProducts as $product):

                                $productId = $product['product_id'];
                                if ($productId <= 9 && isset($originalProducts[$productId])) {
                                    $sizeClass = $originalProducts[$productId]['size'];
                                } else {
                                    $sizeClass = 'small';
                                }
                            ?>
                            <div class="product-card <?= $sizeClass ?>"
                                 data-product-id="<?= $productId ?>"
                                 data-available="<?= $product['is_available'] && $product['stock_quantity'] > 0 ? 'true' : 'false' ?>">
                                <div class="product-image-container">
                                    <img src="<?= htmlspecialchars($product['image_url'] ?? 'img/1.jpg') ?>"
                                         alt="<?= htmlspecialchars($product['name']) ?>"
                                         class="<?= strpos($sizeClass, 'small1') !== false ? 'product-img1' : 'product-img' ?>">

                                    <div class="product-name-overlay">
                                        <div class="name"><?= htmlspecialchars($product['name']) ?></div>
                                        <div class="price"><?= number_format($product['price'], 0, '', ' ') ?> ₽</div>
                                    </div>

                                    <i class="fas fa-shopping-cart product-wishlist-icon add-to-cart-btn"
                                       data-product-id="<?= $productId ?>"
                                       data-product-name="<?= htmlspecialchars($product['name']) ?>"
                                       data-product-price="<?= $product['price'] ?>"
                                       title="Добавить в корзину"></i>
                                </div>
                            </div>
                            <?php endforeach;
                        } ?>
                    </div>
                </section>
            </div>
        </div>
    </main>

    <footer class="footer" id="footer">
        <div class="container footer__content">
            <div class="footer__col footer--logo">
                <div class="logo" style="color: #453227;">AETERNA</div>
            </div>

            <div class="footer__col">
                <h5 style="color: #453227;">ПОКУПАТЕЛЮ</h5>
                <ul>
                    <li><a href="catalog.php" style="color: #453227;">Каталог</a></li>
                    <li><a href="services.php" style="color: #453227;">Услуги</a></li>
                </ul>
            </div>

            <div class="footer__col">
                <h5 style="color: #453227;">ПОМОЩЬ</h5>
                <ul>
                    <li><a href="delivery.php" style="color: #453227;">Доставка и оплата</a></li>
                    <li><a href="warranty.php" style="color: #453227;">Гарантия и возврат</a></li>
                    <li><a href="cite_mebel.php#faq" style="color: #453227;">Ответы на вопросы</a></li>
                    <li><a href="#footer" style="color: #453227;">Контакты</a></li>
                </ul>
            </div>

            <div class="footer__col">
                <h5 style="color: #453227;">КОНТАКТЫ</h5>
                <p style="color: #453227;">aeterna@mail.ru</p>
                <p style="color: #453227;">+7(912)999-12-23</p>
                <div class="social-icons">
                    <span class="icon" style="color: #453227;"><i class="fab fa-telegram"></i></span>
                    <span class="icon" style="color: #453227;"><i class="fab fa-instagram"></i></span>
                    <span class="icon" style="color: #453227;"><i class="fab fa-vk"></i></span>
                </div>
            </div>

            <div class="footer__col">
                <h5 style="color: #453227;">ПРИНИМАЕМ К ОПЛАТЕ</h5>
                <div class="payment-icons">
                    <span class="pay-icon" style="color: #453227;"><i class="fab fa-cc-visa"></i></span>
                    <span class="pay-icon" style="color: #453227;"><i class="fab fa-cc-mastercard"></i></span>
                </div>
            </div>
        </div>
        <div class="copyright" style="color: #453227;">
            <p>© 2025 AETERNA. Все права защищены.</p>
        </div>
    </footer>

    <script>
    $(document).ready(function() {

        $('#priceSlider').on('input', function() {
            const value = $(this).val();
            $('#priceDisplay').text('До ' + new Intl.NumberFormat('ru-RU').format(value) + ' ₽');
        });

        $('#profileToggle').click(function(e) {
            e.stopPropagation();
            $('#profileMenu').toggle();
        });

        $(document).click(function(e) {
            if (!$(e.target).closest('.user-profile-dropdown').length) {
                $('#profileMenu').hide();
            }
        });

        updateCartCount();

        $('.add-to-cart-btn').click(function(e) {
            e.stopPropagation();
            const productId = $(this).data('product-id');
            const productName = $(this).data('product-name');
            const productPrice = $(this).data('product-price');
            const isAvailable = $(this).closest('.product-card').data('available');

            if (isAvailable) {
                addToCart(productId, productName, productPrice);
            } else {
                showNotification('Этот товар временно недоступен', 'error');
            }
        });

        $('.product-card').click(function(e) {
            if (!$(e.target).closest('.add-to-cart-btn').length &&
                !$(e.target).closest('.product-wishlist-icon').length) {
                const productId = $(this).data('product-id');
                const isAvailable = $(this).data('available');

                if (isAvailable) {
                    window.location.href = 'product.php?id=' + productId;
                }
            }
        });

        <?php if ($success_message): ?>
        showNotification('<?= $messages[$success_message] ?? "Операция выполнена успешно!" ?>', 'success');
        <?php endif; ?>

        <?php if ($error_message): ?>
        showNotification('Ошибка: <?= addslashes($error_message) ?>', 'error');
        <?php endif; ?>
    });

    function updateCartCount() {
        $.ajax({
            url: 'api/get_cart_count.php',
            method: 'GET',
            success: function(response) {
                try {
                    const result = JSON.parse(response);
                    if (result.success) {
                        $('#cartCount').text(result.cart_count);
                    }
                } catch(e) {
                    console.error('Ошибка при получении корзины:', e);
                }
            },
            error: function() {
                console.error('Ошибка при обновлении корзины');
            }
        });
    }

    function addToCart(productId, productName, productPrice) {
        $.ajax({
            url: 'api/add_to_cart.php',
            method: 'POST',
            data: {
                product_id: productId,
                quantity: 1
            },
            success: function(response) {
                try {
                    const result = JSON.parse(response);
                    if (result.success) {
                        showNotification('Товар "' + productName + '" добавлен в корзину!');
                        updateCartCount();
                    } else {
                        showNotification('Ошибка: ' + result.message, 'error');
                    }
                } catch(e) {
                    showNotification('Ошибка при добавлении в корзину', 'error');
                }
            },
            error: function() {
                showNotification('Ошибка сервера', 'error');
            }
        });
    }

    function showNotification(message, type = 'success') {
        const notification = $('#notification');
        notification.text(message);
        notification.removeClass('success error info').addClass(type + ' show');

        setTimeout(function() {
            notification.removeClass('show');
        }, 3000);
    }
    </script>
</body>
</html>