beginTransaction(); // 1. Check if the listing is still 'claimed' $checkSql = "SELECT status FROM food_listings WHERE id = :listing_id FOR UPDATE"; // Lock the row $checkStmt = $pdo->prepare($checkSql); $checkStmt->bindParam(':listing_id', $listing_id, PDO::PARAM_INT); $checkStmt->execute(); $currentStatus = $checkStmt->fetchColumn(); if ($currentStatus === 'claimed') { // 2. Update the listing status to 'assigned' $updateSql = "UPDATE food_listings SET status = 'assigned' WHERE id = :listing_id"; $updateStmt = $pdo->prepare($updateSql); $updateStmt->bindParam(':listing_id', $listing_id, PDO::PARAM_INT); $updateStmt->execute(); // 3. Create the assignment record $assignSql = "INSERT INTO volunteer_assignments (listing_id, volunteer_id) VALUES (:listing_id, :volunteer_id)"; $assignStmt = $pdo->prepare($assignSql); $assignStmt->bindParam(':listing_id', $listing_id, PDO::PARAM_INT); $assignStmt->bindParam(':volunteer_id', $volunteer_id, PDO::PARAM_INT); $assignStmt->execute(); $pdo->commit(); header('Location: volunteer_hub.php?status=assigned'); } else { // The listing was already assigned or is in another state $pdo->rollBack(); header('Location: volunteer_hub.php?status=already_assigned'); } } catch (PDOException $e) { if ($pdo->inTransaction()) { $pdo->rollBack(); } // error_log($e->getMessage()); header('Location: volunteer_hub.php?status=error'); } exit();