update to use single html with dynamic div

This commit is contained in:
max 2025-04-16 09:31:36 +02:00
parent 0dcdfa7e76
commit 1d3febeec1
21 changed files with 794 additions and 179 deletions

View File

@ -1,46 +0,0 @@
<?php
include 'db_connection.php';
session_start();
if (!isset($_SESSION['username'])) {
header("Location: login.php"); // Redirect if not logged in
exit();
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = sanitize_input($_POST['name']);
$maps_link = sanitize_input($_POST['maps_link']);
$sql = "INSERT INTO Restaurant (name, maps_link) VALUES ('$name', '$maps_link')";
if ($conn->query($sql) === TRUE) {
$restaurant_success = "Restaurant added successfully!";
} else {
$restaurant_error = "Error: " . $sql . "<br>" . $conn->error;
}
}
$conn->close();
?>
<!DOCTYPE html>
<html>
<head>
<title>Add Restaurant</title>
</head>
<body>
<h2>Add New Restaurant</h2>
<?php if (isset($restaurant_error)): ?>
<p style="color:red;"><?php echo $restaurant_error; ?></p>
<?php endif; ?>
<?php if (isset($restaurant_success)): ?>
<p style="color:green;"><?php echo $restaurant_success; ?></p>
<?php endif; ?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
Name: <input type="text" name="name" required><br><br>
Maps Link: <input type="text" name="maps_link"><br><br>
<input type="submit" value="Add Restaurant">
</form>
<p><a href="index.php">Back to Dashboard</a></p>
</body>
</html>

View File

@ -128,7 +128,7 @@ th {
/* Specific elements for your pages */
/* You can add more specific styles here as needed */
/* Example for the welcome message on index.php */
/* Example for the welcome message on index.html */
.welcome-message {
margin-bottom: 20px;
font-size: 1.2em;

View File

@ -1,60 +0,0 @@
<?php
$databaseFile = 'mydatabase.db';
try {
$db = new PDO("sqlite:" . $databaseFile);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Check if the User table exists
$result = $db->query("SELECT name FROM sqlite_master WHERE type='table' AND name='User'");
$userTableExists = $result->fetchColumn();
if (!$userTableExists) {
// Initialize the database structure
$db->exec("
CREATE TABLE User (
id INTEGER PRIMARY KEY AUTOINCREMENT,
vorname TEXT NOT NULL,
nachname TEXT NOT NULL,
username TEXT UNIQUE NOT NULL,
password TEXT NOT NULL
)
");
$db->exec("
CREATE TABLE Restaurant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
maps_link TEXT
)
");
$db->exec("
CREATE TABLE Bewertung (
id INTEGER PRIMARY KEY AUTOINCREMENT,
fk_user_id INTEGER NOT NULL,
fk_restaurant_id INTEGER NOT NULL,
bewertung INTEGER NOT NULL CHECK (bewertung BETWEEN 0 AND 10),
bewertung_str TEXT,
FOREIGN KEY (fk_user_id) REFERENCES User(id),
FOREIGN KEY (fk_restaurant_id) REFERENCES Restaurant(id)
)
");
echo "<p style='color:green;'>Database initialized successfully!</p>";
} else {
// Optionally, you can add a message indicating the database already exists
// echo "<p style='color:blue;'>Database already exists.</p>";
}
} catch (PDOException $e) {
die("Database connection failed: " . $e->getMessage());
}
function sanitize_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>

View File

@ -0,0 +1,8 @@
<h2>Add New Restaurant</h2>
<div class="error"></div>
<div class="success"></div>
<form id="add-restaurant-form">
Name: <input type="text" name="name" required><br><br>
Maps Link: <input type="text" name="maps_link"><br><br>
<input type="submit" value="Add Restaurant">
</form>

81
htmls/chart.html Normal file
View File

@ -0,0 +1,81 @@
<h2>Restaurant Tier List</h2>
<div id="tier-list">
</div>
<style>
.tier {
margin-bottom: 20px;
border: 1px solid #ccc;
padding: 10px;
border-radius: 5px;
}
.tier h3 {
margin-top: 0;
}
.restaurant-item {
padding: 8px;
margin-bottom: 5px;
border-left: 5px solid;
border-radius: 3px;
}
.tier-S { border-color: #4CAF50; background-color: #e8f5e9; } /* Green */
.tier-A { border-color: #2196F3; background-color: #e3f2fd; } /* Blue */
.tier-B { border-color: #FFC107; background-color: #fffde7; } /* Yellow */
.tier-C { border-color: #FF9800; background-color: #ffe0b2; } /* Orange */
.tier-D { border-color: #F44336; background-color: #ffebee; } /* Red */
.tier-Unrated { border-color: #9e9e9e; background-color: #f5f5f5; } /* Grey */
</style>
<script>
function loadTierList() {
const tierListDiv = document.getElementById('tier-list');
tierListDiv.innerHTML = '<p>Loading tier list...</p>';
fetch('../php/get_restaurant_tiers.php')
.then(response => response.json())
.then(data => {
tierListDiv.innerHTML = '';
const tierOrder = ['S', 'A', 'B', 'C', 'D', 'Unrated'];
tierOrder.forEach(tier => {
if (data[tier] && data[tier].length > 0) {
const tierDiv = document.createElement('div');
tierDiv.classList.add('tier', `tier-${tier}`);
tierDiv.innerHTML = `<h3>Tier ${tier}</h3>`;
const ul = document.createElement('ul');
data[tier].forEach(restaurant => {
const li = document.createElement('li');
li.classList.add('restaurant-item');
li.textContent = `${restaurant.name} (Score: ${restaurant.median_score !== null ? restaurant.median_score : 'N/A'})`;
ul.appendChild(li);
});
tierDiv.appendChild(ul);
tierListDiv.appendChild(tierDiv);
} else if (tier === 'Unrated' && data[tier] && data[tier].length > 0) {
const tierDiv = document.createElement('div');
tierDiv.classList.add('tier', `tier-${tier}`);
tierDiv.innerHTML = `<h3>Tier ${tier}</h3>`;
const ul = document.createElement('ul');
data[tier].forEach(restaurant => {
const li = document.createElement('li');
li.classList.add('restaurant-item');
li.textContent = `${restaurant.name} (Score: N/A)`;
ul.appendChild(li);
});
tierDiv.appendChild(ul);
tierListDiv.appendChild(tierDiv);
}
});
})
.catch(error => {
console.error('Error loading tier list:', error);
tierListDiv.innerHTML = '<p class="error">Failed to load tier list.</p>';
});
}
// Call this function when chart.html is loaded
loadTierList();
</script>

8
htmls/login.html Normal file
View File

@ -0,0 +1,8 @@
<h2>Login</h2>
<div class="error"></div>
<form id="login-form">
Username: <input type="text" name="username" required><br><br>
Password: <input type="password" name="password" required><br><br>
<input type="submit" value="Login">
</form>
<button id="register-btn">Request Account</button>

21
htmls/overview.html Normal file
View File

@ -0,0 +1,21 @@
<h2>Restaurant Overview</h2>
<div id="restaurant-list">
</div>
<script>
// This script might be moved to the main index.html or a separate JS file
function loadRestaurantOverview() {
const restaurantListDiv = document.getElementById('restaurant-list');
fetch('php/get_restaurant_overview.php')
.then(response => response.text())
.then(data => {
restaurantListDiv.innerHTML = data;
})
.catch(error => {
console.error('Error loading restaurant overview:', error);
restaurantListDiv.innerHTML = '<p class="error">Failed to load restaurant overview.</p>';
});
}
// Call this function when overview.html is loaded
loadRestaurantOverview();
</script>

View File

@ -0,0 +1,47 @@
<h2>Request Account</h2>
<div class="error"></div>
<div class="success"></div>
<form id="register-request-form">
Vorname: <input type="text" name="vorname" required><br><br>
Nachname: <input type="text" name="nachname" required><br><br>
Username: <input type="text" name="username" required><br><br>
<input type="submit" value="Request Account">
</form>
<script>
document.getElementById('register-request-form').addEventListener('submit', function(event) {
event.preventDefault();
const formData = new FormData(this);
fetch('../php/register_request.php', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
const errorDiv = document.querySelector('#register-request-form + .error');
const successDiv = document.querySelector('#register-request-form + .error + .success');
if (data.success) {
if (successDiv) {
successDiv.textContent = data.message;
} else {
document.querySelector('#register-request-form').insertAdjacentHTML('afterend', '<p class="success">' + data.message + '</p>');
}
document.getElementById('register-request-form').reset();
} else {
if (errorDiv) {
errorDiv.textContent = data.error;
} else {
document.querySelector('#register-request-form').insertAdjacentHTML('afterend', '<p class="error">' + data.error + '</p>');
}
}
})
.catch(error => {
console.error('Error requesting registration:', error);
const errorDiv = document.querySelector('#register-request-form + .error');
if (errorDiv) {
errorDiv.textContent = 'Failed to request account due to network error.';
} else {
document.querySelector('#register-request-form').insertAdjacentHTML('afterend', '<p class="error">Failed to request account due to network error.</p>');
}
});
});
</script>

268
index.html Normal file
View File

@ -0,0 +1,268 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Restaurant Review Site</title>
<link rel="stylesheet" type="text/css" href="central.css">
<style>
/* ... (rest of your existing styles in <style> tag) ... */
</style>
</head>
<body>
<div id="menu-bar">
<ul>
<li><a href="#" data-target="login.html" id="login-link">Login</a></li>
<li><a href="#" data-target="chart.html">Chart</a></li>
<li><a href="#" data-target="overview.html">Overview</a></li>
<li id="admin-link-item" style="display: none;"><a href="#" data-target="logged_in.html">Admin</a></li>
</ul>
<a id="add-restaurant-btn" href="#" data-target="add_restaurant.html" style="display: none;">Add Restaurant</a>
</div>
<div id="content-area">
</div>
<script>
const contentArea = document.getElementById('content-area');
const menuLinks = document.querySelectorAll('#menu-bar a[data-target]');
const addRestaurantBtn = document.getElementById('add-restaurant-btn');
const loginLink = document.getElementById('login-link');
const adminLinkItem = document.getElementById('admin-link-item');
function loadContent(url) {
fetch('htmls/' + url)
.then(response => response.text())
.then(data => {
contentArea.innerHTML = data;
// Re-attach event listeners for dynamic content
attachFormListeners(url);
if (url === 'overview.html') {
loadRestaurantOverview(); // If this function is only in overview.html
} else if (url === 'chart.html') {
loadTierList(); // If this function is only in chart.html
} else if (url === 'logged_in.html') {
loadRegistrationRequests(); // Load admin content
}
})
.catch(error => {
console.error('Error loading content:', error);
contentArea.innerHTML = '<p class="error">Failed to load content.</p>';
});
}
function attachFormListeners(url) {
if (url === 'login.html') {
const registerButton = contentArea.querySelector('#register-btn');
if (registerButton) {
registerButton.addEventListener('click', () => {
loadContent('register_request.html');
});
}
const loginForm = contentArea.querySelector('#login-form');
if (loginForm) {
loginForm.addEventListener('submit', handleLoginFormSubmit);
}
} else if (url === 'add_restaurant.html') {
const addRestaurantForm = contentArea.querySelector('#add-restaurant-form');
if (addRestaurantForm) {
addRestaurantForm.addEventListener('submit', handleAddRestaurantFormSubmit);
}
} else if (url === 'register_request.html') {
const registerRequestForm = contentArea.querySelector('#register-request-form');
if (registerRequestForm) {
registerRequestForm.addEventListener('submit', handleRegisterRequestFormSubmit);
}
} else if (url === 'logged_in.html') {
// Event listeners for accept/reject buttons are attached in loadRegistrationRequests()
const changePasswordForm = contentArea.querySelector('#change-password-form');
if (changePasswordForm) {
changePasswordForm.addEventListener('submit', handleChangePasswordFormSubmit);
}
}
}
function handleLoginFormSubmit(event) {
event.preventDefault();
const formData = new FormData(this);
fetch('php/login.php', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
if (data.success) {
setLoggedInCookie();
checkLoginStatus(); // Reload content based on login
} else {
const errorDiv = contentArea.querySelector('.error');
if (errorDiv) {
errorDiv.textContent = data.error;
} else {
contentArea.innerHTML += '<p class="error">' + data.error + '</p>';
}
}
})
.catch(error => {
console.error('Error during login:', error);
contentArea.innerHTML = '<p class="error">Login failed due to network error.</p>';
});
}
function handleAddRestaurantFormSubmit(event) {
event.preventDefault();
const formData = new FormData(this);
fetch('php/add_restaurant.php', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
const errorDiv = contentArea.querySelector('.error');
const successDiv = contentArea.querySelector('.success');
if (data.success) {
if (successDiv) {
successDiv.textContent = data.message;
} else {
contentArea.innerHTML += '<p class="success">' + data.message + '</p>';
}
document.getElementById('add-restaurant-form').reset();
} else {
if (errorDiv) {
errorDiv.textContent = data.error;
} else {
contentArea.innerHTML += '<p class="error">' + data.error + '</p>';
}
}
})
.catch(error => {
console.error('Error adding restaurant:', error);
contentArea.innerHTML = '<p class="error">Failed to add restaurant.</p>';
});
}
function handleRegisterRequestFormSubmit(event) {
event.preventDefault();
const formData = new FormData(this);
fetch('php/register_request.php', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
const errorDiv = contentArea.querySelector('#register-request-form + .error');
const successDiv = contentArea.querySelector('#register-request-form + .error + .success');
if (data.success) {
if (successDiv) {
successDiv.textContent = data.message;
} else {
document.querySelector('#register-request-form').insertAdjacentHTML('afterend', '<p class="success">' + data.message + '</p>');
}
document.getElementById('register-request-form').reset();
} else {
if (errorDiv) {
errorDiv.textContent = data.error;
} else {
document.querySelector('#register-request-form').insertAdjacentHTML('afterend', '<p class="error">' + data.error + '</p>');
}
}
})
.catch(error => {
console.error('Error requesting registration:', error);
const errorDiv = document.querySelector('#register-request-form + .error');
if (errorDiv) {
errorDiv.textContent = 'Failed to request account due to network error.';
} else {
document.querySelector('#register-request-form').insertAdjacentHTML('afterend', '<p class="error">Failed to request account due to network error.</p>');
}
});
}
function handleChangePasswordFormSubmit(event) {
event.preventDefault();
const formData = new FormData(this);
fetch('php/process_registration.php', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => {
if (data.success) {
alert(data.message);
document.getElementById('change-password-form').reset();
} else {
alert(data.error);
}
})
.catch(error => {
console.error('Error changing password:', error);
alert('Failed to change password.');
});
}
function setLoggedInCookie() {
const expiryDate = new Date(Date.now() + 10 * 60 * 1000); // 10 minutes
document.cookie = `loggedIn=true; expires=${expiryDate.toUTCString()}; path=/`;
}
function deleteLoggedInCookie() {
document.cookie = 'loggedIn=; expires=Thu, 01 Jan 1970 00:00:00 UTC; path=/;';
}
function getCookie(name) {
const value = `; ${document.cookie}`;
const parts = value.split(`; ${name}=`);
if (parts.length === 2) return parts.pop().split(';').shift();
}
function checkLoginStatus() {
const loggedIn = getCookie('loggedIn');
if (loggedIn) {
loginLink.textContent = 'Logout';
loginLink.removeEventListener('click', handleLoginClick);
loginLink.addEventListener('click', handleLogoutClick);
// For simplicity, we'll just show the admin link if logged in.
// A more robust solution would involve checking the user's role on the server.
adminLinkItem.style.display = 'inline-block';
addRestaurantBtn.style.display = 'inline-block';
loadContent('overview.html'); // Load a default logged-in view
} else {
loginLink.textContent = 'Login';
loginLink.removeEventListener('click', handleLogoutClick);
loginLink.addEventListener('click', handleLoginClick);
adminLinkItem.style.display = 'none';
addRestaurantBtn.style.display = 'none';
loadContent('login.html'); // Load login form by default
}
}
function handleLoginClick(event) {
event.preventDefault();
loadContent('login.html');
}
function handleLogoutClick(event) {
event.preventDefault();
fetch('php/logout.php')
.then(response => response.json())
.then(data => {
if (data.success) {
deleteLoggedInCookie();
checkLoginStatus(); // Reload based on logout
} else {
console.error('Logout failed:', data.error);
alert('Logout failed.');
}
})
.catch(error => {
console.error('Error during logout:', error);
alert('Logout failed due to network error.');
});
}
// Initial check on page load
checkLoginStatus();
</script>
</body>
</html>

View File

@ -1,13 +0,0 @@
<?php
session_start();
if (!isset($_SESSION['username'])) {
header("Location: login.php"); // Redirect if not logged in
exit();
}
echo "Welcome, " . $_SESSION['username'] . "!";
echo "<p><a href='add_restaurant.php'>Add Restaurant</a></p>";
echo "<p><a href='add_review.php'>Add Review</a></p>";
echo "<p><a href='logout.php'>Logout</a></p>";
?>

View File

@ -1,52 +0,0 @@
<?php
include 'db_connection.php';
session_start();
if (isset($_SESSION['username'])) {
header("Location: index.php"); // Redirect to a logged-in page
exit();
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = sanitize_input($_POST['username']);
$password = sanitize_input($_POST['password']);
$sql = "SELECT id, username, password FROM User WHERE username='$username'";
$result = $conn->query($sql);
if ($result->num_rows == 1) {
$row = $result->fetch_assoc();
if (password_verify($password, $row['password'])) {
$_SESSION['username'] = $row['username'];
$_SESSION['user_id'] = $row['id'];
header("Location: index.php"); // Redirect after successful login
exit();
} else {
$login_error = "Invalid username or password.";
}
} else {
$login_error = "Invalid username or password.";
}
}
$conn->close();
?>
<!DOCTYPE html>
<html>
<head>
<title>Login</title>
</head>
<body>
<h2>Login</h2>
<?php if (isset($login_error)): ?>
<p style="color:red;"><?php echo $login_error; ?></p>
<?php endif; ?>
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>">
Username: <input type="text" name="username" required><br><br>
Password: <input type="password" name="password" required><br><br>
<input type="submit" value="Login">
</form>
<p>Don't have an account? <a href="register.php">Register here</a></p>
</body>
</html>

View File

@ -1,6 +0,0 @@
<?php
session_start();
session_destroy();
header("Location: login.php"); // Redirect to login page after logout
exit();
?>

29
php/add_restaurant.php Normal file
View File

@ -0,0 +1,29 @@
<?php
include 'db_connection.php';
session_start();
if (!isset($_SESSION['username'])) {
echo json_encode(['success' => false, 'error' => 'Not logged in.']);
exit();
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$name = sanitize_input($_POST['name']);
$maps_link = sanitize_input($_POST['maps_link']);
$stmt = $db->prepare("INSERT INTO Restaurant (name, maps_link) VALUES (:name, :maps_link)");
$stmt->bindParam(':name', $name);
$stmt->bindParam(':maps_link', $maps_link);
if ($stmt->execute()) {
echo json_encode(['success' => true, 'message' => 'Restaurant added successfully!']);
exit();
} else {
echo json_encode(['success' => false, 'error' => 'Error: ' . print_r($stmt->errorInfo(), true)]);
exit();
}
} else {
echo json_encode(['success' => false, 'error' => 'Invalid request method.']);
exit();
}
?>

View File

@ -65,6 +65,6 @@ $conn->close();
Review Text: <textarea name="bewertung_str"></textarea><br><br>
<input type="submit" value="Add Review">
</form>
<p><a href="index.php">Back to Dashboard</a></p>
<p><a href="index.html">Back to Dashboard</a></p>
</body>
</html>

91
php/db_connection.php Normal file
View File

@ -0,0 +1,91 @@
<?php
$databaseFile = '../mydatabase.db';
try {
$db = new PDO("sqlite:" . $databaseFile);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
// Check if the User table exists
$result = $db->query("SELECT name FROM sqlite_master WHERE type='table' AND name='User'");
$userTableExists = $result->fetchColumn();
if (!$userTableExists) {
// Initialize the database structure
$db->exec("
CREATE TABLE User (
id INTEGER PRIMARY KEY AUTOINCREMENT,
vorname TEXT NOT NULL,
nachname TEXT NOT NULL,
username TEXT UNIQUE NOT NULL,
password TEXT NOT NULL,
active BOOLEAN DEFAULT 0
)
");
$db->exec("
CREATE TABLE Restaurant (
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL,
maps_link TEXT
)
");
$db->exec("
CREATE TABLE Bewertung (
id INTEGER PRIMARY KEY AUTOINCREMENT,
fk_user_id INTEGER NOT NULL,
fk_restaurant_id INTEGER NOT NULL,
bewertung INTEGER NOT NULL CHECK (bewertung BETWEEN 0 AND 10),
bewertung_str TEXT,
FOREIGN KEY (fk_user_id) REFERENCES User(id),
FOREIGN KEY (fk_restaurant_id) REFERENCES Restaurant(id)
)
");
echo "<p style='color:green;'>Database structure created.</p>";
// Check if any users exist
$checkUserStmt = $db->query("SELECT COUNT(*) FROM User");
$userCount = $checkUserStmt->fetchColumn();
if ($userCount == 0) {
// Create an initial admin account
$adminVorname = 'Admin';
$adminNachname = 'User';
$adminUsername = 'admin';
$adminPassword = 'admin123'; // IMPORTANT: Change this default password!
$hashedPassword = password_hash($adminPassword, PASSWORD_DEFAULT);
$adminActive = 2; // Let's use 2 to denote an admin user
$insertAdminStmt = $db->prepare("
INSERT INTO User (vorname, nachname, username, password, active)
VALUES (:vorname, :nachname, :username, :password, :active)
");
$insertAdminStmt->bindParam(':vorname', $adminVorname);
$insertAdminStmt->bindParam(':nachname', $adminNachname);
$insertAdminStmt->bindParam(':username', $adminUsername);
$insertAdminStmt->bindParam(':password', $hashedPassword);
$insertAdminStmt->bindParam(':active', $adminActive, PDO::PARAM_INT);
if ($insertAdminStmt->execute()) {
echo "<p style='color:green;'>Initial admin account created: Username='admin', Password='admin123' (Please change immediately!).</p>";
} else {
echo "<p style='color:red;'>Error creating initial admin account: " . print_r($insertAdminStmt->errorInfo(), true) . "</p>";
}
}
} else {
// echo "<p style='color:blue;'>Database already exists.</p>";
}
} catch (PDOException $e) {
die("Database connection failed: " . $e->getMessage());
}
function sanitize_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
?>

View File

@ -0,0 +1,22 @@
<?php
include 'db_connection.php';
$stmt = $db->prepare("SELECT id, name, maps_link FROM Restaurant");
$stmt->execute();
$restaurants = $stmt->fetchAll(PDO::FETCH_ASSOC);
if ($restaurants) {
$output = "<ul>";
foreach ($restaurants as $restaurant) {
$output .= "<li>Name: {$restaurant['name']}";
if ($restaurant['maps_link']) {
$output .= " - <a href='{$restaurant['maps_link']}' target='_blank'>View on Maps</a>";
}
$output .= "</li>";
}
$output .= "</ul>";
echo $output;
} else {
echo "<p>No restaurants available.</p>";
}
?>

View File

@ -0,0 +1,37 @@
<?php
include 'db_connection.php';
// Fetch restaurants and their median scores
$stmt = $db->prepare("
SELECT
r.id,
r.name,
ROUND(MEDIAN(b.bewertung)) AS median_score
FROM Restaurant r
LEFT JOIN Bewertung b ON r.id = b.fk_restaurant_id
GROUP BY r.id, r.name
ORDER BY median_score DESC NULLS LAST
");
$stmt->execute();
$restaurants = $stmt->fetchAll(PDO::FETCH_ASSOC);
$tiers = [];
foreach ($restaurants as $restaurant) {
$score = $restaurant['median_score'];
if ($score >= 9) {
$tiers['S'][] = $restaurant;
} elseif ($score >= 7) {
$tiers['A'][] = $restaurant;
} elseif ($score >= 5) {
$tiers['B'][] = $restaurant;
} elseif ($score >= 3) {
$tiers['C'][] = $restaurant;
} elseif ($score >= 1) {
$tiers['D'][] = $restaurant;
} else {
$tiers['Unrated'][] = $restaurant; // For restaurants with no reviews
}
}
echo json_encode($tiers);
?>

37
php/login.php Normal file
View File

@ -0,0 +1,37 @@
<?php
include 'db_connection.php';
session_start();
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$username = sanitize_input($_POST['username']);
$password = sanitize_input($_POST['password']);
$stmt = $db->prepare("SELECT id, username, password, active FROM User WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($row) {
if ($row['active'] == 1 && password_verify($password, $row['password'])) {
$_SESSION['username'] = $row['username'];
$_SESSION['user_id'] = $row['id'];
// Set cookie
setcookie('loggedIn', 'true', time() + 600, '/'); // Expires in 10 minutes
echo json_encode(['success' => true, 'message' => 'Login successful!']);
exit();
} else if ($row['active'] == 0) {
echo json_encode(['success' => false, 'error' => 'Account is not active. Please wait for admin approval.']);
exit();
} else {
echo json_encode(['success' => false, 'error' => 'Invalid username or password.']);
exit();
}
} else {
echo json_encode(['success' => false, 'error' => 'Invalid username or password.']);
exit();
}
} else {
echo json_encode(['success' => false, 'error' => 'Invalid request method.']);
exit();
}
?>

7
php/logout.php Normal file
View File

@ -0,0 +1,7 @@
<?php
session_start();
session_destroy();
setcookie('loggedIn', '', time() - 3600, '/'); // Clear the cookie
echo json_encode(['success' => true, 'message' => 'Logged out successfully.']);
exit();
?>

View File

@ -0,0 +1,101 @@
<?php
include 'db_connection.php';
session_start();
if (!isset($_SESSION['username'])) {
// header("Location: ../login.php"); // Redirect to login
echo json_encode(['success' => false, 'error' => 'Not logged in.']);
exit();
}
// Check if the user is an admin (you'd likely have an 'admin' column in your User table)
$check_admin_stmt = $db->prepare("SELECT id FROM User WHERE username = :username AND active = 2"); // 2 for admin
$check_admin_stmt->bindParam(':username', $_SESSION['username']);
$check_admin_stmt->execute();
$is_admin = $check_admin_stmt->fetchColumn();
if (!$is_admin) {
echo json_encode(['success' => false, 'error' => 'Unauthorized access.']);
exit();
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if ($_POST['action'] == 'process') {
$user_id = sanitize_input($_POST['user_id']);
$accept = sanitize_input($_POST['accept']);
$update_stmt = $db->prepare("UPDATE User SET active = :active WHERE id = :user_id");
$update_stmt->bindParam(':active', $accept, PDO::PARAM_BOOL);
$update_stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT);
if ($update_stmt->execute()) {
echo json_encode(['success' => true, 'message' => 'User status updated.']);
exit();
} else {
echo json_encode(['success' => false, 'error' => 'Error updating user status: ' . print_r($update_stmt->errorInfo(), true)]);
exit();
}
} else if ($_POST['action'] == 'change_password') {
$old_password = sanitize_input($_POST['old_password']);
$new_password = sanitize_input($_POST['new_password']);
$confirm_new_password = sanitize_input($_POST['confirm_new_password']);
if ($new_password != $confirm_new_password) {
echo json_encode(['success' => false, 'error' => 'New passwords do not match.']);
exit();
}
$user_id = $_SESSION['user_id'];
$get_user_stmt = $db->prepare("SELECT password FROM User WHERE id = :user_id");
$get_user_stmt->bindParam(':user_id', $user_id);
$get_user_stmt->execute();
$row = $get_user_stmt->fetch(PDO::FETCH_ASSOC);
if($row){
if (password_verify($old_password, $row['password'])) {
$hashed_new_password = password_hash($new_password, PASSWORD_DEFAULT);
$update_password_stmt = $db->prepare("UPDATE User SET password = :new_password WHERE id = :user_id");
$update_password_stmt->bindParam(':new_password', $hashed_new_password);
$update_password_stmt->bindParam(':user_id', $user_id);
if ($update_password_stmt->execute()) {
echo json_encode(['success' => true, 'message' => 'Password changed successfully.']);
exit();
} else {
echo json_encode(['success' => false, 'error' => 'Error changing password: ' . print_r($update_password_stmt->errorInfo(), true)]);
exit();
}
} else {
echo json_encode(['success' => false, 'error' => 'Incorrect old password.']);
exit();
}
}
else{
echo json_encode(['success' => false, 'error' => 'User not found.']);
exit();
}
}
} else if ($_SERVER["REQUEST_METHOD"] == "GET" && $_GET['action'] == 'get_requests') {
$get_requests_stmt = $db->prepare("SELECT id, vorname, nachname, username FROM User WHERE active = 0");
$get_requests_stmt->execute();
$requests = $get_requests_stmt->fetchAll(PDO::FETCH_ASSOC);
if ($requests) {
$output = "<ul>";
foreach ($requests as $request) {
$output .= "<li>{$request['vorname']} {$request['nachname']} ({$request['username']}) -
<button class='accept-btn' data-user-id='{$request['id']}'>Accept</button>
<button class='reject-btn' data-user-id='{$request['id']}'>Reject</button>
</li>";
}
$output .= "</ul>";
echo $output;
exit();
} else {
echo "<p>No pending registration requests.</p>";
exit();
}
}else {
echo json_encode(['success' => false, 'error' => 'Invalid request method.']);
exit();
}
?>

35
php/register_request.php Normal file
View File

@ -0,0 +1,35 @@
<?php
include 'db_connection.php';
if ($_SERVER["REQUEST_METHOD"] == "POST") {
$vorname = sanitize_input($_POST['vorname']);
$nachname = sanitize_input($_POST['nachname']);
$username = sanitize_input($_POST['username']);
// Check if the username already exists
$check_stmt = $db->prepare("SELECT username FROM User WHERE username = :username");
$check_stmt->bindParam(':username', $username);
$check_stmt->execute();
if ($check_stmt->fetchColumn()) {
echo json_encode(['success' => false, 'error' => 'Username already exists.']);
exit();
} else {
$insert_stmt = $db->prepare("INSERT INTO User (vorname, nachname, username) VALUES (:vorname, :nachname, :username)");
$insert_stmt->bindParam(':vorname', $vorname);
$insert_stmt->bindParam(':nachname', $nachname);
$insert_stmt->bindParam(':username', $username);
if ($insert_stmt->execute()) {
echo json_encode(['success' => true, 'message' => 'Registration request sent. Please wait for admin approval.']);
exit();
} else {
echo json_encode(['success' => false, 'error' => 'Error: ' . print_r($insert_stmt->errorInfo(), true)]);
exit();
}
}
} else {
echo json_encode(['success' => false, 'error' => 'Invalid request method.']);
exit();
}
?>