<?php
require_once 'config.php';

$selected_category = isset($_GET['category']) ? trim($_GET['category']) : '';
$categories = getAllCategories($pdo);

if($selected_category && $selected_category !== '') {
    $stmt = $pdo->prepare("SELECT * FROM products WHERE is_active = 1 AND category = ? ORDER BY name");
    $stmt->execute([$selected_category]);
} else {
    $stmt = $pdo->prepare("SELECT * FROM products WHERE is_active = 1 ORDER BY category, name");
    $stmt->execute();
}
$products = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Обработка добавления в корзину
if($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['add_to_cart'])) {
    $product_id = (int)$_POST['product_id'];
    $quantity = max(1, (int)$_POST['quantity']);
    
    // Проверяем наличие товара
    $checkStmt = $pdo->prepare("SELECT stock FROM products WHERE id = ?");
    $checkStmt->execute([$product_id]);
    $product = $checkStmt->fetch();
    
    if($product && $product['stock'] >= $quantity) {
        addToCart($product_id, $quantity);
        $success_message = "Товар добавлен в корзину!";
    } else {
        $error_message = "Недостаточно товара на складе!";
    }
}
?>
<!DOCTYPE html>
<html lang="ru">
<head>
    <meta charset="UTF-8">
    <title>Каталог товаров - Интернет-магазин</title>
    <meta name="description" content="Большой выбор товаров по категориям. Электроника, одежда, книги, товары для дома. Удобная навигация.">
    <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body { font-family: 'Segoe UI', Arial, sans-serif; background: #f0fdf4; line-height: 1.6; }
        header, footer { background: #0f172a; color: #f8fafc; padding: 1rem; text-align: center; }
        nav a { color: #f8fafc; margin: 0 15px; text-decoration: none; transition: 0.3s; }
        nav a:hover { color: #14b8a6; }
        main { max-width: 1400px; margin: 30px auto; padding: 0 20px; min-height: 60vh; }
        h1 { text-align: center; color: #0f172a; margin-bottom: 10px; }
        .subtitle { text-align: center; color: #475569; margin-bottom: 30px; }
        
        .cart-info { background: #fff; padding: 10px 20px; border-radius: 30px; display: inline-block; margin-bottom: 20px; }
        .message { padding: 10px; border-radius: 8px; margin-bottom: 20px; text-align: center; }
        .message-success { background: #dcfce7; color: #166534; }
        .message-error { background: #fee2e2; color: #991b1b; }
        
        .filter-section { background: #fff; padding: 20px; border-radius: 16px; margin-bottom: 30px; box-shadow: 0 2px 10px rgba(0,0,0,0.05); }
        .filter-title { font-size: 1.1rem; font-weight: bold; margin-bottom: 15px; color: #0f172a; }
        .filter-buttons { display: flex; flex-wrap: wrap; gap: 10px; }
        .filter-btn { background: #e2e8f0; color: #0f172a; border: none; padding: 8px 20px; border-radius: 30px; cursor: pointer; transition: 0.3s; text-decoration: none; display: inline-block; font-size: 0.9rem; }
        .filter-btn:hover { background: #cbd5e1; }
        .filter-btn.active { background: #0f766e; color: #fff; }
        
        .products-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: 25px; }
        .product-card { background: #fff; border-radius: 20px; overflow: hidden; box-shadow: 0 5px 20px rgba(0,0,0,0.08); transition: transform 0.3s; }
        .product-card:hover { transform: translateY(-5px); }
        .product-card img { width: 100%; height: 200px; object-fit: cover; }
        .product-info { padding: 20px; }
        .product-name { font-size: 1.2rem; font-weight: bold; color: #0f172a; margin-bottom: 5px; }
        .category-badge { display: inline-block; background: #e2e8f0; color: #475569; padding: 4px 12px; border-radius: 20px; font-size: 0.7rem; margin-bottom: 10px; }
        .description { color: #475569; font-size: 0.85rem; margin: 10px 0; }
        .price { font-size: 1.5rem; font-weight: bold; color: #0f766e; margin: 10px 0; }
        .stock { font-size: 0.75rem; color: #64748b; margin-bottom: 15px; }
        .btn-add { background: #0f766e; color: #fff; border: none; padding: 10px; border-radius: 30px; cursor: pointer; font-weight: bold; width: 100%; transition: 0.3s; }
        .btn-add:hover { background: #0d5c56; }
        footer { margin-top: 50px; }
        .empty-message { text-align: center; padding: 50px; background: #fff; border-radius: 16px; }
        @media (max-width: 768px) { .products-grid { grid-template-columns: 1fr; } .filter-buttons { justify-content: center; } }
    </style>
</head>
<body>
<header>
    <div style="display: flex; justify-content: space-between; align-items: center; flex-wrap: wrap;">
        <h1 style="margin: 0;">🛍️ Интернет-магазин</h1>
        <nav>
            <a href="index.php">📦 Каталог</a>
            <a href="cart.php">🛒 Корзина <?= isset($_SESSION['cart']) && count($_SESSION['cart']) > 0 ? '(' . array_sum($_SESSION['cart']) . ')' : '' ?></a>
            <?php if(isLoggedIn()): ?>
                <a href="my_orders.php">📋 Мои заказы</a>
                <a href="logout.php">🚪 Выйти (<?= h($_SESSION['username']) ?>)</a>
            <?php else: ?>
                <a href="login.php">🔐 Вход</a>
                <a href="register.php">📝 Регистрация</a>
            <?php endif; ?>
        </nav>
    </div>
</header>

<main>
    <h1>📦 Каталог товаров</h1>
    <p class="subtitle">Выберите товары для покупки</p>
    
    <?php if(isset($success_message)): ?>
        <div class="message message-success">✅ <?= h($success_message) ?></div>
    <?php endif; ?>
    <?php if(isset($error_message)): ?>
        <div class="message message-error">❌ <?= h($error_message) ?></div>
    <?php endif; ?>
    
    <div class="filter-section">
        <div class="filter-title">🔍 Фильтр по категории</div>
        <div class="filter-buttons">
            <a href="index.php" class="filter-btn <?= empty($selected_category) ? 'active' : '' ?>">Все товары</a>
            <?php foreach($categories as $cat): ?>
                <a href="?category=<?= urlencode($cat) ?>" class="filter-btn <?= $selected_category == $cat ? 'active' : '' ?>">
                    <?= h($cat) ?>
                </a>
            <?php endforeach; ?>
        </div>
    </div>
    
    <?php if(count($products) > 0): ?>
        <div class="products-grid">
            <?php foreach($products as $product): ?>
                <div class="product-card">
                    <img src="<?= h($product['image_url'] ?: 'img/placeholder.jpg') ?>" alt="<?= h($product['name']) ?>">
                    <div class="product-info">
                        <div class="product-name"><?= h($product['name']) ?></div>
                        <div><span class="category-badge">📁 <?= h($product['category']) ?></span></div>
                        <div class="description"><?= h(mb_substr($product['description'], 0, 80)) ?>...</div>
                        <div class="price"><?= number_format($product['price'], 2) ?> ₽</div>
                        <div class="stock">📦 В наличии: <?= $product['stock'] ?> шт.</div>
                        <form method="POST">
                            <input type="hidden" name="product_id" value="<?= $product['id'] ?>">
                            <input type="number" name="quantity" value="1" min="1" max="<?= $product['stock'] ?>" style="width: 60px; padding: 5px; margin-bottom: 10px;">
                            <button type="submit" name="add_to_cart" class="btn-add">🛒 В корзину</button>
                        </form>
                    </div>
                </div>
            <?php endforeach; ?>
        </div>
    <?php else: ?>
        <div class="empty-message">
            <p>😕 Товаров в выбранной категории не найдено.</p>
            <a href="index.php" class="filter-btn active">Показать все товары</a>
        </div>
    <?php endif; ?>
</main>

<footer>
    <p>&copy; 2025 Интернет-магазин. Лучшие товары по лучшим ценам.</p>
    <p>📍 Доставка по всей России | 📞 8-800-555-35-35 | ✉️ shop@example.com</p>
</footer>
</body>
</html>