<?php
include 'db.php';

$topic  = isset($_POST['topic'])  ? $_POST['topic']  : "";
$search = isset($_POST['search']) ? trim($_POST['search']) : "";
$page   = isset($_POST['page']) && is_numeric($_POST['page']) ? (int)$_POST['page'] : 1;

$perPage = 6;
$offset  = ($page - 1) * $perPage;

$where  = "WHERE 1=1";
$params = [];

if ($topic != "") {
    $where .= " AND topics.id = :topic";
    $params[':topic'] = $topic;
}
if ($search != "") {
    $where .= " AND books.title LIKE :search";
    $params[':search'] = "%" . $search . "%";
}

$stmtCount = $pdo->prepare("SELECT COUNT(*) FROM books JOIN topics ON books.topic_id = topics.id $where");
$stmtCount->execute($params);
$total = $stmtCount->fetchColumn();

$stmt = $pdo->prepare("SELECT books.title, books.author, books.image, topics.name AS topic
                        FROM books JOIN topics ON books.topic_id = topics.id
                        $where LIMIT :limit OFFSET :offset");
foreach ($params as $key => $val) {
    $stmt->bindValue($key, $val);
}
$stmt->bindValue(':limit',  $perPage, PDO::PARAM_INT);
$stmt->bindValue(':offset', $offset,  PDO::PARAM_INT);
$stmt->execute();
$books = $stmt->fetchAll(PDO::FETCH_ASSOC);

echo json_encode([
    'books'      => $books,
    'total'      => $total,
    'totalPages' => ceil($total / $perPage),
    'page'       => $page
]);
