35354-vm/process-scan.php
Flatlogic Bot 2332ec6934 1.0
2025-10-30 14:24:12 +00:00

103 lines
3.3 KiB
PHP

<?php
require_once __DIR__ . '/includes/auth.php';
require_role('Librarian');
require_once __DIR__ . '/db/config.php';
header('Content-Type: application/json');
$response = ['success' => false, 'message' => 'Invalid request'];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$action = $_POST['action'] ?? '';
$qr_code_hash = $_POST['qr_code_hash'] ?? '';
if (empty($action) || empty($qr_code_hash)) {
$response['message'] = 'Missing action or QR code';
echo json_encode($response);
exit;
}
try {
$pdo = db();
// Find the book by QR code hash
$stmt = $pdo->prepare("SELECT id FROM books WHERE qr_code_hash = ?");
$stmt->execute([$qr_code_hash]);
$book = $stmt->fetch();
if (!$book) {
$response['message'] = 'Book not found';
echo json_encode($response);
exit;
}
$book_id = $book['id'];
if ($action === 'checkout') {
$user_email = $_POST['user_email'] ?? '';
if (empty($user_email)) {
$response['message'] = 'Missing user email for checkout';
echo json_encode($response);
exit;
}
// Find the user by email
$stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
$stmt->execute([$user_email]);
$user = $stmt->fetch();
if (!$user) {
$response['message'] = 'User not found';
echo json_encode($response);
exit;
}
$user_id = $user['id'];
// Check if the book is already on loan
$stmt = $pdo->prepare("SELECT id FROM loans WHERE book_id = ? AND return_date IS NULL");
$stmt->execute([$book_id]);
if ($stmt->fetch()) {
$response['message'] = 'Book is already on loan';
echo json_encode($response);
exit;
}
$loan_date = date('Y-m-d H:i:s');
$due_date = date('Y-m-d H:i:s', strtotime('+2 weeks'));
$stmt = $pdo->prepare("INSERT INTO loans (book_id, user_id, due_date) VALUES (?, ?, ?)");
if ($stmt->execute([$book_id, $user_id, $due_date])) {
$response['success'] = true;
$response['message'] = 'Book checked out successfully';
} else {
$response['message'] = 'Failed to check out book';
}
} elseif ($action === 'checkin') {
$stmt = $pdo->prepare("UPDATE loans SET return_date = CURRENT_TIMESTAMP WHERE book_id = ? AND return_date IS NULL");
if ($stmt->execute([$book_id])) {
if ($stmt->rowCount() > 0) {
$response['success'] = true;
$response['message'] = 'Book checked in successfully';
} else {
$response['message'] = 'Book was not on loan';
}
} else {
$response['message'] = 'Failed to check in book';
}
} else {
$response['message'] = 'Invalid action';
}
} catch (PDOException $e) {
$response['message'] = 'Database error: ' . $e->getMessage();
}
echo json_encode($response);
exit;
}
echo json_encode($response);