<?php
require '../includes/db_connect.php';
require '../includes/islogin.php';
header('Content-Type: application/json');

$user_id = $_SESSION['user_id'] ?? null;
$food_id = $_POST['food_id'] ?? null;
$action = $_POST['action'] ?? null;

if (!$user_id || !$food_id || !in_array($action, ['increase', 'decrease'])) {
  echo json_encode(['success' => false, 'message' => '잘못된 요청']);
  exit;
}

// 수량 변경
if ($action === 'increase') {
  $sql = "UPDATE Cart SET quantity = quantity + 1 WHERE user_id = ? AND food_id = ?";
} else {
  $sql = "UPDATE Cart SET quantity = quantity - 1 WHERE user_id = ? AND food_id = ? AND quantity > 1";
}
$stmt = $conn->prepare($sql);
$stmt->bind_param("ii", $user_id, $food_id);
$stmt->execute();

// 현재 수량 가져오기
$check_sql = "SELECT quantity FROM Cart WHERE user_id = ? AND food_id = ?";
$check_stmt = $conn->prepare($check_sql);
$check_stmt->bind_param("ii", $user_id, $food_id);
$check_stmt->execute();
$result = $check_stmt->get_result();
$row = $result->fetch_assoc();
$current_quantity = $row['quantity'] ?? 0;

// 총액 재계산
$total_sql = "SELECT SUM(f.price * c.quantity) AS total_price
              FROM Cart c
              JOIN Foods f ON c.food_id = f.food_id
              WHERE c.user_id = ?";
$total_stmt = $conn->prepare($total_sql);
$total_stmt->bind_param("i", $user_id);
$total_stmt->execute();
$total_result = $total_stmt->get_result();
$total_price = $total_result->fetch_assoc()['total_price'] ?? 0;

// 응답
echo json_encode([
  'success' => true,
  'quantity' => (int)$current_quantity,
  'total_price' => (int)$total_price
]);
