<?php

require 'connect.php'; 

session_start();

$distinct_genres = [];
$sql_get_distinct_genres = "SELECT DISTINCT genre FROM Book";

$stmt = $conn->prepare($sql_get_distinct_genres);
$stmt->execute();

while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
  $distinct_genres[] = $row['genre'];
}

$year_query = "SELECT MIN(PublishedYear) as min_year, MAX(PublishedYear) as max_year FROM Book";
$year_stmt = $conn->prepare($year_query);
$year_stmt->execute();
$year_range = $year_stmt->fetch(PDO::FETCH_ASSOC);


$where_conditions = [];
$params = [];

$year_from = isset($_GET['year_from']) ? (int)$_GET['year_from'] : null;
$year_to = isset($_GET['year_to']) ? (int)$_GET['year_to'] : null;

$year_min = $year_range['min_year'];
$year_max = $year_range['max_year'];

$query_from = $year_from;
$query_to = $year_to;

if($year_from === null) {
    $query_from = $year_min;
}
if($year_to === null) {
    $query_to = $year_max;
}

    if(isset($_GET['genres'])) {
        $genres_filters = $_GET['genres'];
        $placeholders = str_repeat('?,', count($genres_filters) - 1) . '?';

        $stmt = $conn->prepare("SELECT book.bookid, book.CoverImage, book.Title, book.Genre, book.PublishedYear, author.FirstName, author.LastName
                                FROM Book
                                INNER JOIN Book_Author ON Book.BookID = Book_Author.BookID
                                INNER JOIN Author ON Book_Author.AuthorID = Author.AuthorID
                                WHERE book.genre IN ($placeholders) AND book.PublishedYear BETWEEN ? AND ?;");

        $stmt->execute(array_merge($genres_filters, [$query_from, $query_to]));
    }
    else {
        $genres_filters = [];
        $stmt = $conn->prepare("SELECT book.bookid, book.CoverImage, book.Title, book.Genre, book.PublishedYear, author.FirstName, author.LastName
                                FROM Book
                                INNER JOIN Book_Author ON Book.BookID = Book_Author.BookID
                                INNER JOIN Author ON Book_Author.AuthorID = Author.AuthorID WHERE book.PublishedYear BETWEEN :year_from AND :year_to;
        ");
        $stmt->bindParam(":year_from", $query_from, PDO::PARAM_STR);
        $stmt->bindParam(":year_to", $query_to, PDO::PARAM_STR);
        $stmt->execute();
    }

    if ($year_from !== null) {
        $where_conditions[] = "book.publishedyear >= ?";
        $params[] = $year_from;
    }
    if ($year_to !== null) {
        $where_conditions[] = "book.publishedyear <= ?";
        $params[] = $year_to;
    }

    $all_books = [];

    while($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
      $all_books[] = $row;
    }

    // CART
    if(isset($_GET['submit']) && isset($_GET['bookid'])){

        if(!isset($_SESSION['userid'])) {
            header("Location: ./SignLog.php");
            die();
        }

        $sql = "SELECT * FROM member WHERE memberid = :userid";
        $stmt = $conn->prepare($sql);
        $stmt->bindParam(':userid', $_SESSION['userid'], PDO::PARAM_INT);
        $stmt->execute();

        $row = $stmt->fetch(PDO::FETCH_ASSOC);
        $current_date = date('Y-m-d');

        if($stmt->rowCount() <= 0 || $row['expired_date'] < $current_date || $row['membership_status'] != 'Active') {
            // ne si member ili ti istekol ili ti e neaktiven ili suspendiran
            header("Location: ./Profile.php");
            die();
        }

        if ($_GET['submit'] == 'add-to-cart') {
            try {
                $check_stmt = $conn->prepare("
                            SELECT Cart.*, member.*, book.* FROM CART
                            INNER JOIN Member ON Cart.memberid = member.memberid
                            INNER JOIN Book ON Cart.bookid = Book.bookid
                            WHERE Book.bookid = :bookid AND member.memberid = {$row['memberid']};
                ");

                $check_stmt->bindParam(':bookid', $_GET['bookid'], PDO::PARAM_INT);

                $check_stmt->execute();
                
                if($check_stmt->rowCount() > 0){
                    header("Location: ./Cart.php");
                    die();
                }
                else {
                    // INSERT INTO CART
                    $sql = $conn->prepare('INSERT INTO Cart (BookID, MemberID) VALUES (:book_id, :member_id)');
                    $sql->bindParam(':book_id', $_GET['bookid'], PDO::PARAM_INT);
                    $sql->bindParam(':member_id', $row['memberid'], PDO::PARAM_INT);
                    $sql->execute();
                }
        
                header("Location: ./Cart.php");
                exit();
        
            } catch (PDOException $e) {
                error_log("Database error: " . $e->getMessage());
                echo $e->getMessage();
                echo "An error occurred while adding the book to your cart.";
                exit();
            }
        }
        header("Location: ./Cart.php");
    }
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>All Books</title>
    <link rel="stylesheet" href="CSS/Books.css">

</head>
<body>
  <?php include 'Components/Header.html'; ?>
  

  <main class="books-page">
    <!-- Filters Sidebar -->
    
    <aside class="filters-sidebar">
        <div class="filters-header">
            <h2>Filters</h2>
            <button class="clear-filters">Clear All</button>
        </div>

        <!-- Categories Filter -->
        <form action="./Books.php" method="GET">
        <div class="filter-section">
            <h3>Genre</h3>
            <div class="filter-options">
            <?php
                foreach($distinct_genres as $gen) {
                    echo "<label class='filter-option'>
                        <input type='checkbox' name='genres[]' ".((in_array($gen, $genres_filters)) ? "checked" : "")." value='$gen'> $gen
                        </label>";
                }
              ?>
            </div>
        </div>

        <!-- Publication Year Filter -->
        <div class="filter-section">
            <h3>Publication Year</h3>
            <div class="filter-options">
                <select id="yearFrom" name="year_from">
                    <option value="<?php echo $year_min?>">From</option>
                    <?php
                            for($year = $year_range['max_year']; $year >= $year_range['min_year']; $year--) {
                                $selected = ($year_from == $year) ? 'selected' : '';
                                echo "<option value='$year' $selected>$year</option>";
                            }
                    ?>
                </select>
                <select id="yearTo" name="year_to">
                    <option value="<?php echo $year_max ?>">To</option>
                    <?php
                        for($year = $year_range['max_year']; $year >= $year_range['min_year']; $year--) {
                                $selected = ($year_to == $year) ? 'selected' : '';
                                echo "<option value='$year' $selected>$year</option>";
                            }
                    ?>
                </select>
            </div>
        </div>
        <button type="submit" class="btn-btn-primary">Apply Filters</button>
        </form>
    </aside>

    <!-- Books Content -->
    <section class="books-content">
        <!-- Top Bar -->
        <div class="books-header">
            <div class="results-count">
                <span id="bookCount">0</span> Results
            </div>
            <div class="sort-options">
                <label for="sortBy">Sort by:</label>
                <select id="sortBy">
                    <option value="relevance">Relevance</option>
                    <option value="name-asc">Name: A to Z</option>
                    <option value="name-desc">Name: Z to A</option>
                    <option value="year-desc">Newest to Oldest</option>
                    <option value="year-asc">Oldest to Newest</option>
                </select>
            </div>
        </div>

        <!-- Books Grid -->
        <div class="books-grid" id="booksGrid">
            <!-- Books will be dynamically added here -->
        </div>

        <!-- Pagination -->
        <div class="pagination">
            <button class="pagination-button" id="prevPage">Previous</button>
            <div class="page-numbers" id="pageNumbers">
                Page numbers will be dynamically added here 
            </div>
            <button class="pagination-button" id="nextPage">Next</button>
        </div>

    </section>
</main>


<script>
const allBooks = [
    <?php
    foreach ($all_books as $book) {
        echo "{id: " . htmlspecialchars($book['bookid'], ENT_QUOTES, 'UTF-8') . 
        ", title: '" . htmlspecialchars($book['title'], ENT_QUOTES, 'UTF-8') . 
        "', author: '" . htmlspecialchars($book['firstname'] . " " . $book['lastname'], ENT_QUOTES, 'UTF-8') . 
        "', image: '" . htmlspecialchars($book['coverimage'] ?? '', ENT_QUOTES, 'UTF-8') . 
        "', genre: '" . htmlspecialchars($book['genre'], ENT_QUOTES, 'UTF-8') . 
        "', publishedYear: " . intval($book['publishedyear']) . "},";
    }
    ?>
];

  // State management
  let currentState = {
      filters: {
          genres: <?php echo json_encode($distinct_genres) ?>,
          yearFrom: <?php echo $year_from ? $year_from : 'null' ?>,
          yearTo: <?php echo $year_to ? $year_to : 'null' ?>
      },
      sort: 'relevance',
      page: 1,
      itemsPerPage: 15,
  };

const pages = document.getElementById('pageNumbers');

// Initialize page
document.addEventListener('DOMContentLoaded', () => {

    const sortedBooks = sortBooks(allBooks, currentState.sort);
    allBooks.length = 0;
    allBooks.push(...sortedBooks);

    document.getElementById('nextPage').addEventListener('click', goToNextPage);
    document.getElementById('prevPage').addEventListener('click', goToPrevPage);

    currentState.page = 1;

    initializeGenreDisplay();
    renderPagination();
});


// Render books
function renderBook(cur_book) {
    // Render books
    const card_hidden = document.createElement('input');
    const card_element = document.createElement('form');
    const card_image = document.createElement('img');
    const card_info = document.createElement('div');
    const card_title = document.createElement('h3');
    const card_author = document.createElement('p');
    const card_genre = document.createElement('p');
    const actions_div = document.createElement('div');
    const actions_button = document.createElement('button');

    actions_button.innerHTML = "Add to cart";
    actions_div.appendChild(actions_button);

    card_image.src = "./BookImages/" + cur_book.image;
    card_image.alt = cur_book.title;
    //card_title.innerHTML = cur_book.title;
    card_author.innerHTML = "by " + cur_book.author;
    card_genre.innerHTML = cur_book.genre;

    const titleLink = document.createElement('a');
    titleLink.href = `BookView.php?bookid=${cur_book.id}`;
    titleLink.textContent = cur_book.title;
    titleLink.style.textDecoration = 'none';
    titleLink.style.color = 'green';
    card_title.appendChild(titleLink);

    card_info.appendChild(card_title);
    card_info.appendChild(card_author);
    card_info.appendChild(card_genre);

    card_element.appendChild(card_image);
    card_element.appendChild(card_info);
    card_element.appendChild(actions_div);
    card_element.appendChild(card_hidden);

    card_element.classList.add('book-card');
    card_image.classList.add('book-cover');
    card_info.classList.add('book-info');
    card_title.classList.add('book-title');
    card_author.classList.add('book-author');
    card_genre.classList.add('book-genre');
    actions_div.classList.add('actions');
    actions_button.classList.add('btn', 'btn-primary');
    actions_button.type = 'submit';
    actions_button.value = 'add-to-cart';
    actions_button.name = 'submit';

    card_element.setAttribute('action', './Books.php');
    card_element.setAttribute('method', 'GET');

    card_hidden.setAttribute('type', 'hidden');
    card_hidden.setAttribute('name', 'bookid');
    card_hidden.setAttribute('value', cur_book.id);


    booksGrid.appendChild(card_element)

}

function renderPagination() {

    booksGrid.innerHTML = "";
    document.getElementById('bookCount').textContent = allBooks.length;

    // render books
    for(let i = (currentState.page-1)*currentState.itemsPerPage; i < Math.min(currentState.page*currentState.itemsPerPage, allBooks.length); i++) {
        renderBook(allBooks[i]);
    }
    // Disable/enable prev/next buttons
    document.getElementById('prevPage').disabled = currentState.page === 1;
    document.getElementById('nextPage').disabled = currentState.page === Math.ceil(allBooks.length / currentState.itemsPerPage);

    pages.innerHTML = "";

    for(let i = 0; i < allBooks.length / currentState.itemsPerPage; i++) {
        const page_number = document.createElement('button');
        page_number.classList.add('page-button');
        if(i+1 === currentState.page) {
            page_number.classList.add('active');
        }
        page_number.textContent = i+1;
        page_number.addEventListener('click', () => {
            currentState.page = i+1;
            renderPagination()
        });
        pages.appendChild(page_number);
    }
}

// Clear filters
  document.querySelector('.clear-filters').addEventListener('click', (e) => {
      // Reset filters in the state
      currentState.filters = {
          yearFrom: null,
          yearTo: null,
          genres: []
      };

      // Reset checkboxes
      document.querySelectorAll('.filter-option input[type="checkbox"]').forEach(checkbox => {
          checkbox.checked = false;
      });

      // Reset year dropdowns
      document.getElementById('yearFrom').value = '';
      document.getElementById('yearTo').value = '';

      document.querySelector('form').submit();
  });


  function sortBooks(books, sortType) {
    const sortedBooks = [...books]; 
    
    switch(sortType) {
        case 'name-asc':
            sortedBooks.sort((a, b) => a.title.localeCompare(b.title));
            break;
        case 'name-desc':
            sortedBooks.sort((a, b) => b.title.localeCompare(a.title));
            break;
        case 'year-desc':
            sortedBooks.sort((a, b) => b.publishedYear - a.publishedYear);
            break;
        case 'year-asc':
            sortedBooks.sort((a, b) => a.publishedYear - b.publishedYear);
            break;
        case 'relevance':
        default:
            break;
    }
    
    return sortedBooks;
}

document.getElementById('sortBy').addEventListener('change', (e) => {
    currentState.sort = e.target.value;
    
    const sortedBooks = sortBooks(allBooks, currentState.sort);
    
    allBooks.length = 0;
    allBooks.push(...sortedBooks);
    
    currentState.page = 1;
    
    renderPagination();
});

function goToNextPage() {
    const maxPages = Math.ceil(allBooks.length / currentState.itemsPerPage);
    if (currentState.page < maxPages) {
        currentState.page++;
        renderPagination();
    }
}

function goToPrevPage() {
    if (currentState.page > 1) {
        currentState.page--;
        renderPagination();
    }
}

function initializeGenreDisplay() {
    const GENRES_PER_LOAD = 5;
    const filterOptions = document.querySelector('.filter-options');
    const allGenreLabels = Array.from(filterOptions.querySelectorAll('.filter-option'));
    
    // Hide all genres initially
    allGenreLabels.forEach((label, index) => {
        if (index >= GENRES_PER_LOAD) {
            label.style.display = 'none';
        }
    });
    
    // Only add Show More button if there are more genres to show
    if (allGenreLabels.length > GENRES_PER_LOAD) {
        const showMoreButton = document.createElement('button');
        showMoreButton.setAttribute('type', 'button');
        showMoreButton.textContent = 'Show More';
        showMoreButton.classList.add('show-more-btn');
        filterOptions.appendChild(showMoreButton);
        
        let currentlyShown = GENRES_PER_LOAD;
        
        showMoreButton.addEventListener('click', () => {
            for (let i = currentlyShown; i < Math.min(currentlyShown + GENRES_PER_LOAD, allGenreLabels.length); i++) {
                allGenreLabels[i].style.display = 'block';
            }
            
            currentlyShown += GENRES_PER_LOAD;
            
            if (currentlyShown >= allGenreLabels.length) {
                showMoreButton.style.display = 'none';
            }
        });
    }
}

    const styleSheet = document.createElement('style');
    styleSheet.textContent = `
        .show-more-btn {
            margin-top: 10px;
            padding: 5px 10px;
            background: none;
            border: 1px solid #ccc;
            border-radius: 4px;
            cursor: pointer;
            width: 100%;
            text-align: center;
        }
        
        .show-more-btn:hover {
            background-color: #f5f5f5;
        }
        
        .filter-options {
            display: flex;
            flex-direction: column;
            gap: 8px;
        }
    `;
    document.head.appendChild(styleSheet);


</script>

<?php include 'Components/Footer.html'; ?>
</body>
</html>