<?php
session_start();
require_once 'db/config.php';

// Check if the user is logged in
if (!isset($_SESSION['user_id'])) {
    // Redirect to login page if not logged in
    header('Location: login.php');
    exit;
}

// Check if the request method is POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // Get the restaurant ID from the POST data
    $restaurant_id = isset($_POST['restaurant_id']) ? (int)$_POST['restaurant_id'] : 0;
    $user_id = $_SESSION['user_id'];

    if ($restaurant_id > 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;
}
