Show sourcecode
The following files exists in this folder. Click to view.
webbserverprogrammering/submissions/projekt-matkort-handler/classes/
CardBalance.php
FoodLog.php
Restaurant.php
User.php
FoodLog.php
69 lines UTF-8 Windows (CRLF)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
<?php
Class FoodLogs {
private $conn;
function __construct($conn) {
$this->conn = $conn;
}
// Create food log
function create(
$user_id,
$restaurant_id,
$money_spent,
$healthy_rating,
$happy_rating,
$comment,
$log_date
) {
try {
$sql = "INSERT INTO food_logs (user_id, restaurant_id, money_spent, healthy_rating, happy_rating, comment, log_date) VALUES (?, ?, ?, ?, ?, ?, ?)";
$stmt = $this->conn->prepare($sql);
$success = $stmt->execute([$user_id, $restaurant_id, $money_spent, $healthy_rating, $happy_rating, $comment, $log_date]);
if(!$success) throw new Exception("Misslyckades att spara i databasen.");
require_once 'CardBalance.php';
$cardBalance = new CardBalance($this->conn);
$cardBalance->deduct($user_id, $money_spent);
} catch (Exception $e) {
throw new Exception("Kunde inte skapa matlogg: ".$e->getMessage());
}
}
function getUserLogs($user_id) {
try {
$sql = "SELECT fl.*, r.restaurant_name FROM food_logs fl JOIN restaurants r ON fl.restaurant_id = r.id WHERE fl.user_id = :user_id ORDER BY fl.log_date DESC";
$stmt = $this->conn->prepare($sql);
$stmt->execute(["user_id" => $user_id]);
return $stmt->fetchAll(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
throw new Exception("Kunde inte hämta matloggar:".$e->getMessage());
}
}
function getChartData($user_id) {
try {
// Aggregated daily ratings
$ratingsSql = "SELECT DATE(log_date) as log_date_str, AVG(healthy_rating) as avg_health, AVG(happy_rating) as avg_happy FROM food_logs WHERE user_id = :user_id GROUP BY DATE(log_date) ORDER BY log_date_str ASC";
$stmt = $this->conn->prepare($ratingsSql);
$stmt->execute(["user_id" => $user_id]);
$ratings = $stmt->fetchAll(PDO::FETCH_ASSOC);
// Top visited restaurants
$topSql = "SELECT r.restaurant_name, COUNT(fl.id) as visit_count FROM food_logs fl JOIN restaurants r ON fl.restaurant_id = r.id WHERE fl.user_id = :user_id GROUP BY fl.restaurant_id ORDER BY visit_count DESC LIMIT 5";
$stmt2 = $this->conn->prepare($topSql);
$stmt2->execute(["user_id" => $user_id]);
$top_restaurants = $stmt2->fetchAll(PDO::FETCH_ASSOC);
return ["ratings" => $ratings, "top_restaurants" => $top_restaurants];
} catch (PDOException $e) {
return ["ratings" => [], "top_restaurants" => []];
}
}
}