0) { try { $db = db(); // Check if the restaurant is already a favorite $stmt = $db->prepare("SELECT COUNT(*) FROM favorite_restaurants WHERE user_id = :user_id AND restaurant_id = :restaurant_id"); $stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT); $stmt->bindParam(':restaurant_id', $restaurant_id, PDO::PARAM_INT); $stmt->execute(); $is_favorite = $stmt->fetchColumn() > 0; if ($is_favorite) { // Remove from favorites $delete_stmt = $db->prepare("DELETE FROM favorite_restaurants WHERE user_id = :user_id AND restaurant_id = :restaurant_id"); $delete_stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT); $delete_stmt->bindParam(':restaurant_id', $restaurant_id, PDO::PARAM_INT); $delete_stmt->execute(); $_SESSION['alert'] = ['type' => 'success', 'message' => 'Restaurant removed from your favorites.']; } else { // Add to favorites $insert_stmt = $db->prepare("INSERT INTO favorite_restaurants (user_id, restaurant_id) VALUES (:user_id, :restaurant_id)"); $insert_stmt->bindParam(':user_id', $user_id, PDO::PARAM_INT); $insert_stmt->bindParam(':restaurant_id', $restaurant_id, PDO::PARAM_INT); $insert_stmt->execute(); $_SESSION['alert'] = ['type' => 'success', 'message' => 'Restaurant added to your favorites!']; } } catch (PDOException $e) { // Handle database errors $_SESSION['alert'] = ['type' => 'danger', 'message' => 'Database error: ' . $e->getMessage()]; } } // Redirect back to the menu page header('Location: menu.php?restaurant_id=' . $restaurant_id); exit; } else { // If not a POST request, redirect to the homepage header('Location: index.php'); exit; }