52 lines
2.0 KiB
PHP
52 lines
2.0 KiB
PHP
<?php
|
|
session_start();
|
|
require_once 'db/config.php';
|
|
|
|
// Check if user is logged in, if not, redirect to login page
|
|
if (!isset($_SESSION['user_id'])) {
|
|
// For now, we'll use a hardcoded user_id for simplicity.
|
|
// In a real application, you would redirect to a login page.
|
|
$_SESSION['user_id'] = 1; // Hardcoded user_id for demonstration
|
|
}
|
|
|
|
$user_id = $_SESSION['user_id'];
|
|
$action = $_POST['action'] ?? '';
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
|
if ($action === 'add') {
|
|
$menu_item_id = $_POST['menu_item_id'] ?? null;
|
|
$quantity = $_POST['quantity'] ?? 1;
|
|
|
|
if ($menu_item_id) {
|
|
try {
|
|
$pdo = db();
|
|
|
|
// Check if the item is already in the cart
|
|
$stmt = $pdo->prepare("SELECT * FROM cart WHERE user_id = ? AND menu_item_id = ?");
|
|
$stmt->execute([$user_id, $menu_item_id]);
|
|
$existing_item = $stmt->fetch();
|
|
|
|
if ($existing_item) {
|
|
// If item exists, update the quantity
|
|
$new_quantity = $existing_item['quantity'] + $quantity;
|
|
$update_stmt = $pdo->prepare("UPDATE cart SET quantity = ? WHERE id = ?");
|
|
$update_stmt->execute([$new_quantity, $existing_item['id']]);
|
|
} else {
|
|
// If item does not exist, insert it
|
|
$insert_stmt = $pdo->prepare("INSERT INTO cart (user_id, menu_item_id, quantity) VALUES (?, ?, ?)");
|
|
$insert_stmt->execute([$user_id, $menu_item_id, $quantity]);
|
|
}
|
|
|
|
echo json_encode(['success' => true, 'message' => 'Item added to cart.']);
|
|
|
|
} catch (PDOException $e) {
|
|
http_response_code(500);
|
|
echo json_encode(['success' => false, 'message' => 'Database error: ' . $e->getMessage()]);
|
|
}
|
|
} else {
|
|
http_response_code(400);
|
|
echo json_encode(['success' => false, 'message' => 'Menu item ID is required.']);
|
|
}
|
|
}
|
|
}
|
|
?>
|