<?php
require_once "../../includes/islogin.php";
require_once "../../includes/db_connect.php";

$user_id = $_SESSION['user_id'];
$food_ids = $_POST['food_id'] ?? [];
$quantities = $_POST['food_quantity'] ?? [];
$prices = $_POST['food_price'] ?? [];
$special_request = trim($_POST['special_request'] ?? '');

if (count($food_ids) === 0) {
    echo "장바구니가 비어 있습니다.";
    exit;
}

// 음식 하나로 식당 ID 추출
$sql = "SELECT restaurant_id FROM Foods WHERE food_id = ? LIMIT 1";
$stmt = $conn->prepare($sql);
$stmt->bind_param("i", $food_ids[0]);
$stmt->execute();
$result = $stmt->get_result();
$row = $result->fetch_assoc();
$restaurant_id = $row['restaurant_id'] ?? 1;

// 총 가격 계산
$total_price = 0;
foreach ($quantities as $i => $qty) {
    $total_price += $prices[$i] * $qty;
}

// 1. Orders 테이블에 주문 추가
$order_sql = "INSERT INTO Orders (user_id, restaurant_id, order_time, total_price, special_request)
              VALUES (?, ?, NOW(), ?, ?)";
$order_stmt = $conn->prepare($order_sql);
$order_stmt->bind_param("iiis", $user_id, $restaurant_id, $total_price, $special_request);
$order_stmt->execute();
$order_id = $conn->insert_id;

// 2. OrderItems 테이블에 항목 추가
$order_item_sql = "INSERT INTO OrderItems (order_id, food_id, quantity, price) VALUES (?, ?, ?, ?)";
$item_stmt = $conn->prepare($order_item_sql);

foreach ($food_ids as $i => $food_id) {
    $qty = $quantities[$i];
    $price = $prices[$i];
    $item_stmt->bind_param("iiii", $order_id, $food_id, $qty, $price);
    $item_stmt->execute();
}

// 3. 장바구니 비우기
$delete_sql = "DELETE FROM Cart WHERE user_id = ?";
$delete_stmt = $conn->prepare($delete_sql);
$delete_stmt->bind_param("i", $user_id);
$delete_stmt->execute();

// 4. 완료 후 이동
header("Location: orderlist.php"); // 주문 내역 페이지로 이동
exit;
?>
