<?php
session_start();
include('includes/config.php');
date_default_timezone_set('Asia/Kolkata');
$updatetime = date('Y-m-d H:i:s');
if (strlen($_SESSION['alogin']) == 0) {
    header('location:index.php');
    exit;
}

if (!empty($_POST['qrcode'])) {
    $qrcode = trim($_POST['qrcode']);

    // Extract bookcopy if QR code contains a URL
    if (strpos($qrcode, 'bookcopy=') !== false) {
        parse_str(parse_url($qrcode, PHP_URL_QUERY), $params);
        $qrcode = $params['bookcopy'] ?? $qrcode;
    }

    // Check if book is issued
    $sql = "SELECT * FROM tblissuedbookdetails WHERE BookId=:bookcopy AND RetrunStatus=0 LIMIT 1";
    $query = $dbh->prepare($sql);
    $query->bindParam(':bookcopy', $qrcode, PDO::PARAM_STR);
    $query->execute();
    $result = $query->fetch(PDO::FETCH_ASSOC);

    if ($result) {
        // Mark as returned
        $update = "UPDATE tblissuedbookdetails 
                   SET RetrunStatus=1, ReturnDate=:updatetime 
                   WHERE id=:id";
        $stmt = $dbh->prepare($update);
        $stmt->bindParam(':id', $result['id'], PDO::PARAM_INT);
        $stmt->bindParam(':updatetime', $updatetime);

        $stmt->execute();

        echo "<script>
            alert('Book returned successfully!');
            window.location.href='return_book.php';
        </script>";
    } else {
        echo "<script>
            alert('Book is not issued or already returned!');
            window.location.href='return_book.php';
        </script>";
    }
} else {
    echo "<script>
        alert('QR code is missing!');
        window.location.href='return_book.php';
    </script>";
}
?>