<?php

session_start();

require __DIR__ . "/../db/database.php";

// Pieprasījums, kas iegūst visas grāmatas
$sql = "SELECT * FROM books";
$all_books = $mysqli->query($sql);


// Pieprasījums, kas iegūst lietotāja piekļuves id 
$sql = "SELECT * FROM users WHERE id = ". $_SESSION['user_id'];
$result = $mysqli->query($sql);
$user_access = $result->fetch_assoc()['id_access'];

// Ja lietotāja piekļuves id ir 2, novirza lietotāju uz sākumlapu
if($user_access == 2){
    header("Location: http://localhost/projectlasitava/homepage/homepage.php");
}
?>

<!DOCTYPE html>
<html lang="lv">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Grāmatu pārvalde</title>
    <link rel="stylesheet" href="controlpanel.css"> 
</head>

<body>
    <!-- Pārbauda, vai lietotājs ir pierakstījies -->
    <?php if (isset($_SESSION["user_id"])): ?>   
    <!-- Ja ir, tad parāda šo lapu -->
    <div class="topSection">
            <a href="../login/logout.php" id="logout">Izrakstīties</a> 
    </div>
    
    <h1>Grāmatu pārvalde</h1> 
     
    <!-- Pārslēdzamās sadaļas -->
    <div class="middleSection">
        <button id="viewBooks">Visas grāmatas</button> 
        <button id="createBook">Izveidot jaunu grāmatu</button> 
    </div>

    <!-- Visas grāmatas sadaļa -->
    <div class="contentSection">
        <!-- Izvada visas grāmatas -->
        <?php while($row = mysqli_fetch_assoc($all_books)): ?> 
        <div class="card">
            <div class="image">
                <img src="<?php echo "../uploads/" . $row["image"]?>" alt=""> 
            </div>

            <div class="info">
            <h2 class="heading" title="<?php echo $row["title"]?>">
                <?php echo mb_strlen($row["title"]) > 15 ? mb_substr($row["title"], 0, 8) . '...' : $row["title"] ?>
            </h2> 
                <p class="description"><?php echo $row["description"];?></p> 
            </div>

            <div class="buttons">
                <!-- Poga, lai izdzēstu grāmatu -->
                <button id="delete" data-book-id="<?php echo $row['id']; ?>">X</button> 
                <!-- Poga, lai rediģētu grāmatu -->
                <button id="edit" data-book-id="<?php echo $row['id']; ?>"><img src="../uploads/edit_icon.png"></button> 
            </div>

        </div>
        <?php endwhile; ?>
    </div>
    
    <!-- Grāmatas izveides sadaļa -->
    <div class="createSection">
        <form action="controlpanelform.php" method="post" enctype="multipart/form-data">
            <input type="hidden" name="id" id="bookId" value=""> 
            <label for="title">Nosaukums: </label>
            <input type="text" id="title" name="title" maxlength="200"> 

            <br>

            <label for="author">Autors: </label>
            <input type="text" id="author" name="author" maxlength="200"> 

            <br>

            <label for="year">Gads: </label>
            <input type="number" id="year" name="year" minlength="1" maxlength="4"> 

            <br>

            <label for="description">Apraksts: </label>
            <input type="text" id="description" name="description" maxlength="2000" cols="100" rows="5"> 

            <br>

            <label for="image">Bilde: </label>
            <input type="file" id="image" name="image" maxlength="2000" accept="image/*">

            <br>
            <input id="submit" type="submit" value="Izveidot"> 
        </form>        
    </div>
    
    <!-- Apstiprinājuma logs grāmatas dzēšanai -->
    <div id="popup" class="popup" style="display: none"> 
    <div class="popup-content">
        <span class="close-btn" onclick="closePopup()">&times;</span> 
        <br>
        <div class="popup-title">
            <b>Vai gribat izdēst šo grāmatu?<b> 
        </div>
        <hr>
        <div class="popup-content" id="popupContent">
        </div>
        <hr>
        <br>
        <br>
        <br>
        <div class="confirm-btns">
            <button id="confirmButton">Apstiprināt</button>  
            <button id="cancelButton" onclick="closePopup()">Atcelt</button> 
        </div>
    </div>
    </div>

    <script>

    document.addEventListener("DOMContentLoaded", function() {
        const viewBooks = document.getElementById("viewBooks");
        const createBook = document.getElementById("createBook");
        const contentSection = document.getElementsByClassName("contentSection")[0];
        const createSection = document.getElementsByClassName("createSection")[0];

        // Iestata, ka "Visas grāmatas" sadaļa vienmēr būs redzama
        contentSection.style.display = "flex";
        createSection.style.display = "none";

        viewBooks.addEventListener("click", function() {
            contentSection.style.display = "flex";
            createSection.style.display = "none";
        });

        createBook.addEventListener("click", function() {
            createSection.style.display = "block";
            contentSection.style.display = "none";
            document.getElementById('submit').value = 'Izveidot';
            document.getElementById('bookId').value = '';
            document.getElementById('title').value = '';
            document.getElementById('author').value = '';
            document.getElementById('year').value = '';
            document.getElementById('description').value = '';
        });

        // Dzēšanas poga
        const deleteButtons = document.querySelectorAll('#delete');
            deleteButtons.forEach(button => {
                button.addEventListener('click', function() {
                    const bookId = this.getAttribute('data-book-id');
                    openPopup(bookId)
                });
            });

        // Rediģēšanas poga
        const editButtons = document.querySelectorAll('#edit');
            editButtons.forEach(button => {
                button.addEventListener('click', function() {
                    const bookId = this.getAttribute('data-book-id');
                    openEdit(bookId);
                });
            });
        });

        //Funkcija, kas pārslēdz apstiprinājuma loga redzamību
        function togglePopup(bookId) {
            var popup = document.getElementById("popup");

            if (popup.style.display === "block") {
                closePopup();

            } else {
                openPopup(BookId);

            }
        }

        // Funkcija, kas parāda logu un grāmatas datus
        function openPopup(bookId) {
            var xhr = new XMLHttpRequest();

            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4 && xhr.status == 200) {
                    document.getElementById("popupContent").innerHTML = xhr.responseText;
                    document.getElementById("popup").style.display = "block";
                }
            };

            xhr.open('GET', 'getPopupBookDetails.php?id=' + bookId, true);
            xhr.send();

            var confirmButton = document.getElementById("confirmButton");

            confirmButton.removeEventListener('click', confirmButtonClickHandler);

            confirmButton.addEventListener('click', function() {
                confirmButtonClickHandler(bookId);
            });
        }

        // Funkcija, kas atbild par apstiprinājuma pogu
        function confirmButtonClickHandler(bookId) {
            confirmPopup(bookId);
        }


        // Aizver logu
        function closePopup() {
            document.getElementById("popup").style.display = "none";
        }

        // Funkcija, kas atbild par apstiprinājuma logu
        function confirmPopup(bookId) {
            const button = document.querySelector(`button[data-book-id="${bookId}"]`);

            if (button) {
                const card = button.closest('.card');
                const xhr = new XMLHttpRequest();
                xhr.open('GET', `deletebook.php?id=${bookId}`); 
                xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                xhr.onload = function() {
                    if (xhr.status === 200) {
                        card.parentNode.removeChild(card);
                    } else {
                        console.error('Kļūda dzēšot grāmatu');
                    }
                };
                xhr.send('book_id=' + encodeURIComponent(bookId));
                closePopup();
            }

            
        }

        // Funkcija, kas ļauj rediģēt grāmatu
        function openEdit(bookId){

            const xhr = new XMLHttpRequest();
            xhr.open('GET', `getBookInfo.php?id=${bookId}`); 
            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
            xhr.onload = function() {
                if (xhr.status === 200) {
                    const data = JSON.parse(xhr.responseText);

                    document.getElementById("createBook").dispatchEvent(new Event('click'));

                    document.getElementById('title').value = data['title'];
                    document.getElementById('author').value = data['author'];
                    document.getElementById('year').value = data['year'];
                    document.getElementById('description').value = data['description'];
                    

                    document.getElementById('submit').value = 'Atjaunot';
                    
                    document.getElementById('bookId').value = bookId;
                } else {
                    console.error('Error getting book');
                }
            };
            xhr.send('book_id=' + encodeURIComponent(bookId));
        }
    </script>

    <?php endif; ?>
    
</body>
</html>