<?php
session_start();
require './connect.php';

if (!isset($_SESSION['userid'])) {
    echo json_encode(['success' => false, 'message' => 'User not logged in']);
    exit;
}

// Check if loan ID was provided
if (!isset($_POST['loanId'])) {
    echo json_encode(['success' => false, 'message' => 'No loan ID provided']);
    exit;
}

try {
    // Begin transaction
    $conn->beginTransaction();

    // Update loan status to 'Returned'
    $updateLoan = "UPDATE loan SET status = 'Returned', returndate = CURRENT_DATE WHERE loanid = :loanid AND memberid = :userid";
    $stmt = $conn->prepare($updateLoan);
    $stmt->bindParam(':loanid', $_POST['loanId'], PDO::PARAM_INT);
    $stmt->bindParam(':userid', $_SESSION['userid'], PDO::PARAM_INT);
    $stmt->execute();

    // Check if the loan was actually updated
    if ($stmt->rowCount() === 0) {
        throw new Exception('Loan not found or not authorized');
    }

    // Get the book copy ID
    $getCopyId = "SELECT Book_Copies.copyid
                    FROM Book_Copies
                    INNER JOIN loan ON Book_Copies.copyid = loan.BookCopyID
                    WHERE loan.LoanID = :loanid";
    $stmt = $conn->prepare($getCopyId);
    $stmt->bindParam(':loanid', $_POST['loanId'], PDO::PARAM_INT);
    $stmt->execute();
    $copyId = $stmt->fetchColumn();

    // Update book copy status to available
    if ($copyId) {
        $updateCopy = "UPDATE loan 
               SET BookCopyID = NULL, status = 'Available' 
               WHERE loanid = :loanid AND BookCopyID = :copyid";
        $stmt = $conn->prepare($updateCopy);
        $stmt->bindParam(':loanid', $loanId, PDO::PARAM_INT);
        $stmt->bindParam(':copyid', $copyId, PDO::PARAM_INT);
        $stmt->execute();
    }

    // Commit transaction
    $conn->commit();

    echo json_encode(['success' => true]);
} catch (Exception $e) {
    // Rollback transaction on error
    $conn->rollBack();
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
}
?>