39728-vm/api/place_order.php
2026-04-19 16:03:44 +00:00

98 lines
3.2 KiB
PHP

<?php
require_once __DIR__ . '/../includes/app.php';
header('Content-Type: application/json; charset=utf-8');
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
echo json_encode(['success' => 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'];
$total = 0;
// Recalculate total for security
$db = db();
$processedItems = [];
foreach ($items as $id => $item) {
$qty = (int)$item['qty'];
if ($qty <= 0) continue;
// get price from DB
$stmt = $db->prepare("SELECT sku, name, price FROM items WHERE id = ?");
$stmt->execute([$id]);
$dbItem = $stmt->fetch();
if ($dbItem) {
$price = (float)$dbItem['price'];
$total += ($price * $qty);
$processedItems[] = [
'id' => $id,
'sku' => $dbItem['sku'],
'name' => $dbItem['name'],
'price' => $price,
'qty' => $qty
];
}
}
if (empty($processedItems)) {
echo json_encode(['success' => false, 'error' => 'Invalid items']);
exit;
}
try {
$stmt = $db->prepare("INSERT INTO online_orders (customer_name, customer_phone, customer_address, items_json, total_amount) VALUES (?, ?, ?, ?, ?)");
$stmt->execute([
$name,
$phone,
$address,
json_encode($processedItems, JSON_UNESCAPED_UNICODE),
$total
]);
// Optional: send telegram notification if configured
try {
// require_once __DIR__ . '/telegram_webhook.php'; // wait, it might not be a function but a script. Let's just do simple notification
$orderId = $db->lastInsertId();
$msg = "🛒 *New Online Order #{$orderId}*\n\n";
$msg .= "👤 {$name}\n📞 {$phone}\n📍 {$address}\n\n";
$msg .= "💰 Total: " . currency($total) . "\n";
// To send, we'd need to call telegram api directly if token is set.
$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']);
}