false, 'error' => 'Invalid method']); exit; } $input = json_decode(file_get_contents('php://input'), true); if (!$input || empty($input['items'])) { echo json_encode(['success' => false, 'error' => 'Cart is empty']); exit; } $name = trim($input['name'] ?? ''); $phone = trim($input['phone'] ?? ''); $address = trim($input['address'] ?? ''); if ($name === '' || $phone === '' || $address === '') { echo json_encode(['success' => false, 'error' => 'Missing customer details']); exit; } $items = $input['items']; $subtotal = 0; $totalVat = 0; // Recalculate total for security $db = db(); $processedItems = []; foreach ($items as $id => $item) { $qty = (int)$item['qty']; if ($qty <= 0) continue; // get price and vat from DB $stmt = $db->prepare("SELECT sku, name, price, vat FROM items WHERE id = ?"); $stmt->execute([$id]); $dbItem = $stmt->fetch(); if ($dbItem) { $price = (float)$dbItem['price']; $vatPercent = (float)($dbItem['vat'] ?? 0); $lineTotal = $price * $qty; $itemVat = $lineTotal * ($vatPercent / 100); $subtotal += $lineTotal; $totalVat += $itemVat; $processedItems[] = [ 'id' => $id, 'sku' => $dbItem['sku'], 'name' => $dbItem['name'], 'price' => $price, 'vat' => $vatPercent, 'vat_amount' => $itemVat, 'qty' => $qty, 'line_total' => $lineTotal ]; } } if (empty($processedItems)) { echo json_encode(['success' => false, 'error' => 'Invalid items']); exit; } $totalAmount = $subtotal + $totalVat; try { $stmt = $db->prepare("INSERT INTO online_orders (customer_name, customer_phone, customer_address, items_json, subtotal, vat_amount, total_amount) VALUES (?, ?, ?, ?, ?, ?, ?)"); $stmt->execute([ $name, $phone, $address, json_encode($processedItems, JSON_UNESCAPED_UNICODE), $subtotal, $totalVat, $totalAmount ]); // Optional: send telegram notification if configured try { $orderId = $db->lastInsertId(); $msg = "๐Ÿ›’ *New Online Order #{$orderId}*\n\n"; $msg .= "๐Ÿ‘ค {$name}\n๐Ÿ“ž {$phone}\n๐Ÿ“ {$address}\n\n"; $msg .= "๐Ÿ’ฐ Subtotal: " . currency($subtotal) . "\n"; $msg .= "๐Ÿงพ VAT: " . currency($totalVat) . "\n"; $msg .= "๐Ÿ’ต Total: " . currency($totalAmount) . "\n"; $botToken = getenv('TELEGRAM_BOT_TOKEN') ?: get_setting('telegram_bot_token'); $chatId = getenv('TELEGRAM_CHAT_ID') ?: get_setting('telegram_chat_id'); if ($botToken && $chatId) { $url = "https://api.telegram.org/bot{$botToken}/sendMessage"; $data = ['chat_id' => $chatId, 'text' => $msg, 'parse_mode' => 'Markdown']; $options = [ 'http' => [ 'header' => "Content-type: application/x-www-form-urlencoded\r\n", 'method' => 'POST', 'content' => http_build_query($data) ] ]; $context = stream_context_create($options); @file_get_contents($url, false, $context); } } catch (Exception $e) { // ignore notification errors } echo json_encode(['success' => true]); } catch (Exception $e) { echo json_encode(['success' => false, 'error' => 'Database error: ' . $e->getMessage()]); }