<?php
include 'db.php';
include 'header.php';

$stmtTopics = $pdo->prepare("SELECT * FROM topics");
$stmtTopics->execute();
$topics = $stmtTopics->fetchAll(PDO::FETCH_ASSOC);

$cartCount = isset($_SESSION['cart']) ? count($_SESSION['cart']) : 0;
?>

<style>
    .top-bar { display: flex; justify-content: flex-end; margin-bottom: 15px; }
    .cart-link {
        background: #27ae60;
        color: white;
        padding: 8px 18px;
        border-radius: 5px;
        text-decoration: none;
        font-size: 14px;
    }
    .cart-link:hover { background: #1e8449; }
    .search-box {
        background: white;
        padding: 20px 25px;
        border-radius: 8px;
        margin-bottom: 25px;
        box-shadow: 0 1px 4px rgba(0,0,0,0.1);
    }
    .search-box h2 { margin-top: 0; font-size: 17px; color: #2c3e50; }
    .search-box form { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; }
    select, input[type=text] {
        padding: 8px 12px; font-size: 14px;
        font-family: Tahoma, sans-serif;
        border: 1px solid #ccc; border-radius: 5px;
    }
    input[type=text] { flex: 1; min-width: 160px; }
    button {
        padding: 8px 18px; background-color: #2980b9; color: white;
        border: none; border-radius: 5px; font-size: 14px;
        font-family: Tahoma, sans-serif; cursor: pointer;
    }
    button:hover { background-color: #1a6fa0; }
    .result-count { margin-bottom: 15px; font-size: 13px; color: #666; }
    .books-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(180px, 1fr));
        gap: 20px;
        margin-bottom: 30px;
    }
    .book-card {
        background: white; border-radius: 10px;
        box-shadow: 0 2px 6px rgba(0,0,0,0.1);
        overflow: hidden; transition: transform 0.2s;
    }
    .book-card:hover { transform: translateY(-4px); }
    .book-card img { width: 100%; height: 200px; object-fit: cover; display: block; }
    .book-info { padding: 12px; }
    .book-info h3 { margin: 0 0 6px 0; font-size: 14px; color: #2c3e50; line-height: 1.4; }
    .book-info .author { font-size: 12px; color: #777; margin: 0 0 8px 0; }
    .book-info .topic-badge {
        display: inline-block; background: #2980b9;
        color: white; font-size: 11px; padding: 2px 8px; border-radius: 10px;
    }
    .btn-add-cart {
        display: block; width: 100%; margin-top: 10px;
        padding: 7px 0; background: #27ae60; color: white;
        border: none; border-radius: 5px; font-size: 13px;
        font-family: Tahoma, sans-serif; cursor: pointer; text-align: center;
    }
    .btn-add-cart:hover { background: #1e8449; }
    .btn-add-cart.added { background: #aaa; cursor: default; }
    .pagination { text-align: center; margin-top: 10px; }
    .pagination button {
        margin: 3px; padding: 7px 13px; border-radius: 5px;
        font-size: 14px; font-family: Tahoma, sans-serif;
        background: white; color: #2980b9; border: 1px solid #ccc; cursor: pointer;
    }
    .pagination button.active { background: #2980b9; color: white; border-color: #2980b9; }
    .pagination button:hover:not(.active) { background: #eaf4fb; }
    .no-result { text-align: center; color: #999; padding: 40px; }
</style>

<script src="jquery-3.7.1.min.js"></script>
<script>

var cartTitles = <?php echo json_encode(array_column($_SESSION['cart'] ?? [], 'title')); ?>;

function loadBooks(page) {
    if (!page) page = 1;
    var topic  = $('#topic').val();
    var search = $('#search').val();

    // URL رو آپدیت کن بدون رفرش صفحه
    var newUrl = 'index.php?page=' + page + '&topic=' + encodeURIComponent(topic) + '&search=' + encodeURIComponent(search);
    history.replaceState(null, '', newUrl);

    $.post('fetchBooks.php', { topic: topic, search: search, page: page },
        function(data) {
            var res = JSON.parse(data);
            var books = res.books;

            $('#result-count').text('تعداد کتاب‌ها: ' + res.total);

            var txt = '';
            if (books.length == 0) {
                txt = '<p class="no-result">کتابی یافت نشد.</p>';
                $('#books-grid').html(txt);
            } else {
                books.forEach(function(book) {
                    var inCart = cartTitles.indexOf(book.title) !== -1;
                    var btnClass = inCart ? 'btn-add-cart added' : 'btn-add-cart';
                    var btnText  = inCart ? '✓ در سبد' : '🛒 افزودن به سبد';
                    var btnDisabled = inCart ? 'disabled' : '';

                    txt += '<div class="book-card">';
                    txt += '<img src="' + book.image + '" alt="' + book.title + '">';
                    txt += '<div class="book-info">';
                    txt += '<h3>' + book.title + '</h3>';
                    txt += '<p class="author">' + book.author + '</p>';
                    txt += '<span class="topic-badge">' + book.topic + '</span>';
                    txt += '<form method="POST" action="add_to_cart.php">';
                    txt += '<input type="hidden" name="title"       value="' + book.title  + '">';
                    txt += '<input type="hidden" name="author"      value="' + book.author + '">';
                    txt += '<input type="hidden" name="image"       value="' + book.image  + '">';
                    txt += '<input type="hidden" name="current_url" value="' + window.location.href + '">';
                    txt += '<button type="submit" class="' + btnClass + '" ' + btnDisabled + '>' + btnText + '</button>';
                    txt += '</form>';
                    txt += '</div></div>';
                });
                $('#books-grid').html(txt);
            }

            var pages = '';
            for (var i = 1; i <= res.totalPages; i++) {
                var active = (i == res.page) ? 'active' : '';
                pages += '<button class="' + active + '" onclick="loadBooks(' + i + ')">' + i + '</button>';
            }
            $('#pagination').html(pages);
        }
    );
}

$(document).ready(function() {
    // لود کردن صفحه قبل هنگام بازگشت 
    var params = new URLSearchParams(window.location.search);
    var initPage   = params.get('page')   || 1;
    var initTopic  = params.get('topic')  || '';
    var initSearch = params.get('search') || '';

    if (initTopic)  $('#topic').val(initTopic);
    if (initSearch) $('#search').val(initSearch);

    loadBooks(initPage);
});
</script>

<div class="top-bar">
    <a href="cart.php" class="cart-link">🛒 سبد خرید (<?php echo $cartCount; ?>)</a>
</div>

<div class="search-box">
    <h2>🔍 جستجوی کتاب</h2>
    <form onsubmit="return false;">
        <label>موضوع:</label>
        <select id="topic">
            <option value="">-- همه --</option>
            <?php foreach ($topics as $t): ?>
                <option value="<?php echo $t['id']; ?>"><?php echo $t['name']; ?></option>
            <?php endforeach; ?>
        </select>
        <input type="text" id="search" placeholder="جستجوی عنوان کتاب...">
        <button onclick="loadBooks(1)">جستجو</button>
    </form>
</div>

<p class="result-count" id="result-count"></p>
<div class="books-grid" id="books-grid"></div>
<div class="pagination" id="pagination"></div>

<?php include 'footer.php'; ?>
