Show sourcecode
The following files exists in this folder. Click to view.
webbserverprogrammering/submissions/projekt-matkort-handler/api/
restaurant_ajax.php
57 lines ASCII Windows (CRLF)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
<?php
session_start();
include_once '../config/database.php';
include_once '../classes/Restaurant.php';
header('Content-Type: application/json');
if (!isset($_GET['action'])) {
echo json_encode(['error' => 'No action specified']);
exit;
}
$action = $_GET['action'];
$restaurantModel = new Restaurant($pdo);
$user_id = isset($_SESSION['user_id']) ? $_SESSION['user_id'] : null;
if ($action === 'get_stats') {
if (!isset($_GET['restaurant_id'])) {
echo json_encode(['error' => 'Missing restaurant_id']);
exit;
}
$restaurant_id = (int)$_GET['restaurant_id'];
$stats = $restaurantModel->getStatsAndFavorite($restaurant_id, $user_id);
echo json_encode($stats);
exit;
}
if ($action === 'toggle_favorite') {
if (!$user_id) {
echo json_encode(['error' => 'Must be logged in to favorite']);
exit;
}
// Assume POST for state changes
$data = json_decode(file_get_contents('php://input'), true);
if (!isset($data['restaurant_id'])) {
echo json_encode(['error' => 'Missing restaurant_id']);
exit;
}
$result = $restaurantModel->toggleFavorite($user_id, (int)$data['restaurant_id']);
echo json_encode($result);
exit;
}
if ($action === 'get_favorites') {
if (!$user_id) {
echo json_encode([]); // return empty if not logged in
exit;
}
$favs = $restaurantModel->getUserFavorites($user_id);
echo json_encode($favs);
exit;
}
echo json_encode(['error' => 'Invalid action']);