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

$customer = $_POST['customer_name'] ?? 'Walk-in';
$table_id = !empty($_POST['table_id']) ? intval($_POST['table_id']) : null;
$order_mode = $_POST['order_mode'] ?? null;
$cart_json = $_POST['cart_json'] ?? '[]';
$cart = json_decode($cart_json, true);

// 💵 Calculate total
$total_amount = 0;
foreach ($cart as $item) {
    $total_amount += $item['price'] * $item['qty'];
}

$hold_id = null;
if ($order_mode === 'dine_in' && $table_id) {
    $check = $conn->query("SELECT id FROM hold_orders WHERE table_id = $table_id LIMIT 1");
    if ($check && $check->num_rows > 0) {
        $row = $check->fetch_assoc();
        $hold_id = $row['id'];

        $stmt = $conn->prepare("UPDATE hold_orders SET customer_name = ?, order_mode = ?, total_amount = total_amount + ? WHERE id = ?");
        $stmt->bind_param("ssdi", $customer, $order_mode, $total_amount, $hold_id);
        $stmt->execute();
        $stmt->close();
    }
}

if (!$hold_id) {
    $stmt = $conn->prepare("INSERT INTO hold_orders (customer_name, table_id, order_mode, total_amount) VALUES (?, ?, ?, ?)");
    $stmt->bind_param("sisd", $customer, $table_id, $order_mode, $total_amount);
    $stmt->execute();
    $hold_id = $stmt->insert_id;
    $stmt->close();
}

// 🔍 Get existing items
$existing_items = [];
$res = $conn->query("SELECT item_id FROM hold_items WHERE hold_id = $hold_id");
while ($row = $res->fetch_assoc()) {
    $existing_items[$row['item_id']] = true;
}

$newly_added_ids = [];

foreach ($cart as $item) {
    $item_id = intval($item['id']);
    $name = $item['name'];
    $qty = intval($item['qty']);
    $price = floatval($item['price']);
    $tax_rate = floatval($item['tax_rate']);

    if (isset($existing_items[$item_id])) {
        $conn->query("UPDATE hold_items SET quantity = quantity + $qty WHERE hold_id = $hold_id AND item_id = $item_id");
    } else {
        $item_stmt = $conn->prepare("INSERT INTO hold_items (hold_id, item_id, item_name, quantity, unit_price, tax_rate) VALUES (?, ?, ?, ?, ?, ?)");
        $item_stmt->bind_param("iisidd", $hold_id, $item_id, $name, $qty, $price, $tax_rate);
        $item_stmt->execute();
        $item_stmt->close();

        $newly_added_ids[] = $item_id;
    }
}

// ⚙️ KOT setting
$setting_res = $conn->query("SELECT value FROM settings WHERE code = 'print_kot' AND is_active = 1 LIMIT 1");
$should_print_kot = $setting_res && $setting_res->fetch_assoc()['value'] === '1';

echo json_encode([
    'status' => 'success',
    'hold_id' => $hold_id,
    'print_kot' => $should_print_kot,
    'new_items' => $newly_added_ids // 🔄 Only print these
]);
