<?php 
$title = 'Каталог';
use App\Core\View;
?>

<style>
    .catalog-wrapper { display: flex; gap: 30px; margin-top: 20px; }
    .catalog-sidebar { width: 250px; flex-shrink: 0; }
    .catalog-products { flex: 1; }
    .filter-group { margin-bottom: 25px; }
    .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; }
    .products-container { display: grid; grid-template-columns: repeat(auto-fill, minmax(250px, 1fr)); gap: 20px; }
    .product-card { background: #f5f5f5; border-radius: 8px; overflow: hidden; position: relative; cursor: pointer; transition: transform 0.3s; }
    .product-card:hover { transform: translateY(-5px); }
    .product-card img { width: 100%; height: 200px; object-fit: cover; }
    .product-info { padding: 15px; }
    .product-info .name { font-weight: bold; color: #453227; margin-bottom: 5px; }
    .product-info .product-rating { display: flex; align-items: center; gap: 5px; margin: 8px 0; }
    .product-info .product-rating .stars { display: flex; gap: 1px; }
    .product-info .product-rating .star { font-size: 14px; color: #ddd; }
    .product-info .product-rating .star.filled { color: #ffc107; }
    .product-info .product-rating .rating-text { font-size: 12px; color: #666; }
    .product-info .price { color: #617365; font-size: 18px; font-weight: bold; }
    .add-to-cart-btn { 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; color: #453227; border: 1px solid #eee; transition: all 0.3s; }
    .add-to-cart-btn:hover { background: #453227; color: white; }
    .admin-panel { background: #f8f9fa; padding: 15px; margin-bottom: 20px; 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; }
    .user-welcome { background: #f5e9dc; color: #453227; padding: 15px; border-radius: 8px; margin-bottom: 20px; border-left: 4px solid #453227; }
    .product-card.unavailable { opacity: 0.6; filter: grayscale(0.7); }
</style>

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

        <?php if (!empty($success)): ?>
        <div style="background: #d4edda; color: #155724; padding: 15px; border-radius: 5px; margin: 20px 0;">
            <?= htmlspecialchars($success) ?>
        </div>
        <?php endif; ?>

        <?php if ($isAdmin): ?>
        <div class="admin-panel">
            <h3 style="margin-bottom: 15px; color: #453227;">
                <i class="fas fa-user-shield"></i> Панель управления каталогом
            </h3>
            <div style="margin-bottom: 15px;">
                <a href="/admin/products" class="admin-btn"><i class="fas fa-boxes"></i> Управление каталогом</a>
                <a href="/admin/products/add" class="admin-btn"><i class="fas fa-plus"></i> Добавить товар</a>
                <a href="/admin/categories" class="admin-btn"><i class="fas fa-tags"></i> Категории</a>
                <a href="/admin/orders" class="admin-btn"><i class="fas fa-shopping-cart"></i> Заказы</a>
            </div>
            <div style="padding: 10px; background: white; border-radius: 4px; display: inline-block;">
                <strong style="margin-right: 10px;">Отображение:</strong>
                <a href="/catalog?show_all=1" class="admin-btn" style="<?= $showAll ? 'background: #453227;' : '' ?>">
                    <i class="fas fa-list"></i> Все товары
                </a>
                <a href="/catalog?show_all=0" class="admin-btn" style="<?= !$showAll ? 'background: #453227;' : '' ?>">
                    <i class="fas fa-check-circle"></i> Только доступные
                </a>
            </div>
        </div>
        <?php endif; ?>

        <div class="user-welcome">
            <i class="fas fa-user-check"></i> Добро пожаловать, <strong><?= htmlspecialchars($user['full_name'] ?? $user['email']) ?></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; ?>
        </div>

        <div class="catalog-wrapper">
            <aside class="catalog-sidebar">
                <form method="GET" action="/catalog" id="filterForm">
                    <div class="filter-group">
                        <h4 class="filter-title">КАТЕГОРИИ</h4>
                        <ul class="filter-list">
                            <li><a href="/catalog" class="<?= empty($filters['category_id']) ? 'active-category' : '' ?>">Все товары</a></li>
                            <?php foreach ($categories as $category): ?>
                            <li>
                                <a href="/catalog?category=<?= $category['category_id'] ?>"
                                   class="<?= $filters['category_id'] == $category['category_id'] ? 'active-category' : '' ?>">
                                    <?= htmlspecialchars($category['name']) ?>
                                </a>
                            </li>
                            <?php endforeach; ?>
                        </ul>
                    </div>

                    <div class="filter-group">
                        <h4 class="filter-title">СТОИМОСТЬ</h4>
                        <div class="price-range">
                            <input type="range" min="0" max="100000" value="<?= $filters['max_price'] ?>" 
                                   step="1000" id="priceSlider" name="max_price" style="width: 100%;">
                            <div id="priceDisplay" style="text-align: center; margin-top: 10px; font-weight: bold; color: #453227;">
                                До <?= number_format($filters['max_price'], 0, '', ' ') ?> ₽
                            </div>
                        </div>
                    </div>

                    <?php if (!empty($availableColors)): ?>
                    <div class="filter-group">
                        <h4 class="filter-title">ЦВЕТ</h4>
                        <ul class="filter-list">
                            <?php foreach ($availableColors as $color): ?>
                            <li>
                                <label>
                                    <input type="checkbox" name="colors[]" value="<?= htmlspecialchars($color) ?>"
                                           <?= in_array($color, $filters['colors']) ? 'checked' : '' ?>>
                                    <?= htmlspecialchars($color) ?>
                                </label>
                            </li>
                            <?php endforeach; ?>
                        </ul>
                    </div>
                    <?php endif; ?>

                    <button type="submit" style="width: 100%; background: #453227; color: white; padding: 12px; border: none; border-radius: 4px; cursor: pointer; font-weight: bold;">
                        ПРИМЕНИТЬ ФИЛЬТРЫ
                    </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;">
                            (<?= count($products) ?> товаров)
                        </span>
                    </h2>

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

                <div class="products-container">
                    <?php if (empty($products)): ?>
                    <p style="grid-column: 1/-1; text-align: center; padding: 40px; color: #666;">
                        Товары не найдены
                    </p>
                    <?php else: ?>
                        <?php foreach ($products as $product): ?>
                        <div class="product-card <?= !$product['is_available'] ? 'unavailable' : '' ?>"
                             onclick="window.location.href='/product/<?= $product['product_id'] ?>'"
                             data-product-id="<?= $product['product_id'] ?>">
                            <?php 
                            $imageUrl = $product['image_url'] ?? '';
                            if (empty($imageUrl)) {
                                $imageUrl = '/assets/images/1.jpg';
                            } elseif (strpos($imageUrl, '/img2/') === 0) {
                                $imageUrl = str_replace('/img2/', '/assets/images/', $imageUrl);
                            } elseif (strpos($imageUrl, 'img2/') === 0) {
                                $imageUrl = str_replace('img2/', '/assets/images/', $imageUrl);
                            }
                            ?>
                            <img src="<?= htmlspecialchars($imageUrl) ?>"
                                 alt="<?= htmlspecialchars($product['name']) ?>">
                            <div class="product-info">
                                <div class="name"><?= htmlspecialchars($product['name']) ?></div>
                                <?php if (isset($product['rating']) && $product['rating'] > 0): ?>
                                <div class="product-rating">
                                    <div class="stars">
                                        <?php
                                        $rating = $product['rating'] ?? 0;
                                        for ($i = 1; $i <= 5; $i++) {
                                            $filled = $i <= round($rating);
                                            echo '<span class="star ' . ($filled ? 'filled' : '') . '">★</span>';
                                        }
                                        ?>
                                    </div>
                                    <span class="rating-text"><?= number_format($product['rating'], 1) ?> (<?= $product['review_count'] ?? 0 ?>)</span>
                                </div>
                                <?php endif; ?>
                                <div class="price"><?= View::formatPrice($product['price']) ?></div>
                            </div>
                            <?php if (!$isAdmin && $product['is_available']): ?>
                            <i class="fas fa-shopping-cart add-to-cart-btn"
                               onclick="event.stopPropagation(); addToCart(<?= $product['product_id'] ?>, '<?= addslashes($product['name']) ?>')"
                               title="Добавить в корзину"></i>
                            <?php endif; ?>
                        </div>
                        <?php endforeach; ?>
                    <?php endif; ?>
                </div>
            </section>
        </div>
    </div>
</main>

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

function addToCart(productId, productName) {
    $.ajax({
        url: '/cart/add',
        method: 'POST',
        data: { product_id: productId, quantity: 1 },
        dataType: 'json',
        success: function(result) {
            if (result.success) {
                showNotification('Товар "' + productName + '" добавлен в корзину!');
                $('.cart-count').text(result.cart_count);
            } else {
                showNotification('Ошибка: ' + result.message, 'error');
            }
        },
        error: function() {
            showNotification('Ошибка сервера', 'error');
        }
    });
}
</script>
