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()); }