66 lines
2.2 KiB
PHP
66 lines
2.2 KiB
PHP
<?php
|
|
declare(strict_types=1);
|
|
@ini_set('display_errors', '1');
|
|
@error_reporting(E_ALL);
|
|
@date_default_timezone_set('UTC');
|
|
|
|
header('Content-Type: application/json');
|
|
|
|
require_once 'db/config.php';
|
|
|
|
$response = [];
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
|
$sale_data = json_decode(file_get_contents('php://input'), true);
|
|
$cart_data = $sale_data['cart'];
|
|
$customer_id = !empty($sale_data['customer_id']) ? (int)$sale_data['customer_id'] : null;
|
|
|
|
if (empty($cart_data)) {
|
|
$response = ['success' => false, 'message' => 'Cart is empty.'];
|
|
echo json_encode($response);
|
|
exit;
|
|
}
|
|
|
|
$pdo = db();
|
|
$pdo->beginTransaction();
|
|
|
|
try {
|
|
// 1. Calculate total amount
|
|
$total_amount = 0;
|
|
foreach ($cart_data as $item) {
|
|
$total_amount += $item['sale_price'] * $item['quantity'];
|
|
}
|
|
|
|
// 2. Insert into sales table
|
|
$sql = "INSERT INTO sales (customer_id, total_amount, payable_amount) VALUES (?, ?, ?)";
|
|
$stmt = $pdo->prepare($sql);
|
|
$stmt->execute([$customer_id, $total_amount, $total_amount]);
|
|
$sale_id = $pdo->lastInsertId();
|
|
|
|
// 3. Insert into sale_items and update stock
|
|
$sql_item = "INSERT INTO sale_items (sale_id, product_id, quantity, price_per_unit, total_price) VALUES (?, ?, ?, ?, ?)";
|
|
$stmt_item = $pdo->prepare($sql_item);
|
|
|
|
$sql_stock = "UPDATE products SET stock_quantity = stock_quantity - ? WHERE id = ?";
|
|
$stmt_stock = $pdo->prepare($sql_stock);
|
|
|
|
foreach ($cart_data as $item) {
|
|
$item_total = $item['sale_price'] * $item['quantity'];
|
|
$stmt_item->execute([$sale_id, $item['id'], $item['quantity'], $item['sale_price'], $item_total]);
|
|
$stmt_stock->execute([$item['quantity'], $item['id']]);
|
|
}
|
|
|
|
$pdo->commit();
|
|
$response = ['success' => true, 'message' => 'Sale processed successfully!', 'sale_id' => $sale_id];
|
|
|
|
} catch (PDOException $e) {
|
|
$pdo->rollBack();
|
|
$response = ['success' => false, 'message' => 'Error processing sale: ' . $e->getMessage()];
|
|
}
|
|
|
|
} else {
|
|
$response = ['success' => false, 'message' => 'Invalid request method.'];
|
|
}
|
|
|
|
echo json_encode($response);
|