Compare commits

...

4 Commits

Author SHA1 Message Date
Flatlogic Bot
ac9362bcab 4 2025-12-15 09:49:58 +00:00
Flatlogic Bot
fdcc78312c 3 2025-12-15 09:46:36 +00:00
Flatlogic Bot
08c2df845a 2 2025-12-15 09:44:41 +00:00
Flatlogic Bot
7100e72a1d 1 2025-12-15 09:37:52 +00:00
15 changed files with 1378 additions and 146 deletions

258
admin_restaurants.php Normal file
View File

@ -0,0 +1,258 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Admin - Manage Restaurants</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>
body {
font-family: 'Poppins', -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif;
background-color: #F8F9FA;
color: #212529;
}
.btn-primary {
background-color: #FF6347;
border-color: #FF6347;
}
.btn-primary:hover {
background-color: #E5533D;
border-color: #E5533D;
}
.table {
background-color: #FFFFFF;
border-radius: 0.5rem;
box-shadow: 0 0.125rem 0.25rem rgba(0,0,0,0.075);
}
.card {
border-radius: 0.5rem;
}
.modal-content {
border-radius: 0.5rem;
}
.table th, .table td {
vertical-align: middle;
}
</style>
</head>
<body>
<div class="container mt-5">
<div class="d-flex justify-content-between align-items-center mb-4">
<h1>Manage Restaurants</h1>
<button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#restaurantModal" id="addNewBtn">
<i class="bi bi-plus-lg"></i> Add New Restaurant
</button>
</div>
<div class="card">
<div class="card-body">
<table class="table table-hover">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Address</th>
<th>Phone</th>
<th>Email</th>
<th>Cuisine</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="restaurantsTableBody">
<!-- Restaurants will be loaded here dynamically -->
</tbody>
</table>
</div>
</div>
</div>
<!-- Add/Edit Restaurant Modal -->
<div class="modal fade" id="restaurantModal" tabindex="-1" aria-labelledby="restaurantModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="restaurantModalLabel">Add New Restaurant</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form id="restaurantForm">
<input type="hidden" id="restaurantId" name="id">
<div class="mb-3">
<label for="name" class="form-label">Restaurant Name</label>
<input type="text" class="form-control" id="name" name="name" required>
</div>
<div class="mb-3">
<label for="address" class="form-label">Address</label>
<textarea class="form-control" id="address" name="address" rows="3" required></textarea>
</div>
<div class="mb-3">
<label for="phone" class="form-label">Phone Number</label>
<input type="text" class="form-control" id="phone" name="phone" required>
</div>
<div class="mb-3">
<label for="email" class="form-label">Contact Email</label>
<input type="email" class="form-control" id="email" name="email" required>
</div>
<div class="mb-3">
<label for="cuisine" class="form-label">Cuisine</label>
<input type="text" class="form-control" id="cuisine" name="cuisine" required>
</div>
<button type="submit" class="btn btn-primary">Save Restaurant</button>
</form>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
const restaurantModal = new bootstrap.Modal(document.getElementById('restaurantModal'));
const restaurantForm = document.getElementById('restaurantForm');
const restaurantModalLabel = document.getElementById('restaurantModalLabel');
const tableBody = document.getElementById('restaurantsTableBody');
// Fetch and display restaurants on page load
fetchRestaurants();
// Handle "Add New" button click
document.getElementById('addNewBtn').addEventListener('click', function() {
restaurantForm.reset();
document.getElementById('restaurantId').value = '';
restaurantModalLabel.textContent = 'Add New Restaurant';
});
// Handle form submission for both add and edit
restaurantForm.addEventListener('submit', function(e) {
e.preventDefault();
const formData = new FormData(this);
const data = Object.fromEntries(formData.entries());
const restaurantId = document.getElementById('restaurantId').value;
const isEdit = restaurantId !== '';
const url = isEdit ? `api/restaurants.php` : 'api/restaurants.php';
const method = isEdit ? 'PUT' : 'POST';
fetch(url, {
method: method,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
})
.then(response => response.json())
.then(result => {
if (result.success) {
restaurantModal.hide();
fetchRestaurants(); // Refresh the table
} else {
alert('Error: ' + result.error);
}
})
.catch(error => {
console.error('Error:', error);
alert('An unexpected error occurred.');
});
});
function fetchRestaurants() {
fetch('api/restaurants.php')
.then(response => response.json())
.then(result => {
if (result.success) {
renderTable(result.data);
} else {
tableBody.innerHTML = `<tr><td colspan="6" class="text-center">Could not load restaurants.</td></tr>`;
}
})
.catch(error => {
tableBody.innerHTML = `<tr><td colspan="6" class="text-center">Error loading restaurants.</td></tr>`;
});
}
function renderTable(restaurants) {
tableBody.innerHTML = '';
if (restaurants.length === 0) {
tableBody.innerHTML = `<tr><td colspan="6" class="text-center">No restaurants found.</td></tr>`;
return;
}
restaurants.forEach(r => {
const row = document.createElement('tr');
row.setAttribute('data-id', r.id);
row.innerHTML = `
<td>${r.id}</td>
<td data-field="name">${r.name}</td>
<td data-field="address">${r.address}</td>
<td data-field="phone">${r.phone}</td>
<td data-field="email">${r.email}</td>
<td data-field="cuisine">${r.cuisine}</td>
<td>
<a href="restaurant_menu.php?restaurant_id=${r.id}" class="btn btn-sm btn-info menu-btn" title="Manage Menu"><i class="bi bi-card-list"></i></a>
<button class="btn btn-sm btn-secondary edit-btn" title="Edit Restaurant"><i class="bi bi-pencil"></i></button>
<button class="btn btn-sm btn-danger delete-btn" title="Delete Restaurant"><i class="bi bi-trash"></i></button>
</td>
`;
tableBody.appendChild(row);
});
// Add event listeners for the new buttons
addEventListeners();
}
function addEventListeners() {
// Edit button handler
document.querySelectorAll('.edit-btn').forEach(button => {
button.addEventListener('click', function() {
const row = this.closest('tr');
const restaurantId = row.dataset.id;
document.getElementById('restaurantId').value = restaurantId;
document.getElementById('name').value = row.querySelector('[data-field="name"]').textContent;
document.getElementById('address').value = row.querySelector('[data-field="address"]').textContent;
document.getElementById('phone').value = row.querySelector('[data-field="phone"]').textContent;
document.getElementById('email').value = row.querySelector('[data-field="email"]').textContent;
document.getElementById('cuisine').value = row.querySelector('[data-field="cuisine"]').textContent;
restaurantModalLabel.textContent = 'Edit Restaurant';
restaurantModal.show();
});
});
// Delete button handler
document.querySelectorAll('.delete-btn').forEach(button => {
button.addEventListener('click', function() {
const row = this.closest('tr');
const restaurantId = row.dataset.id;
if (confirm('Are you sure you want to delete this restaurant?')) {
fetch(`api/restaurants.php`, {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id: restaurantId })
})
.then(response => response.json())
.then(result => {
if (result.success) {
row.remove();
} else {
alert('Error: ' + result.error);
}
})
.catch(error => {
console.error('Error:', error);
alert('An unexpected error occurred.');
});
}
});
});
}
});
</script>
</body>
</html>

56
api/favorites.php Normal file
View File

@ -0,0 +1,56 @@
<?php
session_start();
header('Content-Type: application/json');
require_once '../db/config.php';
$response = ['success' => false, 'loggedIn' => false, 'isFavorite' => false, 'message' => ''];
if (!isset($_SESSION['user_id'])) {
$response['message'] = 'You must be logged in to favorite a restaurant.';
echo json_encode($response);
exit;
}
$response['loggedIn'] = true;
$user_id = $_SESSION['user_id'];
$data = json_decode(file_get_contents('php://input'), true);
$restaurant_id = $data['restaurant_id'] ?? null;
if (!$restaurant_id || !is_numeric($restaurant_id)) {
$response['message'] = 'Invalid restaurant ID.';
echo json_encode($response);
exit;
}
$pdo = db();
// Check if it's already a favorite
$stmt = $pdo->prepare("SELECT id FROM favorite_restaurants WHERE user_id = ? AND restaurant_id = ?");
$stmt->execute([$user_id, $restaurant_id]);
$existing_favorite = $stmt->fetch();
if ($existing_favorite) {
// Remove from favorites
$stmt = $pdo->prepare("DELETE FROM favorite_restaurants WHERE id = ?");
if ($stmt->execute([$existing_favorite['id']])) {
$response['success'] = true;
$response['isFavorite'] = false;
$response['message'] = 'Restaurant removed from favorites.';
} else {
$response['message'] = 'Failed to remove from favorites.';
}
} else {
// Add to favorites
$stmt = $pdo->prepare("INSERT INTO favorite_restaurants (user_id, restaurant_id) VALUES (?, ?)");
if ($stmt->execute([$user_id, $restaurant_id])) {
$response['success'] = true;
$response['isFavorite'] = true;
$response['message'] = 'Restaurant added to favorites.';
} else {
$response['message'] = 'Failed to add to favorites.';
}
}
echo json_encode($response);

133
api/menu.php Normal file
View File

@ -0,0 +1,133 @@
<?php
require_once '../db/config.php';
header('Content-Type: application/json');
$method = $_SERVER['REQUEST_METHOD'];
switch ($method) {
case 'GET':
handle_get();
break;
case 'POST':
handle_post();
break;
case 'PUT':
handle_put();
break;
case 'DELETE':
handle_delete();
break;
default:
header('HTTP/1.1 405 Method Not Allowed');
echo json_encode(['success' => false, 'error' => 'Method Not Allowed']);
break;
}
function handle_get() {
if (empty($_GET['restaurant_id'])) {
header('HTTP/1.1 400 Bad Request');
echo json_encode(['success' => false, 'error' => 'Restaurant ID is required.']);
return;
}
$restaurant_id = $_GET['restaurant_id'];
try {
$pdo = db();
$stmt = $pdo->prepare("SELECT id, name, description, price, category FROM menu_items WHERE restaurant_id = :restaurant_id ORDER BY category, name");
$stmt->execute([':restaurant_id' => $restaurant_id]);
$menu_items = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode(['success' => true, 'data' => $menu_items]);
} catch (PDOException $e) {
header('HTTP/1.1 500 Internal Server Error');
echo json_encode(['success' => false, 'error' => 'Database error: ' . $e->getMessage()]);
}
}
function handle_post() {
$data = json_decode(file_get_contents('php://input'), true);
if (empty($data['restaurant_id']) || empty($data['name']) || !isset($data['price'])) {
header('HTTP/1.1 400 Bad Request');
echo json_encode(['success' => false, 'error' => 'Restaurant ID, name, and price are required.']);
return;
}
try {
$pdo = db();
$sql = "INSERT INTO menu_items (restaurant_id, name, description, price, category) VALUES (:restaurant_id, :name, :description, :price, :category)";
$stmt = $pdo->prepare($sql);
$stmt->execute([
':restaurant_id' => $data['restaurant_id'],
':name' => $data['name'],
':description' => $data['description'] ?? null,
':price' => $data['price'],
':category' => $data['category'] ?? null,
]);
$lastInsertId = $pdo->lastInsertId();
$stmt = $pdo->prepare("SELECT * FROM menu_items WHERE id = :id");
$stmt->execute(['id' => $lastInsertId]);
$newItem = $stmt->fetch(PDO::FETCH_ASSOC);
echo json_encode(['success' => true, 'data' => $newItem]);
} catch (PDOException $e) {
header('HTTP/1.1 500 Internal Server Error');
echo json_encode(['success' => false, 'error' => 'Database error: ' . $e->getMessage()]);
}
}
function handle_put() {
$data = json_decode(file_get_contents('php://input'), true);
if (empty($data['id']) || empty($data['name']) || !isset($data['price'])) {
header('HTTP/1.1 400 Bad Request');
echo json_encode(['success' => false, 'error' => 'All fields including ID are required.']);
return;
}
try {
$pdo = db();
$sql = "UPDATE menu_items SET name = :name, description = :description, price = :price, category = :category WHERE id = :id";
$stmt = $pdo->prepare($sql);
$stmt->execute([
':id' => $data['id'],
':name' => $data['name'],
':description' => $data['description'] ?? null,
':price' => $data['price'],
':category' => $data['category'] ?? null,
]);
echo json_encode(['success' => true]);
} catch (PDOException $e) {
header('HTTP/1.1 500 Internal Server Error');
echo json_encode(['success' => false, 'error' => 'Database error: ' . $e->getMessage()]);
}
}
function handle_delete() {
$data = json_decode(file_get_contents('php://input'), true);
if (empty($data['id'])) {
header('HTTP/1.1 400 Bad Request');
echo json_encode(['success' => false, 'error' => 'Menu item ID is required.']);
return;
}
try {
$pdo = db();
$sql = "DELETE FROM menu_items WHERE id = :id";
$stmt = $pdo->prepare($sql);
$stmt->execute([':id' => $data['id']]);
if ($stmt->rowCount() > 0) {
echo json_encode(['success' => true]);
} else {
header('HTTP/1.1 404 Not Found');
echo json_encode(['success' => false, 'error' => 'Menu item not found.']);
}
} catch (PDOException $e) {
header('HTTP/1.1 500 Internal Server Error');
echo json_encode(['success' => false, 'error' => 'Database error: ' . $e->getMessage()]);
}
}

128
api/restaurants.php Normal file
View File

@ -0,0 +1,128 @@
<?php
require_once '../db/config.php';
header('Content-Type: application/json');
$method = $_SERVER['REQUEST_METHOD'];
switch ($method) {
case 'GET':
handle_get();
break;
case 'POST':
handle_post();
break;
case 'PUT':
handle_put();
break;
case 'DELETE':
handle_delete();
break;
default:
header('HTTP/1.1 405 Method Not Allowed');
echo json_encode(['success' => false, 'error' => 'Method Not Allowed']);
break;
}
function handle_get() {
try {
$pdo = db();
$stmt = $pdo->query("SELECT id, name, cuisine, address, phone, email FROM restaurants ORDER BY created_at DESC");
$restaurants = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode(['success' => true, 'data' => $restaurants]);
} catch (PDOException $e) {
header('HTTP/1.1 500 Internal Server Error');
echo json_encode(['success' => false, 'error' => 'Database error: ' . $e->getMessage()]);
}
}
function handle_post() {
$data = json_decode(file_get_contents('php://input'), true);
if (empty($data['name']) || empty($data['address']) || empty($data['phone']) || empty($data['email']) || empty($data['cuisine'])) {
header('HTTP/1.1 400 Bad Request');
echo json_encode(['success' => false, 'error' => 'All fields are required.']);
return;
}
try {
$pdo = db();
$sql = "INSERT INTO restaurants (name, cuisine, address, phone, email) VALUES (:name, :cuisine, :address, :phone, :email)";
$stmt = $pdo->prepare($sql);
$stmt->execute([
':name' => $data['name'],
':cuisine' => $data['cuisine'],
':address' => $data['address'],
':phone' => $data['phone'],
':email' => $data['email'],
]);
$lastInsertId = $pdo->lastInsertId();
// Fetch the created restaurant to return it
$stmt = $pdo->prepare("SELECT id, name, cuisine, address, phone, email FROM restaurants WHERE id = :id");
$stmt->execute(['id' => $lastInsertId]);
$newRestaurant = $stmt->fetch(PDO::FETCH_ASSOC);
echo json_encode(['success' => true, 'data' => $newRestaurant]);
} catch (PDOException $e) {
header('HTTP/1.1 500 Internal Server Error');
echo json_encode(['success' => false, 'error' => 'Database error: ' . $e->getMessage()]);
}
}
function handle_put() {
$data = json_decode(file_get_contents('php://input'), true);
if (empty($data['id']) || empty($data['name']) || empty($data['address']) || empty($data['phone']) || empty($data['email']) || empty($data['cuisine'])) {
header('HTTP/1.1 400 Bad Request');
echo json_encode(['success' => false, 'error' => 'All fields including ID are required.']);
return;
}
try {
$pdo = db();
$sql = "UPDATE restaurants SET name = :name, cuisine = :cuisine, address = :address, phone = :phone, email = :email WHERE id = :id";
$stmt = $pdo->prepare($sql);
$stmt->execute([
':id' => $data['id'],
':name' => $data['name'],
':cuisine' => $data['cuisine'],
':address' => $data['address'],
':phone' => $data['phone'],
':email' => $data['email'],
]);
echo json_encode(['success' => true]);
} catch (PDOException $e) {
header('HTTP/1.1 500 Internal Server Error');
echo json_encode(['success' => false, 'error' => 'Database error: ' . $e->getMessage()]);
}
}
function handle_delete() {
$data = json_decode(file_get_contents('php://input'), true);
if (empty($data['id'])) {
header('HTTP/1.1 400 Bad Request');
echo json_encode(['success' => false, 'error' => 'Restaurant ID is required.']);
return;
}
try {
$pdo = db();
$sql = "DELETE FROM restaurants WHERE id = :id";
$stmt = $pdo->prepare($sql);
$stmt->execute([':id' => $data['id']]);
if ($stmt->rowCount() > 0) {
echo json_encode(['success' => true]);
} else {
header('HTTP/1.1 404 Not Found');
echo json_encode(['success' => false, 'error' => 'Restaurant not found.']);
}
} catch (PDOException $e) {
header('HTTP/1.1 500 Internal Server Error');
echo json_encode(['success' => false, 'error' => 'Database error: ' . $e->getMessage()]);
}
}

View File

@ -0,0 +1,8 @@
-- 003_create_users_table.sql
CREATE TABLE IF NOT EXISTS `users` (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`name` VARCHAR(255) NOT NULL,
`email` VARCHAR(255) NOT NULL UNIQUE,
`password_hash` VARCHAR(255) NOT NULL,
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

View File

@ -0,0 +1,10 @@
-- 004_create_favorite_restaurants_table.sql
CREATE TABLE IF NOT EXISTS `favorite_restaurants` (
`id` INT AUTO_INCREMENT PRIMARY KEY,
`user_id` INT NOT NULL,
`restaurant_id` INT NOT NULL,
`created_at` TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (`user_id`) REFERENCES `users`(`id`) ON DELETE CASCADE,
FOREIGN KEY (`restaurant_id`) REFERENCES `restaurants`(`id`) ON DELETE CASCADE,
UNIQUE KEY `user_restaurant_unique` (`user_id`, `restaurant_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;

59
favorites.php Normal file
View File

@ -0,0 +1,59 @@
<?php
require_once 'includes/header.php';
require_once 'db/config.php';
if (!isset($_SESSION['user_id'])) {
header("Location: login.php");
exit;
}
$user_id = $_SESSION['user_id'];
$favorite_restaurants = [];
try {
$pdo = db();
$stmt = $pdo->prepare("
SELECT r.id, r.name, r.cuisine, r.address
FROM restaurants r
JOIN favorite_restaurants fr ON r.id = fr.restaurant_id
WHERE fr.user_id = ?
ORDER BY r.name ASC
");
$stmt->execute([$user_id]);
$favorite_restaurants = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
error_log("Database error fetching favorites: " . $e->getMessage());
// Optionally, show a friendly error to the user
}
?>
<div class="container my-5">
<h1 class="mb-4">My Favorite Restaurants</h1>
<div class="row">
<?php if (empty($favorite_restaurants)): ?>
<div class="col">
<p class="text-center text-muted">You haven't added any favorite restaurants yet.</p>
<div class="text-center">
<a href="index.php" class="btn btn-primary">Find some restaurants</a>
</div>
</div>
<?php else: ?>
<?php foreach ($favorite_restaurants as $restaurant): ?>
<div class="col-md-4 mb-4">
<div class="card h-100 restaurant-card">
<div class="card-body d-flex flex-column">
<h5 class="card-title"><?= htmlspecialchars($restaurant['name']) ?></h5>
<p class="card-text"><span class="badge bg-secondary"><?= htmlspecialchars($restaurant['cuisine']) ?></span></p>
<p class="card-text text-muted flex-grow-1"><?= htmlspecialchars($restaurant['address']) ?></p>
<a href="menu.php?restaurant_id=<?= $restaurant['id'] ?>" class="btn btn-primary mt-auto">View Menu</a>
</div>
</div>
</div>
<?php endforeach; ?>
<?php endif; ?>
</div>
</div>
<?php require_once 'includes/footer.php'; ?>

5
includes/footer.php Normal file
View File

@ -0,0 +1,5 @@
</div> <!-- close container -->
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

45
includes/header.php Normal file
View File

@ -0,0 +1,45 @@
<?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>Restaurant Marketplace</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container">
<a class="navbar-brand" href="index.php"><i class="fas fa-utensils"></i> Restaurant Marketplace</a>
<button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
<span class="navbar-toggler-icon"></span>
</button>
<div class="collapse navbar-collapse" id="navbarNav">
<ul class="navbar-nav ms-auto">
<?php if (isset($_SESSION['user_id'])): ?>
<li class="nav-item">
<a class="nav-link" href="favorites.php">My Favorites</a>
</li>
<li class="nav-item">
<span class="nav-link">Welcome, <?php echo htmlspecialchars($_SESSION['user_name']); ?>!</span>
</li>
<li class="nav-item">
<a class="nav-link" href="logout.php">Logout</a>
</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">

242
index.php
View File

@ -1,150 +1,100 @@
<?php
declare(strict_types=1);
@ini_set('display_errors', '1');
@error_reporting(E_ALL);
@date_default_timezone_set('UTC');
require_once 'includes/header.php';
require_once 'db/config.php';
$restaurants = [];
$cuisines = [];
try {
$pdo = db();
$stmt = $pdo->query("SELECT id, name, cuisine, address, phone, email FROM restaurants ORDER BY name ASC");
$restaurants = $stmt->fetchAll(PDO::FETCH_ASSOC);
$stmt = $pdo->query("SELECT DISTINCT cuisine FROM restaurants WHERE cuisine IS NOT NULL AND cuisine != '' ORDER BY cuisine ASC");
$cuisines = $stmt->fetchAll(PDO::FETCH_COLUMN);
} catch (PDOException $e) {
error_log("Database error: " . $e->getMessage());
}
$phpVersion = PHP_VERSION;
$now = date('Y-m-d H:i:s');
?>
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>New Style</title>
<?php
// Read project preview data from environment
$projectDescription = $_SERVER['PROJECT_DESCRIPTION'] ?? '';
$projectImageUrl = $_SERVER['PROJECT_IMAGE_URL'] ?? '';
?>
<?php if ($projectDescription): ?>
<!-- Meta description -->
<meta name="description" content='<?= htmlspecialchars($projectDescription) ?>' />
<!-- Open Graph meta tags -->
<meta property="og:description" content="<?= htmlspecialchars($projectDescription) ?>" />
<!-- Twitter meta tags -->
<meta property="twitter:description" content="<?= htmlspecialchars($projectDescription) ?>" />
<?php endif; ?>
<?php if ($projectImageUrl): ?>
<!-- Open Graph image -->
<meta property="og:image" content="<?= htmlspecialchars($projectImageUrl) ?>" />
<!-- Twitter image -->
<meta property="twitter:image" content="<?= htmlspecialchars($projectImageUrl) ?>" />
<?php endif; ?>
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap" rel="stylesheet">
<style>
:root {
--bg-color-start: #6a11cb;
--bg-color-end: #2575fc;
--text-color: #ffffff;
--card-bg-color: rgba(255, 255, 255, 0.01);
--card-border-color: rgba(255, 255, 255, 0.1);
}
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>
<header class="hero">
<div class="container">
<h1 class="display-4">Find Your Next Meal</h1>
<p class="lead">Browse through our collection of partner restaurants.</p>
</div>
</main>
<footer>
Page updated: <?= htmlspecialchars($now) ?> (UTC)
</footer>
</body>
</html>
</header>
<main class="container my-5">
<div class="row mb-4">
<div class="col-md-8">
<input type="text" id="searchInput" class="form-control" placeholder="Search by restaurant name...">
</div>
<div class="col-md-4">
<select id="cuisineFilter" class="form-select">
<option value="">All Cuisines</option>
<?php foreach ($cuisines as $cuisine): ?>
<option value="<?= htmlspecialchars($cuisine) ?>"><?= htmlspecialchars($cuisine) ?></option>
<?php endforeach; ?>
</select>
</div>
</div>
<div class="row" id="restaurantList">
<?php if (empty($restaurants)): ?>
<div class="col">
<p class="text-center text-muted">No restaurants are available at the moment. Please check back later.</p>
</div>
<?php else: ?>
<?php foreach ($restaurants as $restaurant): ?>
<div class="col-md-4 mb-4 restaurant-item" data-name="<?= htmlspecialchars(strtolower($restaurant['name'])) ?>" data-cuisine="<?= htmlspecialchars(strtolower($restaurant['cuisine'])) ?>">
<div class="card h-100 restaurant-card">
<div class="card-body d-flex flex-column">
<h5 class="card-title"><?= htmlspecialchars($restaurant['name']) ?></h5>
<p class="card-text"><span class="badge bg-secondary"><?= htmlspecialchars($restaurant['cuisine']) ?></span></p>
<p class="card-text text-muted flex-grow-1"><?= htmlspecialchars($restaurant['address']) ?></p>
<a href="menu.php?restaurant_id=<?= $restaurant['id'] ?>" class="btn btn-primary mt-auto">View Menu</a>
</div>
</div>
</div>
<?php endforeach; ?>
<?php endif; ?>
</div>
<div id="noResults" class="text-center text-muted" style="display: none;">
<p>No restaurants match your search.</p>
</div>
</main>
<script>
document.addEventListener('DOMContentLoaded', function () {
const searchInput = document.getElementById('searchInput');
const cuisineFilter = document.getElementById('cuisineFilter');
const restaurantList = document.getElementById('restaurantList');
const restaurantItems = restaurantList.querySelectorAll('.restaurant-item');
const noResults = document.getElementById('noResults');
function filterRestaurants() {
const searchTerm = searchInput.value.toLowerCase();
const cuisineTerm = cuisineFilter.value.toLowerCase();
let resultsFound = false;
restaurantItems.forEach(item => {
const name = item.dataset.name;
const cuisine = item.dataset.cuisine;
const nameMatch = name.includes(searchTerm);
const cuisineMatch = cuisineTerm === '' || cuisine.includes(cuisineTerm);
if (nameMatch && cuisineMatch) {
item.style.display = '';
resultsFound = true;
} else {
item.style.display = 'none';
}
});
noResults.style.display = resultsFound ? 'none' : '';
}
searchInput.addEventListener('input', filterRestaurants);
cuisineFilter.addEventListener('change', filterRestaurants);
});
</script>
<?php require_once 'includes/footer.php'; ?>

84
login.php Normal file
View File

@ -0,0 +1,84 @@
<?php
session_start();
require_once 'db/config.php';
$error_message = '';
if (isset($_SESSION['user_id'])) {
header("Location: index.php");
exit;
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$email = trim($_POST['email']);
$password = $_POST['password'];
if (empty($email) || empty($password)) {
$error_message = "Please enter both email and password.";
} else {
$pdo = db();
$stmt = $pdo->prepare("SELECT id, name, password_hash FROM users WHERE email = ?");
$stmt->execute([$email]);
$user = $stmt->fetch();
if ($user && password_verify($password, $user['password_hash'])) {
$_SESSION['user_id'] = $user['id'];
$_SESSION['user_name'] = $user['name'];
header("Location: index.php");
exit;
} else {
$error_message = "Invalid email or password.";
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container">
<a class="navbar-brand" href="index.php"><i class="fas fa-utensils"></i> Restaurant Marketplace</a>
</div>
</nav>
<div class="container mt-5">
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card">
<div class="card-header">
<h3>Login</h3>
</div>
<div class="card-body">
<?php if ($error_message): ?>
<div class="alert alert-danger"><?php echo $error_message; ?></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 class="card-footer text-center">
Don't have an account? <a href="register.php">Register here</a>.
</div>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

6
logout.php Normal file
View File

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

142
menu.php Normal file
View File

@ -0,0 +1,142 @@
<?php
require_once 'includes/header.php';
require_once 'db/config.php';
if (!isset($_GET['restaurant_id']) || !is_numeric($_GET['restaurant_id'])) {
// Redirect or show a generic error page
header("Location: index.php?error=invalid_restaurant");
exit;
}
$restaurant_id = intval($_GET['restaurant_id']);
// Fetch restaurant details
$restaurant = null;
try {
$pdo = db();
$stmt = $pdo->prepare("SELECT name, address, phone FROM restaurants WHERE id = :id");
$stmt->execute(['id' => $restaurant_id]);
$restaurant = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
error_log("DB error fetching restaurant: " . $e->getMessage());
// Show a generic error page to the user
die("Error: Could not load restaurant information.");
}
if (!$restaurant) {
// Redirect or show a 404 page
header("Location: index.php?error=not_found");
exit;
}
$is_favorite = false;
if (isset($_SESSION['user_id'])) {
$stmt = $pdo->prepare("SELECT id FROM favorite_restaurants WHERE user_id = ? AND restaurant_id = ?");
$stmt->execute([$_SESSION['user_id'], $restaurant_id]);
if ($stmt->fetch()) {
$is_favorite = true;
}
}
// Fetch menu items
$menu_items = [];
try {
$stmt = $pdo->prepare("SELECT name, description, price, category FROM menu_items WHERE restaurant_id = :restaurant_id ORDER BY category, name");
$stmt->execute(['restaurant_id' => $restaurant_id]);
$menu_items = $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
error_log("DB error fetching menu items: " . $e->getMessage());
// It's okay to show the restaurant info even if menu fails to load
}
// Group menu items by category
$menu_by_category = [];
foreach ($menu_items as $item) {
$category = $item['category'] ?: 'Uncategorized';
$menu_by_category[$category][] = $item;
}
?>
<div class="menu-header text-center">
<div class="container">
<h1 class="display-5"><?= htmlspecialchars($restaurant['name']) ?></h1>
<p class="lead"><?= htmlspecialchars($restaurant['address']) ?></p>
<?php if ($restaurant['phone']): ?>
<p class="text-white-50">Call us at: <?= htmlspecialchars($restaurant['phone']) ?></p>
<?php endif; ?>
<?php if (isset($_SESSION['user_id'])):
$btn_class = $is_favorite ? 'btn-danger' : 'btn-outline-warning';
$btn_text = $is_favorite ? '<i class="fas fa-heart-broken"></i> Unfavorite' : '<i class="fas fa-heart"></i> Favorite';
?>
<button id="favoriteBtn" class="btn btn-lg <?= $btn_class ?> mt-3" data-restaurant-id="<?= $restaurant_id ?>">
<?= $btn_text ?>
</button>
<?php endif; ?>
<a href="index.php" class="btn btn-sm btn-outline-light mt-3"><i class="bi bi-arrow-left"></i> Back to all restaurants</a>
</div>
</div>
<main class="container my-5">
<?php if (empty($menu_by_category)): ?>
<div class="text-center">
<p class="text-muted fs-4">This restaurant hasn't added any menu items yet.</p>
</div>
<?php else: ?>
<?php foreach ($menu_by_category as $category => $items): ?>
<div class="mb-5">
<h2 class="mb-4"><?= htmlspecialchars($category) ?></h2>
<?php foreach ($items as $item): ?>
<div class="row menu-item">
<div class="col-8">
<h5 class="mb-1"><?= htmlspecialchars($item['name']) ?></h5>
<p class="text-muted mb-0"><?= htmlspecialchars($item['description']) ?></p>
</div>
<div class="col-4 text-end">
<p class="fw-bold fs-5">$<?= htmlspecialchars(number_format((float)$item['price'], 2)) ?></p>
</div>
</div>
<?php endforeach; ?>
</div>
<?php endforeach; ?>
<?php endif; ?>
</main>
<?php require_once 'includes/footer.php'; ?>
<script>
document.addEventListener('DOMContentLoaded', function() {
const favoriteBtn = document.getElementById('favoriteBtn');
if (favoriteBtn) {
favoriteBtn.addEventListener('click', function() {
const restaurantId = this.dataset.restaurantId;
fetch('api/favorites.php', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({ restaurant_id: restaurantId })
})
.then(response => response.json())
.then(data => {
if (data.success) {
if (data.isFavorite) {
this.classList.remove('btn-outline-warning');
this.classList.add('btn-danger');
this.innerHTML = '<i class="fas fa-heart-broken"></i> Unfavorite';
} else {
this.classList.remove('btn-danger');
this.classList.add('btn-outline-warning');
this.innerHTML = '<i class="fas fa-heart"></i> Favorite';
}
} else {
alert(data.message || 'An error occurred.');
}
})
.catch(error => {
console.error('Error:', error);
alert('An error occurred. Please try again.');
});
});
}
});
</script>

99
register.php Normal file
View File

@ -0,0 +1,99 @@
<?php
session_start();
require_once 'db/config.php';
$error_message = '';
$success_message = '';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = trim($_POST['name']);
$email = trim($_POST['email']);
$password = $_POST['password'];
$password_confirm = $_POST['password_confirm'];
if (empty($name) || empty($email) || empty($password)) {
$error_message = "Please fill in all fields.";
} elseif ($password !== $password_confirm) {
$error_message = "Passwords do not match.";
} elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$error_message = "Invalid email format.";
} else {
$pdo = db();
$stmt = $pdo->prepare("SELECT id FROM users WHERE email = ?");
$stmt->execute([$email]);
if ($stmt->fetch()) {
$error_message = "An account with this email already exists.";
} else {
$password_hash = password_hash($password, PASSWORD_DEFAULT);
$stmt = $pdo->prepare("INSERT INTO users (name, email, password_hash) VALUES (?, ?, ?)");
if ($stmt->execute([$name, $email, $password_hash])) {
$success_message = "Registration successful! You can now <a href='login.php'>log in</a>.";
} else {
$error_message = "An error occurred. Please try again.";
}
}
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Register</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
</head>
<body>
<nav class="navbar navbar-expand-lg navbar-light bg-light">
<div class="container">
<a class="navbar-brand" href="index.php"><i class="fas fa-utensils"></i> Restaurant Marketplace</a>
</div>
</nav>
<div class="container mt-5">
<div class="row justify-content-center">
<div class="col-md-6">
<div class="card">
<div class="card-header">
<h3>Register</h3>
</div>
<div class="card-body">
<?php if ($error_message): ?>
<div class="alert alert-danger"><?php echo $error_message; ?></div>
<?php endif; ?>
<?php if ($success_message): ?>
<div class="alert alert-success"><?php echo $success_message; ?></div>
<?php else: ?>
<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="password_confirm" class="form-label">Confirm Password</label>
<input type="password" class="form-control" id="password_confirm" name="password_confirm" required>
</div>
<button type="submit" class="btn btn-primary">Register</button>
</form>
<?php endif; ?>
</div>
<div class="card-footer text-center">
Already have an account? <a href="login.php">Login here</a>.
</div>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>

249
restaurant_menu.php Normal file
View File

@ -0,0 +1,249 @@
<?php
require_once 'db/config.php';
// Get restaurant ID from URL
if (!isset($_GET['restaurant_id']) || !is_numeric($_GET['restaurant_id'])) {
die("A valid restaurant ID is required.");
}
$restaurant_id = intval($_GET['restaurant_id']);
// Fetch restaurant details
$restaurant_name = 'Unknown Restaurant';
try {
$pdo = db();
$stmt = $pdo->prepare("SELECT name FROM restaurants WHERE id = :id");
$stmt->execute(['id' => $restaurant_id]);
$restaurant = $stmt->fetch(PDO::FETCH_ASSOC);
if ($restaurant) {
$restaurant_name = htmlspecialchars($restaurant['name']);
} else {
die("Restaurant not found.");
}
} catch (PDOException $e) {
die("Database error while fetching restaurant details.");
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Manage Menu for <?php echo $restaurant_name; ?></title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.3/font/bootstrap-icons.min.css">
<link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap" rel="stylesheet">
<style>
body { font-family: 'Poppins', sans-serif; background-color: #F8F9FA; }
.btn-primary { background-color: #4682B4; border-color: #4682B4; }
.btn-primary:hover { background-color: #3A6A92; border-color: #3A6A92; }
.table { background-color: #FFFFFF; border-radius: 0.5rem; box-shadow: 0 0.125rem 0.25rem rgba(0,0,0,0.075); }
.card, .modal-content { border-radius: 0.5rem; }
.table th, .table td { vertical-align: middle; }
</style>
</head>
<body>
<div class="container mt-5">
<div class="d-flex justify-content-between align-items-center mb-4">
<div>
<a href="admin_restaurants.php" class="btn btn-sm btn-outline-secondary mb-2"><i class="bi bi-arrow-left"></i> Back to Restaurants</a>
<h1>Manage Menu</h1>
<h5 class="text-muted">for <?php echo $restaurant_name; ?></h5>
</div>
<button class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#menuItemModal" id="addNewBtn">
<i class="bi bi-plus-lg"></i> Add New Item
</button>
</div>
<div class="card">
<div class="card-body">
<table class="table table-hover">
<thead>
<tr>
<th>Name</th>
<th>Description</th>
<th>Price</th>
<th>Category</th>
<th>Actions</th>
</tr>
</thead>
<tbody id="menuItemsTableBody">
<!-- Menu items will be loaded here dynamically -->
</tbody>
</table>
</div>
</div>
</div>
<!-- Add/Edit Menu Item Modal -->
<div class="modal fade" id="menuItemModal" tabindex="-1" aria-labelledby="menuItemModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="menuItemModalLabel">Add New Menu Item</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
</div>
<div class="modal-body">
<form id="menuItemForm">
<input type="hidden" id="menuItemId" name="id">
<input type="hidden" id="restaurantId" name="restaurant_id" value="<?php echo $restaurant_id; ?>">
<div class="mb-3">
<label for="name" class="form-label">Item Name</label>
<input type="text" class="form-control" id="name" name="name" 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>
<div class="row">
<div class="col-md-6 mb-3">
<label for="price" class="form-label">Price</label>
<div class="input-group">
<span class="input-group-text">$</span>
<input type="number" class="form-control" id="price" name="price" step="0.01" required>
</div>
</div>
<div class="col-md-6 mb-3">
<label for="category" class="form-label">Category</label>
<input type="text" class="form-control" id="category" name="category" placeholder="e.g., Appetizer, Main, Dessert">
</div>
</div>
<button type="submit" class="btn btn-primary">Save Item</button>
</form>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
document.addEventListener('DOMContentLoaded', function() {
const restaurantId = <?php echo $restaurant_id; ?>;
const menuItemModal = new bootstrap.Modal(document.getElementById('menuItemModal'));
const menuItemForm = document.getElementById('menuItemForm');
const menuItemModalLabel = document.getElementById('menuItemModalLabel');
const tableBody = document.getElementById('menuItemsTableBody');
fetchMenuItems();
document.getElementById('addNewBtn').addEventListener('click', function() {
menuItemForm.reset();
document.getElementById('menuItemId').value = '';
document.getElementById('restaurantId').value = restaurantId; // Ensure restaurantId is set on new items
menuItemModalLabel.textContent = 'Add New Menu Item';
});
menuItemForm.addEventListener('submit', function(e) {
e.preventDefault();
const formData = new FormData(this);
const data = Object.fromEntries(formData.entries());
const menuItemId = document.getElementById('menuItemId').value;
const isEdit = menuItemId !== '';
const method = isEdit ? 'PUT' : 'POST';
fetch('api/menu.php', {
method: method,
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(data),
})
.then(response => response.json())
.then(result => {
if (result.success) {
menuItemModal.hide();
fetchMenuItems();
} else {
alert('Error: ' + result.error);
}
})
.catch(error => console.error('Error:', error));
});
function fetchMenuItems() {
fetch(`api/menu.php?restaurant_id=${restaurantId}`)
.then(response => response.json())
.then(result => {
if (result.success) {
renderTable(result.data);
} else {
tableBody.innerHTML = `<tr><td colspan="5" class="text-center">Could not load menu items.</td></tr>`;
}
})
.catch(error => {
tableBody.innerHTML = `<tr><td colspan="5" class="text-center">Error loading menu items.</td></tr>`;
});
}
function renderTable(items) {
tableBody.innerHTML = '';
if (items.length === 0) {
tableBody.innerHTML = `<tr><td colspan="5" class="text-center">No menu items found. Add one to get started.</td></tr>`;
return;
}
items.forEach(item => {
const row = document.createElement('tr');
row.setAttribute('data-id', item.id);
row.innerHTML = `
<td data-field="name">${item.name}</td>
<td data-field="description">${item.description || ''}</td>
<td data-field="price">${parseFloat(item.price).toFixed(2)}</td>
<td data-field="category">${item.category || ''}</td>
<td>
<button class="btn btn-sm btn-secondary edit-btn"><i class="bi bi-pencil"></i></button>
<button class="btn btn-sm btn-danger delete-btn"><i class="bi bi-trash"></i></button>
</td>
`;
tableBody.appendChild(row);
});
addEventListeners();
}
function addEventListeners() {
document.querySelectorAll('.edit-btn').forEach(button => {
button.addEventListener('click', function() {
const row = this.closest('tr');
const menuItemId = row.dataset.id;
document.getElementById('menuItemId').value = menuItemId;
document.getElementById('name').value = row.querySelector('[data-field="name"]').textContent;
document.getElementById('description').value = row.querySelector('[data-field="description"]').textContent;
document.getElementById('price').value = row.querySelector('[data-field="price"]').textContent;
document.getElementById('category').value = row.querySelector('[data-field="category"]').textContent;
menuItemModalLabel.textContent = 'Edit Menu Item';
menuItemModal.show();
});
});
document.querySelectorAll('.delete-btn').forEach(button => {
button.addEventListener('click', function() {
const row = this.closest('tr');
const menuItemId = row.dataset.id;
if (confirm('Are you sure you want to delete this menu item?')) {
fetch(`api/menu.php`, {
method: 'DELETE',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ id: menuItemId })
})
.then(response => response.json())
.then(result => {
if (result.success) {
row.remove();
} else {
alert('Error: ' + result.error);
}
})
.catch(error => console.error('Error:', error));
}
});
});
}
});
</script>
</body>
</html>