37650-vm/purchase_process.php
Flatlogic Bot 73e14b3353 sad
2026-01-21 17:27:41 +00:00

57 lines
1.6 KiB
PHP

<?php
session_start();
require_once __DIR__ . '/db/config.php';
if ($_SERVER['REQUEST_METHOD'] !== 'POST' || !isset($_SESSION['user_id'])) {
header("Location: car_list.php");
exit();
}
$pdo = db();
$carId = $_POST['car_id'] ?? 0;
$province = $_POST['province'] ?? '';
$account = $_POST['account_number'] ?? '';
$userId = $_SESSION['user_id'];
if (empty($carId) || empty($province) || empty($account)) {
die("Invalid input.");
}
// Check if car is available
$stmt = $pdo->prepare("SELECT price, status FROM cars WHERE id = ?");
$stmt->execute([$carId]);
$car = $stmt->fetch();
if (!$car || $car['status'] !== 'approved') {
die("Error: This car is no longer available for purchase.");
}
try {
$pdo->beginTransaction();
// 1. Mark car as sold
// We check status again in WHERE clause to prevent race conditions
$stmt = $pdo->prepare("UPDATE cars SET status = 'sold' WHERE id = ? AND status = 'approved'");
$stmt->execute([$carId]);
if ($stmt->rowCount() === 0) {
throw new Exception("Car was just sold to someone else.");
}
// 2. Create Booking/Sale Record
$stmt = $pdo->prepare("INSERT INTO bookings (user_id, car_id, status, booking_date, bank_province, bank_account_number, sale_price) VALUES (?, ?, 'approved', NOW(), ?, ?, ?)");
$stmt->execute([$userId, $carId, $province, $account, $car['price']]);
$bookingId = $pdo->lastInsertId();
$pdo->commit();
header("Location: receipt.php?id=" . $bookingId);
exit();
} catch (Exception $e) {
if ($pdo->inTransaction()) {
$pdo->rollBack();
}
die("Purchase failed: " . $e->getMessage());
}