<?php
// api-save-order.php
require_once __DIR__ . '/config.php';

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    jsonResponse(['status' => 'error', 'message' => 'POST only'], 405);
}

$input = json_decode(file_get_contents('php://input'), true);
$db = getDB();

// Ambil order_number harian
$today = date('Y-m-d');
$stmt = $db->prepare("SELECT order_number FROM orders WHERE DATE(created_at) = ? ORDER BY order_number DESC LIMIT 1");
$stmt->execute([$today]);
$lastOrder = $stmt->fetch();
$nextNumber = $lastOrder ? (int)$lastOrder['order_number'] + 1 : 1;

$db->beginTransaction();
try {
    $stmt = $db->prepare('
        INSERT INTO orders (order_number, order_type, table_number, payment_method, nama_kasir, outlet_id, sub_total, discount, tax, service_charge, total, payment_amount, transaction_time)
        VALUES (?,?,?,?,?,?,?,?,?,?,?,?,?)
    ');
    $stmt->execute([
        $nextNumber,
        $input['orderType'] ?? 'Dine In',
        $input['tableNumber'] ?? null,
        $input['paymentMethod'] ?? 'Cash',
        $input['namaKasir'] ?? 'Admin',
        empty($input['outletId']) ? null : (int)$input['outletId'],
        (int)($input['subTotal'] ?? 0),
        (int)($input['discount'] ?? 0),
        (int)($input['tax'] ?? 0),
        (int)($input['serviceCharge'] ?? 0),
        (float)($input['total'] ?? 0),
        (float)($input['paymentAmount'] ?? 0),
        $input['transactionTime'] ?? null,
    ]);
    $orderId = (int)$db->lastInsertId();

    // Insert order items
    $items = $input['items'] ?? [];
    $stmtItem = $db->prepare('INSERT INTO order_items (order_id, product_id, product_name, price, quantity, sub_total) VALUES (?,?,?,?,?,?)');
    foreach ($items as $item) {
        $price = (int)($item['price'] ?? 0);
        $qty = (int)($item['quantity'] ?? 1);
        $stmtItem->execute([
            $orderId,
            (int)($item['productId'] ?? 0),
            $item['productName'] ?? '',
            $price,
            $qty,
            $price * $qty,
        ]);
        // Kurangi stok
        if (!empty($item['productId'])) {
            $db->prepare('UPDATE products SET stock = stock - ? WHERE id = ? AND stock >= ?')->execute([$qty, (int)$item['productId'], $qty]);
        }
    }

    $db->commit();
    jsonResponse(['status' => 'success', 'order_id' => $orderId, 'order_number' => $nextNumber]);
} catch (Exception $e) {
    $db->rollBack();
    jsonResponse(['status' => 'error', 'message' => $e->getMessage()], 500);
}
