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

if (!isset($_SESSION['userid']) || !isset($_POST['loanId'])) {
    echo json_encode(['success' => false, 'message' => 'Invalid request']);
    exit;
}

try {
    $conn->beginTransaction();

    // Get loan details to calculate fine
    $getLoan = "SELECT loan.*, book.title, Book_Copies.copyid 
                FROM loan 
                INNER JOIN Book_Copies ON loan.BookCopyID = Book_Copies.copyid 
                INNER JOIN book ON Book_Copies.bookid = book.bookid 
                WHERE loan.loanid = :loanid AND loan.memberid = :userid";
    $stmt = $conn->prepare($getLoan);
    $stmt->bindParam(':loanid', $_POST['loanId'], PDO::PARAM_INT);
    $stmt->bindParam(':userid', $_SESSION['userid'], PDO::PARAM_INT);
    $stmt->execute();
    $loanDetails = $stmt->fetch(PDO::FETCH_ASSOC);

    if (!$loanDetails) {
        throw new Exception('Loan not found');
    }

    // Calculate fine amount ($0.50 per day overdue)
    $dueDate = new DateTime($loanDetails['loandate']);
    $dueDate->modify('+14 days');
    $returnDate = new DateTime();
    $daysOverdue = $returnDate->diff($dueDate)->days;
    $fineAmount = $daysOverdue * 0.50;

    // Insert into fines table
    $insertFine = "INSERT INTO fine (FineAmount, FineDate, Status, LoanID) 
                VALUES (:amount, CURRENT_DATE, 'Unpaid', :loanid)";
    $stmt = $conn->prepare($insertFine);
    $stmt->bindParam(':amount', $fineAmount, PDO::PARAM_STR);
    $stmt->bindParam(':loanid', $_POST['loanId'], PDO::PARAM_INT);
    $stmt->execute();

    // 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');
    }

    // Update book copy status
    $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();

    $conn->commit();
    echo json_encode(['success' => true, 'fine' => $fineAmount]);

} catch (Exception $e) {
    $conn->rollBack();
    echo json_encode(['success' => false, 'message' => $e->getMessage()]);
    echo json_encode(['success' => false, 'message' => $e->getMessage(), 'trace' => $e->getTraceAsString()]);
    echo json_encode(['success' => true, 'fine' => (float)$fineAmount]);
}
?>