<?php
require_once 'config.php';

$selected_genre = isset($_GET['genre']) ? trim($_GET['genre']) : '';
$genres = getAllGenres($pdo);

if($selected_genre && $selected_genre !== '') {
    $stmt = $pdo->prepare("SELECT * FROM audiobooks WHERE is_active = 1 AND genre = ? ORDER BY title");
    $stmt->execute([$selected_genre]);
} else {
    $stmt = $pdo->prepare("SELECT * FROM audiobooks WHERE is_active = 1 ORDER BY genre, title");
    $stmt->execute();
}
$books = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<!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: #f3f4f6; 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: #a855f7; }
        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; }
        
        .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: #7c3aed; color: #fff; }
        .reset-btn { background: #64748b; color: #fff; }
        
        .books-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(300px, 1fr)); gap: 25px; }
        .book-card { background: #fff; border-radius: 20px; overflow: hidden; box-shadow: 0 5px 20px rgba(0,0,0,0.08); transition: transform 0.3s; }
        .book-card:hover { transform: translateY(-5px); }
        .book-card img { width: 100%; height: 280px; object-fit: cover; }
        .book-info { padding: 20px; }
        .book-title { font-size: 1.2rem; font-weight: bold; color: #0f172a; margin-bottom: 5px; }
        .book-author { color: #7c3aed; font-weight: 500; margin-bottom: 8px; }
        .genre-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; line-height: 1.4; }
        .duration { color: #64748b; font-size: 0.8rem; margin-bottom: 15px; }
        .btn { display: inline-block; background: #7c3aed; color: #fff; padding: 10px 20px; text-decoration: none; border-radius: 30px; transition: 0.3s; font-weight: bold; width: 100%; text-align: center; }
        .btn:hover { background: #6d28d9; }
        footer { margin-top: 50px; }
        .empty-message { text-align: center; padding: 50px; background: #fff; border-radius: 16px; }
        @media (max-width: 768px) { .books-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="my_history.php">📜 История</a>
            <?php if(isLoggedIn()): ?>
                <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>
    
    <div class="filter-section">
        <div class="filter-title">🎭 Фильтр по жанру</div>
        <div class="filter-buttons">
            <a href="index.php" class="filter-btn <?= empty($selected_genre) ? 'active' : '' ?>">Все жанры</a>
            <?php foreach($genres as $genre): ?>
                <a href="?genre=<?= urlencode($genre) ?>" class="filter-btn <?= $selected_genre == $genre ? 'active' : '' ?>">
                    <?= h($genre) ?>
                </a>
            <?php endforeach; ?>
        </div>
    </div>
    
    <?php if(count($books) > 0): ?>
        <div class="books-grid">
            <?php foreach($books as $book): ?>
                <div class="book-card">
                    <img src="<?= h($book['cover_image'] ?: 'img/placeholder.jpg') ?>" alt="<?= h($book['title']) ?>">
                    <div class="book-info">
                        <div class="book-title"><?= h($book['title']) ?></div>
                        <div class="book-author">✍️ <?= h($book['author']) ?></div>
                        <div><span class="genre-badge">🎭 <?= h($book['genre']) ?></span></div>
                        <div class="description"><?= h(mb_substr($book['description'], 0, 90)) ?>...</div>
                        <div class="duration">⏱️ <?= formatDuration($book['duration']) ?></div>
                        <a href="book.php?id=<?= $book['id'] ?>" class="btn">🎧 Подробнее</a>
                    </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>🎧 Более 1000 аудиокниг в нашей коллекции</p>
</footer>
</body>
</html>