1 | <?php
|
---|
2 | session_start();
|
---|
3 | require './connect.php';
|
---|
4 |
|
---|
5 | if (!isset($_SESSION['userid'])) {
|
---|
6 | echo json_encode(['success' => false, 'message' => 'User not logged in']);
|
---|
7 | exit;
|
---|
8 | }
|
---|
9 |
|
---|
10 | // Check if loan ID was provided
|
---|
11 | if (!isset($_POST['loanId'])) {
|
---|
12 | echo json_encode(['success' => false, 'message' => 'No loan ID provided']);
|
---|
13 | exit;
|
---|
14 | }
|
---|
15 |
|
---|
16 | try {
|
---|
17 | // Begin transaction
|
---|
18 | $conn->beginTransaction();
|
---|
19 |
|
---|
20 | // Update loan status to 'Returned'
|
---|
21 | $updateLoan = "UPDATE loan SET status = 'Returned', returndate = CURRENT_DATE WHERE loanid = :loanid AND memberid = :userid";
|
---|
22 | $stmt = $conn->prepare($updateLoan);
|
---|
23 | $stmt->bindParam(':loanid', $_POST['loanId'], PDO::PARAM_INT);
|
---|
24 | $stmt->bindParam(':userid', $_SESSION['userid'], PDO::PARAM_INT);
|
---|
25 | $stmt->execute();
|
---|
26 |
|
---|
27 | // Check if the loan was actually updated
|
---|
28 | if ($stmt->rowCount() === 0) {
|
---|
29 | throw new Exception('Loan not found or not authorized');
|
---|
30 | }
|
---|
31 |
|
---|
32 | // Get the book copy ID
|
---|
33 | $getCopyId = "SELECT Book_Copies.copyid
|
---|
34 | FROM Book_Copies
|
---|
35 | INNER JOIN loan ON Book_Copies.copyid = loan.BookCopyID
|
---|
36 | WHERE loan.LoanID = :loanid";
|
---|
37 | $stmt = $conn->prepare($getCopyId);
|
---|
38 | $stmt->bindParam(':loanid', $_POST['loanId'], PDO::PARAM_INT);
|
---|
39 | $stmt->execute();
|
---|
40 | $copyId = $stmt->fetchColumn();
|
---|
41 |
|
---|
42 | // Update book copy status to available
|
---|
43 | if ($copyId) {
|
---|
44 | $updateCopy = "UPDATE loan
|
---|
45 | SET BookCopyID = NULL, status = 'Available'
|
---|
46 | WHERE loanid = :loanid AND BookCopyID = :copyid";
|
---|
47 | $stmt = $conn->prepare($updateCopy);
|
---|
48 | $stmt->bindParam(':loanid', $loanId, PDO::PARAM_INT);
|
---|
49 | $stmt->bindParam(':copyid', $copyId, PDO::PARAM_INT);
|
---|
50 | $stmt->execute();
|
---|
51 | }
|
---|
52 |
|
---|
53 | // Commit transaction
|
---|
54 | $conn->commit();
|
---|
55 |
|
---|
56 | echo json_encode(['success' => true]);
|
---|
57 | } catch (Exception $e) {
|
---|
58 | // Rollback transaction on error
|
---|
59 | $conn->rollBack();
|
---|
60 | echo json_encode(['success' => false, 'message' => $e->getMessage()]);
|
---|
61 | }
|
---|
62 | ?> |
---|