-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbooks.php
More file actions
529 lines (489 loc) · 23.9 KB
/
books.php
File metadata and controls
529 lines (489 loc) · 23.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
<?php
session_start();
include "connection.php";
// Check if student is logged in
if (!isset($_SESSION['student_reg_no'])) {
header("Location: student_login.php");
exit();
}
$student_reg_no = $_SESSION['student_reg_no'];
$student_name = $_SESSION['student_name'] ?? '';
// Fetch student email and id from students table using registration number
$stmt_student_info = $db->prepare("SELECT id, email FROM students WHERE registration_no = ?");
$stmt_student_info->bind_param("s", $student_reg_no);
$stmt_student_info->execute();
$result_info = $stmt_student_info->get_result();
$student_email = '';
$student_id = null;
if ($row_info = $result_info->fetch_assoc()) {
$student_email = $row_info['email'];
$student_id = $row_info['id'];
}
$stmt_student_info->close();
// Fetch max_reservations from system_settings
$settings_result = mysqli_query($db, "SELECT max_reservations FROM system_settings WHERE id=1");
$max_reservations = 3; // default
if ($settings_result && mysqli_num_rows($settings_result) > 0) {
$row = mysqli_fetch_assoc($settings_result);
$max_reservations = intval($row['max_reservations']);
}
// Count current active bookings for the student
$current_bookings = 0;
if (!empty($student_email)) {
$count_sql = "SELECT COUNT(*) as count FROM reservations WHERE student_email = ? AND status = 'Booked'";
$stmt = $db->prepare($count_sql);
$stmt->bind_param("s", $student_email);
$stmt->execute();
$result_count = $stmt->get_result();
if ($row_count = $result_count->fetch_assoc()) {
$current_bookings = intval($row_count['count']);
}
$stmt->close();
}
$message = '';
$message_type = '';
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
if (isset($_POST['action'])) {
$book_id = intval($_POST['book_id']);
$action = $_POST['action'];
if ($action === 'reserve') {
// Validate book exists
$stmt_check = $db->prepare("SELECT id FROM reservations WHERE student_email = ? AND book_id = ? AND status IN ('Booked', 'Issued')");
$stmt_check->bind_param("si", $student_email, $book_id);
$stmt_check->execute();
$reservation_exists = $stmt_check->get_result()->num_rows > 0;
$stmt_check->close();
if ($reservation_exists) {
$message = 'You have already booked this book!';
$message_type = 'warning';
} elseif ($current_bookings >= $max_reservations) {
$message = "You have reached the maximum number of active reservations allowed ($max_reservations).";
$message_type = 'warning';
} else {
// Check book quantity
$stmt_quantity = $db->prepare("SELECT quantity FROM books WHERE id = ?");
$stmt_quantity->bind_param("i", $book_id);
$stmt_quantity->execute();
$quantity_result = $stmt_quantity->get_result()->fetch_assoc();
$stmt_quantity->close();
if ($quantity_result && $quantity_result['quantity'] > 0) {
// Reserve the book
$stmt_reserve = $db->prepare("INSERT INTO reservations (student_name, student_email, book_id, status, reservation_date) VALUES (?, ?, ?, 'Booked', NOW())");
$stmt_reserve->bind_param("ssi", $student_name, $student_email, $book_id);
$reserved = $stmt_reserve->execute();
if (!$reserved) {
error_log("Failed to insert reservation: " . $stmt_reserve->error);
} else {
error_log("Reservation inserted: student_email={$student_email}, book_id={$book_id}");
}
$stmt_reserve->close();
if ($reserved) {
$message = 'Booked successfully!';
$message_type = 'success';
// Redirect to avoid form resubmission and stay on the same page
$redirect_url = 'books.php';
$query_params = [];
if (!empty($_GET['search'])) {
$query_params['search'] = $_GET['search'];
}
if (!empty($_GET['page'])) {
$query_params['page'] = $_GET['page'];
}
if (!empty($query_params)) {
$redirect_url .= '?' . http_build_query($query_params);
}
header("Location: $redirect_url");
exit();
} else {
$message = 'Failed to reserve the book. Please try again.';
$message_type = 'danger';
}
} else {
$message = 'This book is currently unavailable.';
$message_type = 'warning';
}
}
} elseif ($action === 'unreserve') {
// Unbook the book
$stmt_unreserve = $db->prepare("DELETE FROM reservations WHERE student_email = ? AND book_id = ?");
$stmt_unreserve->bind_param("si", $student_email, $book_id);
$unreserved = $stmt_unreserve->execute();
$stmt_unreserve->close();
if ($unreserved) {
$message = 'Booking cancelled successfully!';
$message_type = 'success';
// Redirect to avoid form resubmission and stay on the same page
$redirect_url = 'books.php';
$query_params = [];
if (!empty($_GET['search'])) {
$query_params['search'] = $_GET['search'];
}
if (!empty($_GET['page'])) {
$query_params['page'] = $_GET['page'];
}
if (!empty($query_params)) {
$redirect_url .= '?' . http_build_query($query_params);
}
header("Location: $redirect_url");
exit();
} else {
$message = 'Failed to cancel the booking. Please try again.';
$message_type = 'danger';
}
}
} elseif (isset($_POST['selected_books']) && is_array($_POST['selected_books'])) {
// Handle adding selected books to cart
if (empty($student_email)) {
$message = "Error: Student email not found. Cannot add books to cart.";
$message_type = 'danger';
} else {
$selected_books = $_POST['selected_books'];
$added_count = 0;
foreach ($selected_books as $book_id) {
$book_id = intval($book_id);
// Check if already in cart
$stmt_check_cart = $db->prepare("SELECT id FROM cart WHERE student_email = ? AND book_id = ?");
$stmt_check_cart->bind_param("si", $student_email, $book_id);
$stmt_check_cart->execute();
$already_in_cart = $stmt_check_cart->get_result()->num_rows > 0;
$stmt_check_cart->close();
if (!$already_in_cart) {
// Insert into cart
$stmt_insert_cart = $db->prepare("INSERT INTO cart (student_email, book_id) VALUES (?, ?)");
$stmt_insert_cart->bind_param("si", $student_email, $book_id);
$inserted = $stmt_insert_cart->execute();
if (!$inserted) {
error_log("Failed to insert into cart: " . $stmt_insert_cart->error);
}
$stmt_insert_cart->close();
if ($inserted) {
$added_count++;
}
}
}
if ($added_count > 0) {
$message = "$added_count book(s) added to cart successfully!";
$message_type = 'success';
} else {
$message = "This book has already been added!";
$message_type = 'info';
}
}
// Redirect to avoid form resubmission and stay on the same page
$redirect_url = 'books.php';
$query_params = [];
if (!empty($_GET['search'])) {
$query_params['search'] = $_GET['search'];
}
if (!empty($_GET['page'])) {
$query_params['page'] = $_GET['page'];
}
if (!empty($query_params)) {
$redirect_url .= '?' . http_build_query($query_params);
}
header("Location: $redirect_url");
exit();
}
}
$limit = 9;
$page = max(1, (int)($_GET['page'] ?? 1));
$offset = ($page - 1) * $limit;
$search = trim($_GET['search'] ?? '');
$search_sql = "";
$params = [];
$types = "";
if (!empty($search)) {
$search_sql = " WHERE title LIKE ? OR author LIKE ?";
$search_term = "%{$search}%";
$params = [$search_term, $search_term];
$types = "ss";
}
// Get total book count
$stmt_total = $db->prepare("SELECT COUNT(*) as total FROM books $search_sql");
if ($stmt_total === false) {
error_log("Failed to prepare total count statement: " . $db->error);
}
if (!empty($params)) {
// bind_param requires references, so use call_user_func_array
$bind_params = [];
$bind_params[] = & $types;
for ($i = 0; $i < count($params); $i++) {
$bind_params[] = & $params[$i];
}
call_user_func_array([$stmt_total, 'bind_param'], $bind_params);
}
$stmt_total->execute();
$total_books = $stmt_total->get_result()->fetch_assoc()['total'] ?? 0;
$stmt_total->close();
$total_pages = ceil($total_books / $limit);
// Fetch books
$fetch_sql = "SELECT * FROM books $search_sql ORDER BY title ASC LIMIT ? OFFSET ?";
$stmt_books = $db->prepare($fetch_sql);
if ($stmt_books === false) {
error_log("Failed to prepare fetch books statement: " . $db->error);
}
if (!empty($params)) {
$types_fetch = $types . "ii";
$params_fetch = $params;
$params_fetch[] = $limit;
$params_fetch[] = $offset;
$bind_params_fetch = [];
$bind_params_fetch[] = & $types_fetch;
for ($i = 0; $i < count($params_fetch); $i++) {
$bind_params_fetch[] = & $params_fetch[$i];
}
call_user_func_array([$stmt_books, 'bind_param'], $bind_params_fetch);
} else {
$stmt_books->bind_param("ii", $limit, $offset);
}
$stmt_books->execute();
$books = $stmt_books->get_result();
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Booker Library</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" />
<style>
/* Styles omitted for brevity, keep existing styles */
</style>
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-primary shadow-sm">
<div class="container">
<a class="navbar-brand fw-bold fs-4" href="student_dashboard.php">Booker Library</a>
<form method="GET" action="books.php" class="d-flex ms-3" style="max-width: 320px;">
<input type="search" name="search" class="form-control form-control-sm rounded-pill" placeholder="Search by title or author" aria-label="Search" value="<?= htmlspecialchars($search) ?>" />
<button class="btn btn-light btn-sm ms-2 rounded-pill px-3" type="submit">Search</button>
</form>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ms-auto align-items-center">
<li class="nav-item"><a class="nav-link fw-semibold text-white" href="student_dashboard.php">Dashboard</a></li>
<li class="nav-item">
<button id="addSelectedToCartBtn" class="btn btn-outline-light btn-sm" disabled> Add Selected to Cart </button>
</li>
<li class="nav-item"><a class="nav-link fw-semibold text-white" href="my_cart.php">My Cart</a></li>
<li class="nav-item"><a class="nav-link fw-semibold text-white" href="history.php">History</a></li>
<li class="nav-item"><a class="nav-link fw-semibold text-white" href="student_logout.php">Logout</a></li>
</ul>
</div>
</div>
</nav>
<div class="container" style="padding-top: 80px;">
<?php if ($message): ?>
<div class="alert alert-<?= htmlspecialchars($message_type) ?> alert-dismissible fade show" role="alert">
<?= htmlspecialchars($message) ?>
<button type="button" class="btn-close" data-bs-dismiss="alert"></button>
</div>
<?php endif; ?>
<div class="row g-4">
<?php while ($book = $books->fetch_assoc()): ?>
<?php
// Check reservation status and date for the book (all students)
$stmt_check = $db->prepare("SELECT status, reservation_date, rejected_at FROM reservations WHERE book_id = ? ORDER BY reservation_date DESC");
$stmt_check->bind_param("i", $book['id']);
$stmt_check->execute();
$result_reservation = $stmt_check->get_result();
$reservations = [];
while ($row = $result_reservation->fetch_assoc()) {
$reservations[] = $row;
}
$stmt_check->close();
$is_booked = false;
$is_rejected = false;
$rejected_recently = false;
$is_issued = false;
if ($student_id !== null) {
// Check if book is currently issued to the current student and not returned
$stmt_check_issued = $db->prepare("SELECT id FROM issued_books WHERE book_id = ? AND student_id = ? AND return_date IS NULL LIMIT 1");
$stmt_check_issued->bind_param("ii", $book['id'], $student_id);
$stmt_check_issued->execute();
$result_issued = $stmt_check_issued->get_result();
$is_currently_issued = $result_issued->num_rows > 0;
$stmt_check_issued->close();
if ($is_currently_issued) {
$is_issued = true;
} else {
// Check if any reservation is booked or rejected within 24 hours
foreach ($reservations as $reservation) {
if ($reservation['status'] === 'Booked') {
$is_booked = true;
break;
} elseif ($reservation['status'] === 'Rejected') {
$is_rejected = true;
$rejection_time = strtotime($reservation['rejected_at'] ?? $reservation['reservation_date']);
$current_time = time();
if (($current_time - $rejection_time) < 24 * 3600) {
$rejected_recently = true;
} else {
// Rejection expired, reset status to allow booking
$stmt_reset = $db->prepare("UPDATE reservations SET status = 'Booked', rejected_at = NULL WHERE book_id = ? AND student_email = ?");
$stmt_reset->bind_param("is", $book['id'], $student_email);
$stmt_reset->execute();
$stmt_reset->close();
$is_rejected = false;
$rejected_recently = false;
}
}
}
}
} else {
// If student_id is null, fallback to previous logic without student_id check
foreach ($reservations as $reservation) {
if ($reservation['status'] === 'Booked') {
$is_booked = true;
break;
} elseif ($reservation['status'] === 'Rejected') {
$is_rejected = true;
$rejection_time = strtotime($reservation['rejected_at'] ?? $reservation['reservation_date']);
$current_time = time();
if (($current_time - $rejection_time) < 24 * 3600) {
$rejected_recently = true;
} else {
// Rejection expired, reset status to allow booking
$stmt_reset = $db->prepare("UPDATE reservations SET status = 'Booked', rejected_at = NULL WHERE book_id = ? AND student_email = ?");
$stmt_reset->bind_param("is", $book['id'], $student_email);
$stmt_reset->execute();
$stmt_reset->close();
$is_rejected = false;
$rejected_recently = false;
}
}
}
}
// Determine if booking button should be disabled due to max reservations reached
$disable_booking = false;
$disable_reason = '';
if ($current_bookings >= $max_reservations && !$is_booked && !$is_issued) {
$disable_booking = true;
$disable_reason = "You have reached the maximum number of active reservations allowed ($max_reservations).";
}
?>
<div class="col-md-4">
<div class="book-card">
<div class="book-card-body">
<div class="book-title">
<input type="checkbox" name="selected_books[]" value="<?= $book['id'] ?>" id="select_book_<?= $book['id'] ?>" style="margin-right: 8px;">
<label for="select_book_<?= $book['id'] ?>"><?= htmlspecialchars($book['title']) ?></label>
</div>
<div class="book-info"><strong>Author:</strong> <?= htmlspecialchars($book['author']) ?></div>
<div class="book-info"><strong>Edition:</strong> <?= htmlspecialchars($book['edition']) ?></div>
<div class="book-info"><strong>Available:</strong> <?= (int)$book['quantity'] ?> copies</div>
<form method="POST" action="books.php" class="d-inline-block" onsubmit="return confirmBooking(this);">
<input type="hidden" name="book_id" value="<?= $book['id'] ?>">
<?php if ($is_issued): ?>
<button type="button" class="btn btn-success" disabled>Borrowed</button>
<?php elseif ($is_booked): ?>
<button type="submit" name="action" value="unreserve" class="btn btn-primary">Unbook</button>
<?php elseif ($is_rejected && $rejected_recently): ?>
<button type="button" class="btn btn-warning" disabled>Rejected</button>
<?php else: ?>
<button type="submit" name="action" value="reserve" class="btn btn-primary" <?= $disable_booking ? 'disabled title="' . htmlspecialchars($disable_reason) . '"' : '' ?>>Book</button>
<?php endif; ?>
</form>
<?php if (!empty($search)): ?>
<a href="books.php" class="btn btn-primary ms-2">Leave</a>
<?php endif; ?>
</div>
</div>
</div>
<?php endwhile; ?>
</div>
<?php if ($total_pages > 1): ?>
<nav class="mt-4">
<ul class="pagination justify-content-center">
<li class="page-item <?= $page <= 1 ? 'disabled' : '' ?>">
<a class="page-link" href="books.php?search=<?= urlencode($search) ?>&page=<?= max(1, $page - 1) ?>">Previous</a>
</li>
<?php for ($i = 1; $i <= $total_pages; $i++): ?>
<li class="page-item <?= $page == $i ? 'active' : '' ?>">
<a class="page-link" href="books.php?search=<?= urlencode($search) ?>&page=<?= $i ?>"><?= $i ?></a>
</li>
<?php endfor; ?>
<li class="page-item <?= $page >= $total_pages ? 'disabled' : '' ?>">
<a class="page-link" href="books.php?search=<?= urlencode($search) ?>&page=<?= min($total_pages, $page + 1) ?>">Next</a>
</li>
</ul>
</nav>
<?php endif; ?>
</div>
<footer class="text-center py-3">
<p>© <?= date('Y') ?> Booker Library. All rights reserved.</p>
</footer>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
const addToCartBtn = document.getElementById('addSelectedToCartBtn');
const checkboxes = document.querySelectorAll('input[name="selected_books[]"]');
function updateButtonState() {
const anyChecked = Array.from(checkboxes).some(cb => cb.checked);
addToCartBtn.disabled = !anyChecked;
}
checkboxes.forEach(cb => {
cb.addEventListener('change', updateButtonState);
});
addToCartBtn.addEventListener('click', function () {
const selectedBookIds = Array.from(checkboxes)
.filter(cb => cb.checked)
.map(cb => cb.value);
if (selectedBookIds.length === 0) {
return;
}
// Use AJAX to add selected books to cart without page reload
fetch('update_cart_fixed.php', {
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
body: selectedBookIds.map(id => 'selected_books[]=' + encodeURIComponent(id)).join('&'),
credentials: 'same-origin'
})
.then(response => response.json())
.then(data => {
let addedCount = 0;
for (const key in data) {
if (data[key] === 'added') {
addedCount++;
}
}
if (addedCount > 0) {
alert(addedCount + ' book(s) added to cart successfully!');
// Uncheck all checkboxes and disable button
checkboxes.forEach(cb => cb.checked = false);
addToCartBtn.disabled = true;
// Optionally, update the My Cart component dynamically if present
if (window.updateMyCart) {
window.updateMyCart();
}
} else {
alert('book has already been added to cart!');
}
})
.catch(error => {
console.error('Error adding books to cart:', error);
alert('Failed to add books to cart. Please try again.');
});
});
});
// Function to update My Cart component dynamically if loaded in dashboard
window.updateMyCart = function() {
fetch('my_cart.php', { credentials: 'same-origin' })
.then(response => response.text())
.then(html => {
const myCartContainer = document.querySelector('#content-area .my-cart-container');
if (myCartContainer) {
myCartContainer.innerHTML = html;
}
})
.catch(error => {
console.error('Failed to update My Cart component:', error);
});
};
</script>
</body>
</html>