36782-vm/order_process.php
2025-12-12 14:13:03 +00:00

129 lines
4.3 KiB
PHP

<?php
if (session_status() === PHP_SESSION_NONE) {
session_start();
}
require_once 'includes/lang.php';
require_once 'includes/auth.php';
require_login();
require_once 'includes/helpers.php';
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
header('Location: checkout.php');
exit;
}
$cart = $_SESSION['cart'] ?? [];
if (empty($cart)) {
header('Location: index.php');
exit;
}
$pdo = db();
try {
$pdo->beginTransaction();
// 1. Get product details from the database
$product_ids = array_keys($cart);
$placeholders = implode(',', array_fill(0, count($product_ids), '?'));
$stmt = $pdo->prepare("SELECT id, price, units_per_pallet FROM products WHERE id IN ($placeholders)");
$stmt->execute($product_ids);
$products_by_id = $stmt->fetchAll(PDO::FETCH_GROUP|PDO::FETCH_UNIQUE|PDO::FETCH_ASSOC);
// 2. Calculate total amount & total pallets
$total_amount = 0;
$is_supplier_delivery = false;
$client_id = $_SESSION['client_id'] ?? null;
$product_prices = [];
if ($client_id) {
$price_placeholders = implode(',', array_fill(0, count($product_ids), '?'));
$sql = "SELECT p.id, COALESCE(cp.price, p.price) as price FROM products p LEFT JOIN client_prices cp ON p.id = cp.product_id AND cp.client_id = ? WHERE p.id IN ($price_placeholders)";
$stmt = $pdo->prepare($sql);
$params = array_merge([$client_id], $product_ids);
$stmt->execute($params);
$product_prices = $stmt->fetchAll(PDO::FETCH_KEY_PAIR);
}
$is_supplier_delivery = false;
foreach ($cart as $product_id => $quantity) {
if (isset($products_by_id[$product_id])) {
$product = $products_by_id[$product_id];
$price = $product_prices[$product_id] ?? $product['price'];
$total_amount += $price * $quantity;
$units_per_pallet = $product['units_per_pallet'];
if (isset($units_per_pallet) && $units_per_pallet > 0) {
if ($quantity >= $units_per_pallet) {
$is_supplier_delivery = true;
}
}
}
}
$delivery_source = $is_supplier_delivery ? 'supplier' : 'cs';
if ($_POST['payment_method'] === 'credit') {
$stmt = $pdo->prepare('SELECT credit_balance, credit_enabled FROM clients WHERE id = ? FOR UPDATE');
$stmt->execute([$client_id]);
$credit_info = $stmt->fetch();
if (!$credit_info || !$credit_info['credit_enabled'] || $credit_info['credit_balance'] < $total_amount) {
throw new Exception('Invalid payment method or insufficient credit.');
}
$new_balance = $credit_info['credit_balance'] - $total_amount;
$stmt = $pdo->prepare('UPDATE clients SET credit_balance = ? WHERE id = ?');
$stmt->execute([$new_balance, $client_id]);
}
// 3. Create the order
$stmt = $pdo->prepare(
'INSERT INTO orders (client_id, total_amount, payment_method, delivery_source, notes, status) VALUES (?, ?, ?, ?, ?, ?)'
);
$stmt->execute([
$client_id,
$total_amount,
$_POST['payment_method'],
$delivery_source,
$_POST['notes'],
$_POST['payment_method'] === 'credit' ? 'in_progress' : 'pending_payment'
]);
$order_id = $pdo->lastInsertId();
// 4. Insert order items
$stmt = $pdo->prepare(
'INSERT INTO order_items (order_id, product_id, quantity, unit_price, line_total) VALUES (?, ?, ?, ?, ?)'
);
foreach ($cart as $product_id => $quantity) {
if (isset($products_by_id[$product_id])) {
$product = $products_by_id[$product_id];
$price = $product_prices[$product_id] ?? $product['price'];
$stmt->execute([
$order_id,
$product_id,
$quantity,
$price,
$price * $quantity
]);
}
}
// 5. Commit the transaction
$pdo->commit();
// 6. Clear the cart and store order ID in session for the confirmation page
unset($_SESSION['cart']);
$_SESSION['latest_order_id'] = $order_id;
// 7. Redirect to confirmation page
header('Location: order_confirmation.php');
exit;
} catch (PDOException $e) {
$pdo->rollBack();
// In a real application, log this error
die("Błąd podczas przetwarzania zamówienia: " . $e->getMessage());
}