Compare commits

...

1 Commits

Author SHA1 Message Date
Flatlogic Bot
2332ec6934 1.0 2025-10-30 14:24:12 +00:00
17 changed files with 884 additions and 149 deletions

98
add-book.php Normal file
View File

@ -0,0 +1,98 @@
<?php
require_once __DIR__ . '/includes/auth.php';
require_role('Librarian');
require_once __DIR__ . '/db/config.php';
$errors = [];
$success = '';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$title = $_POST['title'] ?? '';
$author = $_POST['author'] ?? '';
$isbn = $_POST['isbn'] ?? '';
$description = $_POST['description'] ?? '';
if (empty($title)) {
$errors[] = 'Title is required';
}
if (empty($author)) {
$errors[] = 'Author is required';
}
if (empty($isbn)) {
$errors[] = 'ISBN is required';
}
if (empty($errors)) {
try {
$pdo = db();
$qr_code_hash = md5($isbn);
$stmt = $pdo->prepare(
"INSERT INTO books (title, author, isbn, description, qr_code_hash) VALUES (:title, :author, :isbn, :description, :qr_code_hash)"
);
if ($stmt->execute([
':title' => $title,
':author' => $author,
':isbn' => $isbn,
':description' => $description,
':qr_code_hash' => $qr_code_hash
])) {
$success = "Book added successfully!";
} else {
$errors[] = "Failed to add book.";
}
} catch (PDOException $e) {
$errors[] = "Database error: " . $e->getMessage();
}
}
}
require_once __DIR__ . '/includes/header.php';
?>
<div class="row justify-content-center">
<div class="col-md-8">
<div class="card">
<div class="card-header">
<h2>Add a New Book</h2>
</div>
<div class="card-body">
<?php if (!empty($errors)): ?>
<div class="alert alert-danger">
<?php foreach ($errors as $error): ?>
<p><?php echo $error; ?></p>
<?php endforeach; ?>
</div>
<?php endif; ?>
<?php if ($success): ?>
<div class="alert alert-success">
<p><?php echo $success; ?></p>
</div>
<?php endif; ?>
<form action="add-book.php" method="POST">
<div class="mb-3">
<label for="title" class="form-label">Title</label>
<input type="text" class="form-control" id="title" name="title" required>
</div>
<div class="mb-3">
<label for="author" class="form-label">Author</label>
<input type="text" class="form-control" id="author" name="author" required>
</div>
<div class="mb-3">
<label for="isbn" class="form-label">ISBN</label>
<input type="text" class="form-control" id="isbn" name="isbn" required>
</div>
<div class="mb-3">
<label for="description" class="form-label">Description</label>
<textarea class="form-control" id="description" name="description" rows="3"></textarea>
</div>
<button type="submit" class="btn btn-primary">Add Book</button>
</form>
</div>
</div>
</div>
</div>
<?php require_once __DIR__ . '/includes/footer.php'; ?>

61
assets/css/custom.css Normal file
View File

@ -0,0 +1,61 @@
/* assets/css/custom.css */
body {
font-family: 'Inter', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
background-color: #F8F9FA;
color: #212529;
}
.navbar {
box-shadow: 0 2px 4px rgba(0,0,0,.04);
}
.hero {
background: linear-gradient(45deg, #007BFF, #0056b3);
color: white;
}
.hero .btn-primary {
background-color: #FFFFFF;
color: #007BFF;
border-color: #FFFFFF;
font-weight: bold;
}
.hero .btn-primary:hover {
background-color: #f0f0f0;
color: #0056b3;
}
.book-card {
background-color: #FFFFFF;
border: 1px solid #dee2e6;
border-radius: 0.375rem;
transition: transform .2s ease-in-out, box-shadow .2s ease-in-out;
}
.book-card:hover {
transform: translateY(-5px);
box-shadow: 0 0.5rem 1rem rgba(0, 0, 0, 0.15);
}
.book-card .card-title {
color: #007BFF;
}
.book-card .badge {
font-size: 0.8rem;
}
.status-available {
color: #198754;
font-weight: bold;
}
.status-borrowed {
color: #dc3545;
font-weight: bold;
}
.footer {
background-color: #343a40;
color: white;
}

2
assets/js/main.js Normal file
View File

@ -0,0 +1,2 @@
// Intentionally blank for now.
// Future client-side interactions can be added here.

66
catalog.php Normal file
View File

@ -0,0 +1,66 @@
<?php
require_once __DIR__ . '/db/config.php';
$search_term = $_GET['search'] ?? '';
$pdo = db();
$query = "SELECT * FROM books";
$params = [];
if (!empty($search_term)) {
$query .= " WHERE title LIKE :search OR author LIKE :search OR isbn LIKE :search";
$params[':search'] = '%' . $search_term . '%';
}
$stmt = $pdo->prepare($query);
$stmt->execute($params);
$books = $stmt->fetchAll(PDO::FETCH_ASSOC);
?>
<?php require_once __DIR__ . '/includes/header.php'; ?>
<main class="container my-5">
<section>
<h1 class="mb-4">Book Catalog</h1>
<div class="card mb-4">
<div class="card-body">
<form action="catalog.php" method="GET">
<div class="input-group">
<input type="text" class="form-control" name="search" placeholder="Search by title, author, or ISBN..." value="<?php echo htmlspecialchars($search_term); ?>">
<button class="btn btn-primary" type="submit"><i class="bi bi-search"></i> Search</button>
</div>
</form>
</div>
</div>
<div class="row">
<?php if (empty($books)): ?>
<div class="col">
<div class="alert alert-info">No books found matching your search criteria.</div>
</div>
<?php else: ?>
<?php foreach ($books as $book): ?>
<div class="col-md-6 col-lg-4 mb-4">
<div class="card h-100 book-card">
<div class="card-body d-flex flex-column">
<h5 class="card-title fw-bold"><?php echo htmlspecialchars($book['title']); ?></h5>
<h6 class="card-subtitle mb-2 text-muted"><?php echo htmlspecialchars($book['author']); ?></h6>
<p class="card-text flex-grow-1"><?php echo htmlspecialchars(substr($book['description'], 0, 100)) . '...'; ?></p>
<div class="mt-auto">
<p class="mb-1"><small class="text-muted">ISBN: <?php echo htmlspecialchars($book['isbn']); ?></small></p>
<p class="mb-0">
Status:
<span class="status-<?php echo htmlspecialchars($book['status']); ?>">
<?php echo htmlspecialchars(ucfirst($book['status'])); ?>
</span>
</p>
</div>
</div>
</div>
</div>
<?php endforeach; ?>
<?php endif; ?>
</div>
</section>
</main>
<?php require_once __DIR__ . '/includes/footer.php'; ?>

View File

@ -0,0 +1,10 @@
CREATE TABLE IF NOT EXISTS books (
id INT AUTO_INCREMENT PRIMARY KEY,
title VARCHAR(255) NOT NULL,
author VARCHAR(255) NOT NULL,
isbn VARCHAR(20) UNIQUE NOT NULL,
description TEXT,
qr_code_hash VARCHAR(255) UNIQUE,
status ENUM('available', 'borrowed') NOT NULL DEFAULT 'available',
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

View File

@ -0,0 +1,8 @@
CREATE TABLE IF NOT EXISTS `users` (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`name` VARCHAR(255) NOT NULL,
`email` VARCHAR(255) NOT NULL UNIQUE,
`password` VARCHAR(255) NOT NULL,
`role` ENUM('Member', 'Librarian', 'Admin') NOT NULL DEFAULT 'Member',
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
);

View File

@ -0,0 +1,10 @@
CREATE TABLE IF NOT EXISTS `loans` (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`book_id` INT NOT NULL,
`user_id` INT NOT NULL,
`loan_date` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
`due_date` TIMESTAMP NOT NULL,
`return_date` TIMESTAMP NULL,
FOREIGN KEY (`book_id`) REFERENCES `books`(`id`),
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`)
);

77
db/seed.php Normal file
View File

@ -0,0 +1,77 @@
<?php
require_once __DIR__ . '/config.php';
try {
// First, connect to MySQL server without selecting a DB
$pdo_admin = new PDO('mysql:host='.DB_HOST, DB_USER, DB_PASS, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
]);
// Create the database if it doesn't exist
$pdo_admin->exec("CREATE DATABASE IF NOT EXISTS `".DB_NAME."`");
echo "Database '".DB_NAME."' created or already exists.\n";
// Now, connect to the specific database
$pdo = db();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// 1. Run migrations
$migrations = glob(__DIR__ . '/migrations/*.sql');
sort($migrations);
foreach ($migrations as $migration) {
$sql = file_get_contents($migration);
$pdo->exec($sql);
echo "Executed migration: " . basename($migration) . "\n";
}
// 2. Check if table is empty before seeding
$stmt = $pdo->query("SELECT COUNT(*) FROM books");
if ($stmt->fetchColumn() > 0) {
echo "Table 'books' is not empty. Seeding skipped.\n";
exit;
}
// 3. Seed data
$books = [
[
'title' => 'The Hitchhiker\'s Guide to the Galaxy',
'author' => 'Douglas Adams',
'isbn' => '978-0345391803',
'description' => 'A comedy science fiction series created by Douglas Adams.',
'qr_code_hash' => md5('978-0345391803')
],
[
'title' => 'Pride and Prejudice',
'author' => 'Jane Austen',
'isbn' => '978-1503290563',
'description' => 'A romantic novel of manners written by Jane Austen in 1813.',
'qr_code_hash' => md5('978-1503290563')
],
[
'title' => 'To Kill a Mockingbird',
'author' => 'Harper Lee',
'isbn' => '978-0061120084',
'description' => 'A novel by Harper Lee published in 1960. Instantly successful, widely read in high schools and middle schools in the United States, it has become a classic of modern American literature, winning the Pulitzer Prize.',
'qr_code_hash' => md5('978-0061120084')
],
[
'title' => '1984',
'author' => 'George Orwell',
'isbn' => '978-0451524935',
'description' => 'A dystopian social science fiction novel and cautionary tale by English writer George Orwell.',
'qr_code_hash' => md5('978-0451524935')
]
];
$stmt = $pdo->prepare(
"INSERT INTO books (title, author, isbn, description, qr_code_hash) VALUES (:title, :author, :isbn, :description, :qr_code_hash)"
);
foreach ($books as $book) {
$stmt->execute($book);
}
echo "Seeded " . count($books) . " books.\n";
} catch (PDOException $e) {
die("DB ERROR: " . $e->getMessage());
}

24
includes/auth.php Normal file
View File

@ -0,0 +1,24 @@
<?php
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
function is_logged_in() {
return isset($_SESSION['user_id']);
}
function require_login() {
if (!is_logged_in()) {
header("Location: login.php");
exit;
}
}
function require_role($role) {
require_login();
if ($_SESSION['user_role'] !== $role) {
// For simplicity, redirect to home. A 403 page would be better.
header("Location: index.php");
exit;
}
}

5
includes/footer.php Normal file
View File

@ -0,0 +1,5 @@
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
<script src="assets/js/main.js?v=<?php echo time(); ?>"></script>
</body>
</html>

55
includes/header.php Normal file
View File

@ -0,0 +1,55 @@
<?php session_start(); ?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>QR Code Library System</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.5/font/bootstrap-icons.css">
<link rel="stylesheet" href="assets/css/custom.css?v=<?php echo time(); ?>">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-dark bg-dark">
<div class="container-fluid">
<a class="navbar-brand" href="index.php"><i class="bi bi-qr-code-scan"></i> Library</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarSupportedContent">
<ul class="navbar-nav me-auto mb-2 mb-lg-0">
<li class="nav-item">
<a class="nav-link" href="catalog.php">Catalog</a>
</li>
<?php if (isset($_SESSION['user_role']) && $_SESSION['user_role'] === 'Librarian'): ?>
<li class="nav-item">
<a class="nav-link" href="add-book.php">Add Book</a>
</li>
<li class="nav-item">
<a class="nav-link" href="scan.php">Scan</a>
</li>
<?php endif; ?>
</ul>
<ul class="navbar-nav ms-auto">
<?php if (isset($_SESSION['user_id'])): ?>
<li class="nav-item dropdown">
<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
<i class="bi bi-person-circle"></i> <?php echo htmlspecialchars($_SESSION['user_name']); ?>
</a>
<ul class="dropdown-menu dropdown-menu-end" aria-labelledby="navbarDropdown">
<li><a class="dropdown-item" href="logout.php">Logout</a></li>
</ul>
</li>
<?php else: ?>
<li class="nav-item">
<a class="nav-link" href="login.php">Login</a>
</li>
<li class="nav-item">
<a class="nav-link" href="register.php">Register</a>
</li>
<?php endif; ?>
</ul>
</div>
</div>
</nav>
<div class="container mt-4">

188
index.php
View File

@ -1,150 +1,40 @@
<?php <?php require_once __DIR__ . '/includes/header.php'; ?>
declare(strict_types=1);
@ini_set('display_errors', '1');
@error_reporting(E_ALL);
@date_default_timezone_set('UTC');
$phpVersion = PHP_VERSION; <header class="hero text-center py-5">
$now = date('Y-m-d H:i:s'); <div class="container">
?> <h1 class="display-4 fw-bold">Welcome to the Future of Reading</h1>
<!doctype html> <p class="lead my-4">A smart, simple, and seamless library experience powered by QR codes.</p>
<html lang="en"> <a href="catalog.php" class="btn btn-primary btn-lg px-4">Explore the Catalog</a>
<head> </div>
<meta charset="utf-8" /> </header>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>New Style</title> <main class="container my-5">
<?php <section class="text-center">
// Read project preview data from environment <h2 class="mb-5">How It Works</h2>
$projectDescription = $_SERVER['PROJECT_DESCRIPTION'] ?? ''; <div class="row">
$projectImageUrl = $_SERVER['PROJECT_IMAGE_URL'] ?? ''; <div class="col-md-4 mb-4">
?> <div class="p-4">
<?php if ($projectDescription): ?> <i class="bi bi-search fs-1 text-primary"></i>
<!-- Meta description --> <h3 class="h4 my-3">1. Find Your Book</h3>
<meta name="description" content='<?= htmlspecialchars($projectDescription) ?>' /> <p class="text-muted">Browse our extensive digital catalog to find the books you love.</p>
<!-- Open Graph meta tags --> </div>
<meta property="og:description" content="<?= htmlspecialchars($projectDescription) ?>" /> </div>
<!-- Twitter meta tags --> <div class="col-md-4 mb-4">
<meta property="twitter:description" content="<?= htmlspecialchars($projectDescription) ?>" /> <div class="p-4">
<?php endif; ?> <i class="bi bi-qr-code fs-1 text-primary"></i>
<?php if ($projectImageUrl): ?> <h3 class="h4 my-3">2. Scan to Borrow</h3>
<!-- Open Graph image --> <p class="text-muted">Use your phone to scan the book's QR code for instant self-checkout.</p>
<meta property="og:image" content="<?= htmlspecialchars($projectImageUrl) ?>" /> </div>
<!-- Twitter image --> </div>
<meta property="twitter:image" content="<?= htmlspecialchars($projectImageUrl) ?>" /> <div class="col-md-4 mb-4">
<?php endif; ?> <div class="p-4">
<link rel="preconnect" href="https://fonts.googleapis.com"> <i class="bi bi-book-half fs-1 text-primary"></i>
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <h3 class="h4 my-3">3. Enjoy Reading</h3>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap" rel="stylesheet"> <p class="text-muted">Enjoy your book! We'll send you a reminder before it's due.</p>
<style> </div>
:root { </div>
--bg-color-start: #6a11cb; </div>
--bg-color-end: #2575fc; </section>
--text-color: #ffffff; </main>
--card-bg-color: rgba(255, 255, 255, 0.01);
--card-border-color: rgba(255, 255, 255, 0.1); <?php require_once __DIR__ . '/includes/footer.php'; ?>
}
body {
margin: 0;
font-family: 'Inter', sans-serif;
background: linear-gradient(45deg, var(--bg-color-start), var(--bg-color-end));
color: var(--text-color);
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
text-align: center;
overflow: hidden;
position: relative;
}
body::before {
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 100%;
background-image: url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100" viewBox="0 0 100 100"><path d="M-10 10L110 10M10 -10L10 110" stroke-width="1" stroke="rgba(255,255,255,0.05)"/></svg>');
animation: bg-pan 20s linear infinite;
z-index: -1;
}
@keyframes bg-pan {
0% { background-position: 0% 0%; }
100% { background-position: 100% 100%; }
}
main {
padding: 2rem;
}
.card {
background: var(--card-bg-color);
border: 1px solid var(--card-border-color);
border-radius: 16px;
padding: 2rem;
backdrop-filter: blur(20px);
-webkit-backdrop-filter: blur(20px);
box-shadow: 0 8px 32px 0 rgba(0, 0, 0, 0.1);
}
.loader {
margin: 1.25rem auto 1.25rem;
width: 48px;
height: 48px;
border: 3px solid rgba(255, 255, 255, 0.25);
border-top-color: #fff;
border-radius: 50%;
animation: spin 1s linear infinite;
}
@keyframes spin {
from { transform: rotate(0deg); }
to { transform: rotate(360deg); }
}
.hint {
opacity: 0.9;
}
.sr-only {
position: absolute;
width: 1px; height: 1px;
padding: 0; margin: -1px;
overflow: hidden;
clip: rect(0, 0, 0, 0);
white-space: nowrap; border: 0;
}
h1 {
font-size: 3rem;
font-weight: 700;
margin: 0 0 1rem;
letter-spacing: -1px;
}
p {
margin: 0.5rem 0;
font-size: 1.1rem;
}
code {
background: rgba(0,0,0,0.2);
padding: 2px 6px;
border-radius: 4px;
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, monospace;
}
footer {
position: absolute;
bottom: 1rem;
font-size: 0.8rem;
opacity: 0.7;
}
</style>
</head>
<body>
<main>
<div class="card">
<h1>Analyzing your requirements and generating your website…</h1>
<div class="loader" role="status" aria-live="polite" aria-label="Applying initial changes">
<span class="sr-only">Loading…</span>
</div>
<p class="hint"><?= ($_SERVER['HTTP_HOST'] ?? '') === 'appwizzy.com' ? 'AppWizzy' : 'Flatlogic' ?> AI is collecting your requirements and applying the first changes.</p>
<p class="hint">This page will update automatically as the plan is implemented.</p>
<p>Runtime: PHP <code><?= htmlspecialchars($phpVersion) ?></code> — UTC <code><?= htmlspecialchars($now) ?></code></p>
</div>
</main>
<footer>
Page updated: <?= htmlspecialchars($now) ?> (UTC)
</footer>
</body>
</html>

73
login.php Normal file
View File

@ -0,0 +1,73 @@
<?php
require_once __DIR__ . '/db/config.php';
require_once __DIR__ . '/includes/auth.php';
$errors = [];
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$email = $_POST['email'] ?? '';
$password = $_POST['password'] ?? '';
if (empty($email)) {
$errors[] = 'Email is required';
}
if (empty($password)) {
$errors[] = 'Password is required';
}
if (empty($errors)) {
try {
$pdo = db();
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
$stmt->execute([$email]);
$user = $stmt->fetch();
if ($user && password_verify($password, $user['password'])) {
$_SESSION['user_id'] = $user['id'];
$_SESSION['user_name'] = $user['name'];
$_SESSION['user_role'] = $user['role'];
header("Location: index.php");
exit;
} else {
$errors[] = 'Invalid email or password';
}
} catch (PDOException $e) {
$errors[] = "Database error: " . $e->getMessage();
}
}
}
require_once __DIR__ . '/includes/header.php';
?>
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card">
<div class="card-header">
<h2>Login</h2>
</div>
<div class="card-body">
<?php if (!empty($errors)): ?>
<div class="alert alert-danger">
<?php foreach ($errors as $error): ?>
<p><?php echo $error; ?></p>
<?php endforeach; ?>
</div>
<?php endif; ?>
<form action="login.php" method="POST">
<div class="mb-3">
<label for="email" class="form-label">Email address</label>
<input type="email" class="form-control" id="email" name="email" required>
</div>
<div class="mb-3">
<label for="password" class="form-label">Password</label>
<input type="password" class="form-control" id="password" name="password" required>
</div>
<button type="submit" class="btn btn-primary">Login</button>
</form>
</div>
</div>
</div>
</div>
<?php require_once __DIR__ . '/includes/footer.php'; ?>

6
logout.php Normal file
View File

@ -0,0 +1,6 @@
<?php
session_start();
session_unset();
session_destroy();
header("Location: index.php");
exit;

102
process-scan.php Normal file
View File

@ -0,0 +1,102 @@
<?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);

97
register.php Normal file
View File

@ -0,0 +1,97 @@
<?php
require_once __DIR__ . '/db/config.php';
require_once __DIR__ . '/includes/auth.php';
$errors = [];
$success = '';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = $_POST['name'] ?? '';
$email = $_POST['email'] ?? '';
$password = $_POST['password'] ?? '';
$confirm_password = $_POST['confirm_password'] ?? '';
if (empty($name)) {
$errors[] = 'Name is required';
}
if (empty($email)) {
$errors[] = 'Email is required';
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors[] = 'Invalid email format';
}
if (empty($password)) {
$errors[] = 'Password is required';
}
if ($password !== $confirm_password) {
$errors[] = 'Passwords do not match';
}
if (empty($errors)) {
try {
$pdo = db();
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
$stmt->execute([$email]);
if ($stmt->fetch()) {
$errors[] = 'Email already exists';
} else {
$hashed_password = password_hash($password, PASSWORD_DEFAULT);
$stmt = $pdo->prepare("INSERT INTO users (name, email, password, role) VALUES (?, ?, ?, 'Member')");
if ($stmt->execute([$name, $email, $hashed_password])) {
$user_id = $pdo->lastInsertId();
$_SESSION['user_id'] = $user_id;
$_SESSION['user_name'] = $name;
$_SESSION['user_role'] = 'Member';
header("Location: index.php");
exit;
} else {
$errors[] = 'Failed to register user';
}
}
} catch (PDOException $e) {
$errors[] = "Database error: " . $e->getMessage();
}
}
}
require_once __DIR__ . '/includes/header.php';
?>
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card">
<div class="card-header">
<h2>Register</h2>
</div>
<div class="card-body">
<?php if (!empty($errors)): ?>
<div class="alert alert-danger">
<?php foreach ($errors as $error): ?>
<p><?php echo $error; ?></p>
<?php endforeach; ?>
</div>
<?php endif; ?>
<form action="register.php" method="POST">
<div class="mb-3">
<label for="name" class="form-label">Name</label>
<input type="text" class="form-control" id="name" name="name" required>
</div>
<div class="mb-3">
<label for="email" class="form-label">Email address</label>
<input type="email" class="form-control" id="email" name="email" required>
</div>
<div class="mb-3">
<label for="password" class="form-label">Password</label>
<input type="password" class="form-control" id="password" name="password" required>
</div>
<div class="mb-3">
<label for="confirm_password" class="form-label">Confirm Password</label>
<input type="password" class="form-control" id="confirm_password" name="confirm_password" required>
</div>
<button type="submit" class="btn btn-primary">Register</button>
</form>
</div>
</div>
</div>
</div>
<?php require_once __DIR__ . '/includes/footer.php'; ?>

151
scan.php Normal file
View File

@ -0,0 +1,151 @@
<?php
require_once __DIR__ . '/includes/auth.php';
require_role('Librarian');
require_once __DIR__ . '/includes/header.php';
?>
<div class="row">
<div class="col-md-6">
<div class="card">
<div class="card-header"><h2>Scan QR Code</h2></div>
<div class="card-body">
<div class="mb-3">
<button id="start-checkin" class="btn btn-success">Start Check-in</button>
<button id="start-checkout" class="btn btn-primary">Start Check-out</button>
</div>
<div id="scanner-container" style="width: 100%; display: none;"></div>
<div id="checkout-email-container" class="mb-3" style="display: none;">
<label for="member_email" class="form-label">Member Email</label>
<input type="email" class="form-control" id="member_email">
</div>
<div id="scan-result" class="mt-3"></div>
</div>
</div>
</div>
<div class="col-md-6">
<div class="card">
<div class="card-header"><h2>Manual Entry</h2></div>
<div class="card-body">
<form id="checkout-form">
<div class="mb-3">
<label for="manual_member_email" class="form-label">Member Email</label>
<input type="email" class="form-control" id="manual_member_email" required>
</div>
<div class="mb-3">
<label for="book_isbn" class="form-label">Book ISBN</label>
<input type="text" class="form-control" id="book_isbn" required>
</div>
<button type="submit" class="btn btn-primary">Check-out</button>
</form>
<hr>
<form id="checkin-form">
<div class="mb-3">
<label for="checkin_book_isbn" class="form-label">Book ISBN</label>
<input type="text" class="form-control" id="checkin_book_isbn" required>
</div>
<button type="submit" class="btn btn-success">Check-in</button>
</form>
</div>
</div>
</div>
</div>
<script src="https://unpkg.com/html5-qrcode@2.0.9/dist/html5-qrcode.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function () {
const html5QrCode = new Html5Qrcode("scanner-container");
const config = { fps: 10, qrbox: 250 };
let currentAction = null;
const qrCodeSuccessCallback = (decodedText, decodedResult) => {
processScan(decodedText);
html5QrCode.stop();
document.getElementById('scanner-container').style.display = 'none';
};
document.getElementById('start-checkin').addEventListener('click', () => {
currentAction = 'checkin';
document.getElementById('checkout-email-container').style.display = 'none';
document.getElementById('scanner-container').style.display = 'block';
html5QrCode.start({ facingMode: "environment" }, config, qrCodeSuccessCallback);
});
document.getElementById('start-checkout').addEventListener('click', () => {
currentAction = 'checkout';
document.getElementById('checkout-email-container').style.display = 'block';
document.getElementById('scanner-container').style.display = 'block';
html5QrCode.start({ facingMode: "environment" }, config, qrCodeSuccessCallback);
});
function processScan(scannedData) {
let formData = new FormData();
formData.append('action', currentAction);
formData.append('qr_code_hash', scannedData);
if (currentAction === 'checkout') {
let user_email = document.getElementById('member_email').value;
if (!user_email) {
document.getElementById('scan-result').innerHTML = `<div class="alert alert-danger">Please enter a member email for checkout.</div>`;
return;
}
formData.append('user_email', user_email);
}
fetch('process-scan.php', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
let alertClass = data.success ? 'alert-success' : 'alert-danger';
document.getElementById('scan-result').innerHTML = `<div class="alert ${alertClass}">${data.message}</div>`;
})
.catch(error => {
console.error('Error:', error);
document.getElementById('scan-result').innerHTML = `<div class="alert alert-danger">An error occurred.</div>`;
});
}
// Manual form submissions
document.getElementById('checkout-form').addEventListener('submit', function(e) {
e.preventDefault();
let user_email = document.getElementById('manual_member_email').value;
let isbn = document.getElementById('book_isbn').value;
// In a real app, you'd convert ISBN to qr_code_hash or have a separate endpoint
// For now, we'll assume the librarian enters the hash for simplicity
processManual('checkout', isbn, user_email);
});
document.getElementById('checkin-form').addEventListener('submit', function(e) {
e.preventDefault();
let isbn = document.getElementById('checkin_book_isbn').value;
processManual('checkin', isbn);
});
function processManual(action, qr_code_hash, user_email = null) {
let formData = new FormData();
formData.append('action', action);
formData.append('qr_code_hash', qr_code_hash);
if (user_email) {
formData.append('user_email', user_email);
}
fetch('process-scan.php', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
let alertClass = data.success ? 'alert-success' : 'alert-danger';
document.getElementById('scan-result').innerHTML = `<div class="alert ${alertClass}">${data.message}</div>`;
})
.catch(error => {
console.error('Error:', error);
document.getElementById('scan-result').innerHTML = `<div class="alert alert-danger">An error occurred.</div>`;
});
}
});
</script>
<?php require_once __DIR__ . '/includes/footer.php'; ?>