35607-vm/_handle_checkout.php
Flatlogic Bot 9b5a06451f SInarKasih
2025-11-10 04:11:47 +00:00

68 lines
1.9 KiB
PHP

<?php
require_once __DIR__ . '/db/config.php';
header('Content-Type: application/json');
$response = ['success' => false, 'message' => 'An unknown error occurred.'];
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
http_response_code(405);
$response['message'] = 'Invalid request method.';
echo json_encode($response);
exit;
}
$data = json_decode(file_get_contents('php://input'), true);
$cart = $data['cart'] ?? [];
$paymentMethod = $data['payment_method'] ?? 'Cash';
if (empty($cart)) {
http_response_code(400);
$response['message'] = 'Cart is empty.';
echo json_encode($response);
exit;
}
$pdo = db();
try {
$pdo->beginTransaction();
$totalAmount = 0;
foreach ($cart as $item) {
$totalAmount += $item['price'] * $item['quantity'];
}
$transactionId = 'TXN-' . strtoupper(uniqid());
$stmt = $pdo->prepare("INSERT INTO sales (transaction_id, total_amount, payment_method) VALUES (?, ?, ?)");
$stmt->execute([$transactionId, $totalAmount, $paymentMethod]);
$saleId = $pdo->lastInsertId();
$itemStmt = $pdo->prepare("INSERT INTO sale_items (sale_id, product_id, quantity, price) VALUES (?, ?, ?, ?)");
$stockStmt = $pdo->prepare("UPDATE products SET stock = stock - ? WHERE id = ?");
foreach ($cart as $item) {
$productId = $item['id'];
$quantity = $item['quantity'];
$price = $item['price'];
$itemStmt->execute([$saleId, $productId, $quantity, $price]);
$stockStmt->execute([$quantity, $productId]);
}
$pdo->commit();
$response['success'] = true;
$response['message'] = 'Checkout successful!';
$response['transaction_id'] = $transactionId;
http_response_code(200);
} catch (Exception $e) {
if ($pdo->inTransaction()) {
$pdo->rollBack();
}
http_response_code(500);
$response['message'] = 'Checkout failed: ' . $e->getMessage();
}
echo json_encode($response);