From e7a839ae2ba2eb9646f7916c619e62348aea2de1 Mon Sep 17 00:00:00 2001
From: Naufal-Nalendra <16521240@std.stei.itb.ac.id>
Date: Sun, 8 Oct 2023 11:47:44 +0700
Subject: [PATCH] feat: delete bookmark and prevent duplicate

---
 app/controllers/User.php        |  17 ++++
 app/models/BookModel.php        |  26 ++++--
 app/views/bookmark/bookmark.php |   6 +-
 mysql/#innodb_redo/#ib_redo9    | Bin 3276800 -> 3276800 bytes
 public/js/bookmark.js           | 140 ++++++++++++++++----------------
 5 files changed, 112 insertions(+), 77 deletions(-)

diff --git a/app/controllers/User.php b/app/controllers/User.php
index f6cd5a3..5022de9 100644
--- a/app/controllers/User.php
+++ b/app/controllers/User.php
@@ -48,6 +48,23 @@ class User extends Controller {
             $this->view('login/login');
         }
     }
+    public function deletebookmark()
+    {   
+        if (isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'user') {
+            // Check if 'id' was sent via POST
+            if (isset($_POST['id']) && isset($_POST['bookid'])) {
+                // Access the 'id' value from $_POST
+                $id = $_POST['id'];
+                $bookid = $_POST['bookid'];
+                
+                $this->model('BookModel')->deleteBookmark($id, $bookid);
+                $this->bookmark();
+
+            } 
+        } else {
+            $this->view('login/login');
+        }
+    }
 
 
     public function bookdetail($page = 1)
diff --git a/app/models/BookModel.php b/app/models/BookModel.php
index 5901986..bd59a6d 100644
--- a/app/models/BookModel.php
+++ b/app/models/BookModel.php
@@ -47,13 +47,12 @@ class BookModel
         return 1;
     }
     public function getAllBookmark($limit, $offset){
-        $this->database->query("SELECT title, author.name, category FROM book JOIN author ON book.author_id = author.id JOIN inventory ON book.id = inventory.book_id JOIN user ON user.id = inventory.user_id LIMIT $limit OFFSET $offset");
-        // var_dump($_SESSION['username']);
-        // $this->database->bind('username', $_SESSION['username']);
+        $this->database->query("SELECT book.id, title, author.name, category FROM book JOIN author ON book.author_id = author.id JOIN inventory ON book.id = inventory.book_id JOIN user ON user.id = inventory.user_id WHERE user.id = :id LIMIT $limit OFFSET $offset");
+        $this->database->bind('id', $_SESSION['id']);
         return $this->database->resultSet();
     }
     public function getAllBookList($limit, $offset){
-        $this->database->query("SELECT book.id,title, author.name, category FROM book JOIN author ON book.author_id = author.id LIMIT $limit OFFSET $offset");
+        $this->database->query("SELECT book.id, title, author.name, category FROM book JOIN author ON book.author_id = author.id LIMIT $limit OFFSET $offset");
         return $this->database->resultSet();
     }
     public function getBookDetail($id){
@@ -62,7 +61,24 @@ class BookModel
         return $this->database->single();
     }
     public function addBookmark($id, $bookid){
-        $this->database->query("INSERT INTO inventory VALUES (:id, :bookid)");
+        // Check if the tuple exists
+        $this->database->query("SELECT * FROM inventory WHERE user_id = :id AND book_id = :bookid");
+        $this->database->bind('id', $id);
+        $this->database->bind('bookid', $bookid);
+        $this->database->execute();
+        $existingTuple = $this->database->single();
+    
+        if (!$existingTuple) {
+            // The tuple doesn't exist, so insert it
+            $this->database->query("INSERT INTO inventory (id, bookid) VALUES (:id, :bookid)");
+            $this->database->bind('id', $id);
+            $this->database->bind('bookid', $bookid);
+            $this->database->execute();
+        } 
+    }
+    
+    public function deleteBookmark($id, $bookid){
+        $this->database->query("DELETE FROM inventory WHERE user_id = :id AND book_id = :bookid");
         $this->database->bind('id', $id);
         $this->database->bind('bookid', $bookid);
         $this->database->execute();
diff --git a/app/views/bookmark/bookmark.php b/app/views/bookmark/bookmark.php
index 3c562bd..6808638 100644
--- a/app/views/bookmark/bookmark.php
+++ b/app/views/bookmark/bookmark.php
@@ -23,9 +23,11 @@
 
     if (!empty($data['book'])) {
         foreach ($data['book'] as $row) {
+            $bookid = $row['id'];
             $title = $row['title'];
             $author = $row['name'];
             $category = $row['category'];
+            $id = $_SESSION['id'];
 
             if ($boxCount % 2 == 0) {
                 if ($boxCount > 0) {
@@ -65,9 +67,9 @@
                     <h2><?php echo $author ?></h2>
                     <p id="<?php echo $paragraphId; ?>"><br><?php echo $category; ?></p>
                     <hr class="bookmark-line">
-                    <form action="<?php echo BASEURL; ?>/user/addbookmark/" method="post" class="bookmark-form">
+                    <form action="<?php echo BASEURL; ?>/user/deletebookmark/" method="post" class="bookmark-form">
                         <input type="hidden" name="id" value="<?php echo $id; ?>">
-                        <input type="hidden" name="bookid" value="<?php echo $bookid; ?>">
+                        <input type="hidden" name="bookid" value="<?php echo $bookid; ?>">      
                         <button type="submit" class="delete-bookmark">Delete</button>
                     </form>
 
diff --git a/mysql/#innodb_redo/#ib_redo9 b/mysql/#innodb_redo/#ib_redo9
index 34358d16f4babb0f01c12a0c8ec3fcec820c5eeb..3ba183b2bb5ff1b0ad1acd9d599e1afaff19f0c2 100644
GIT binary patch
delta 196
zcmXBIIZi@R06@{a&l4^R0-`bq$e`kcXivvhSO@vBxJ#iXp|GNNF_2K2NC64OX-=B{
zhV*DzOftKDbrs?!#O-Fi`U#U!A&Fu4KRacd&YRyzkVG;P<xH}YljG;*TrQ*_MY)uc
zl%*n9Qk84Dkz1)rT^iDqJ84N<I&v>v=}BJ(@*t1$Btv<Y7kQO8d6$uV$XGrXeEl5&
DGVn6$

delta 196
zcmXBIJ5B;o06@{aVUWvLQ4mq^2ZAUFbQTnp?8e?|VsY2N3g}EsC~Pg+0J|Wel@1b$
z)0`w(h2-F;7^Swkk7bBAA%35)zkkDIP>ABN&Hf#8H=TWcAweQZNi1nOk&GNZD>=za
zL5fn6Q#q5eoXdq&q$-zElPjsqwcJQUnsO_5axV|^C@pErlXRpj&(f0@d6m8l<V}V$
IS}^|K186KU;Q#;t

diff --git a/public/js/bookmark.js b/public/js/bookmark.js
index fb23414..89eb280 100644
--- a/public/js/bookmark.js
+++ b/public/js/bookmark.js
@@ -1,85 +1,85 @@
 // JavaScript code for handling bookmark popups and buttons
 
-var editButtons = document.querySelectorAll('.edit-button');
-
-editButtons.forEach(function (button) {
-    button.addEventListener('click', function () {
-        var boxIndex = button.getAttribute('data-box-index');
-        var editPopup = document.getElementById('editPopup' + boxIndex);
-        var editTextbox = document.getElementById('editTextbox' + boxIndex);
-
-        editPopup.classList.add('show');
-
-        document.getElementById('continueButtonEdit' + boxIndex).addEventListener('click', function () {
-            var paragraph = document.getElementById('paragraph' + boxIndex);
-            paragraph.textContent = editTextbox.value;
-            editPopup.classList.remove('show');
-        });
-
-        document.getElementById('cancelButtonEdit' + boxIndex).addEventListener('click', function () {
-            editPopup.classList.remove('show');
-        });
-    });
-});
-
-var deleteButtons = document.querySelectorAll('.delete-button');
-
-deleteButtons.forEach(function (button) {
-    button.addEventListener('click', function () {
-        var boxIndex = button.getAttribute('id').replace('deleteButton', '');
-        var deletePopup = document.getElementById('deletePopup' + boxIndex);
+// var editButtons = document.querySelectorAll('.edit-button');
+
+// editButtons.forEach(function (button) {
+//     button.addEventListener('click', function () {
+//         var boxIndex = button.getAttribute('data-box-index');
+//         var editPopup = document.getElementById('editPopup' + boxIndex);
+//         var editTextbox = document.getElementById('editTextbox' + boxIndex);
+
+//         editPopup.classList.add('show');
+
+//         document.getElementById('continueButtonEdit' + boxIndex).addEventListener('click', function () {
+//             var paragraph = document.getElementById('paragraph' + boxIndex);
+//             paragraph.textContent = editTextbox.value;
+//             editPopup.classList.remove('show');
+//         });
+
+//         document.getElementById('cancelButtonEdit' + boxIndex).addEventListener('click', function () {
+//             editPopup.classList.remove('show');
+//         });
+//     });
+// });
+
+// var deleteButtons = document.querySelectorAll('.delete-button');
+
+// deleteButtons.forEach(function (button) {
+//     button.addEventListener('click', function () {
+//         var boxIndex = button.getAttribute('id').replace('deleteButton', '');
+//         var deletePopup = document.getElementById('deletePopup' + boxIndex);
         
-        // Extract the employee number from the data attribute
-        var title = button.getAttribute('data-employee-number');
+//         // Extract the employee number from the data attribute
+//         var title = button.getAttribute('data-employee-number');
 
-        document.getElementById('continueButtonDelete' + boxIndex).addEventListener('click', function () {
-            // Use AJAX to send a request to delete the record
-            var xhr = new XMLHttpRequest();
-            xhr.open('POST', 'http://localhost:8080/app/views/bookmark/delete.php', true);
-            xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
+//         document.getElementById('continueButtonDelete' + boxIndex).addEventListener('click', function () {
+//             // Use AJAX to send a request to delete the record
+//             var xhr = new XMLHttpRequest();
+//             xhr.open('POST', 'http://localhost:8080/app/views/bookmark/delete.php', true);
+//             xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
 
-            // Define the data to send (e.g., employee number)
-            var data = 'title=' + encodeURIComponent(title);
+//             // Define the data to send (e.g., employee number)
+//             var data = 'title=' + encodeURIComponent(title);
 
-            xhr.onload = function () {
-                if (xhr.status === 200) {
+//             xhr.onload = function () {
+//                 if (xhr.status === 200) {
                     
-                    try {
-                        console.log(xhr.responseText);
-                        var response = JSON.parse(xhr.responseText);
-                        if (response.success) {
-                            // Record deleted successfully, remove the bookmark box
-                            var bookmarkBox = document.querySelector('.bookmark-box[data-box-index="' + boxIndex + '"]');
-                            if (bookmarkBox) {
-                                var container = bookmarkBox.parentNode;
-                                container.removeChild(bookmarkBox);
-                            }
-                        } else {
-                            // Handle deletion failure (e.g., display an error message)
-                            console.error('Deletion failed: ' + response.message);
-                        }
-                    } catch (e) {
-                        console.error('JSON parsing error: ' + e.message);
-                    }
-                } else {
-                    // Handle AJAX request error
-                    console.error('AJAX request error');
-                }
-            };
+//                     try {
+//                         console.log(xhr.responseText);
+//                         var response = JSON.parse(xhr.responseText);
+//                         if (response.success) {
+//                             // Record deleted successfully, remove the bookmark box
+//                             var bookmarkBox = document.querySelector('.bookmark-box[data-box-index="' + boxIndex + '"]');
+//                             if (bookmarkBox) {
+//                                 var container = bookmarkBox.parentNode;
+//                                 container.removeChild(bookmarkBox);
+//                             }
+//                         } else {
+//                             // Handle deletion failure (e.g., display an error message)
+//                             console.error('Deletion failed: ' + response.message);
+//                         }
+//                     } catch (e) {
+//                         console.error('JSON parsing error: ' + e.message);
+//                     }
+//                 } else {
+//                     // Handle AJAX request error
+//                     console.error('AJAX request error');
+//                 }
+//             };
             
             
 
-            xhr.send(data);
+//             xhr.send(data);
 
-            deletePopup.classList.remove('show');
-        });
+//             deletePopup.classList.remove('show');
+//         });
 
-        document.getElementById('cancelButtonDelete' + boxIndex).addEventListener('click', function () {
-            deletePopup.classList.remove('show');
-        });
-        deletePopup.classList.add('show');
-    });
-});
+//         document.getElementById('cancelButtonDelete' + boxIndex).addEventListener('click', function () {
+//             deletePopup.classList.remove('show');
+//         });
+//         deletePopup.classList.add('show');
+//     });
+// });
 
 
 
-- 
GitLab