<?php
header('Content-Type: application/json');
require_once 'config.php';

$customer_id = $_POST['customer_id'] ?? '';
$name = $_POST['name'] ?? '';
$phone = $_POST['phone'] ?? '';
$address = $_POST['address'] ?? '';
$total = $_POST['total'] ?? '0';
$items_json = $_POST['items'] ?? '';

if (!$customer_id || !$name || !$phone || !$address || !$items_json) {
    echo json_encode(['success' => false, 'message' => 'Missing required fields']);
    exit;
}

$items = json_decode($items_json, true);
if (!is_array($items) || count($items) == 0) {
    echo json_encode(['success' => false, 'message' => 'No items in order']);
    exit;
}

// Insert order
$stmt = $conn->prepare("INSERT INTO orders (customer_id, name, phone, address, total_amount, created_at) VALUES (?, ?, ?, ?, ?, NOW())");
$stmt->bind_param("ssssd", $customer_id, $name, $phone, $address, $total);
if (!$stmt->execute()) {
    echo json_encode(['success' => false, 'message' => 'Failed to place order']);
    exit;
}
$order_id = $stmt->insert_id;
$stmt->close();

// Insert order items
$item_stmt = $conn->prepare("INSERT INTO order_items (order_id, menu_item_id, name, price, quantity) VALUES (?, ?, ?, ?, ?)");
foreach ($items as $item) {
    $menu_item_id = $item['id'] ?? 0;
    $item_name = $item['name'] ?? '';
    $price = $item['price'] ?? 0;
    $quantity = $item['quantity'] ?? 1;
    $item_stmt->bind_param("iisdi", $order_id, $menu_item_id, $item_name, $price, $quantity);
    $item_stmt->execute();
}
$item_stmt->close();

echo json_encode(['success' => true, 'message' => 'Order placed successfully']);
