PNG IHDR x sBIT|d pHYs + tEXtSoftware www.inkscape.org< ,tEXtComment
<?php
session_start();
require 'db.php'; // Connect to the database
// 1. Redirect if accessed directly without submitting the form
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
header('Location: index.php');
exit;
}
// 2. Retrieve Form Data
$firstName = trim($_POST['first_name'] ?? '');
$lastName = trim($_POST['last_name'] ?? '');
$email = trim($_POST['email'] ?? '');
$total = $_POST['final_total'] ?? 0.00;
$method = $_POST['payment_method'] ?? 'Unknown';
$notes = trim($_POST['order_notes'] ?? '');
$currency = $_SESSION['checkout_currency'] ?? '£';
// Handle Contact Preferences (Combine checkboxes into a string)
$prefs = [];
if (isset($_POST['pref_email'])) $prefs[] = 'Email';
if (isset($_POST['pref_phone'])) $prefs[] = 'Phone';
if (isset($_POST['pref_post'])) $prefs[] = 'Post';
if (isset($_POST['pref_sms'])) $prefs[] = 'SMS';
$contactPreferences = implode(', ', $prefs);
// Combine Notes and Prefs for storage
$fullNotes = "Order Notes: $notes | Contact via: $contactPreferences";
// Retrieve Cart
$cartItems = $_SESSION['checkout_cart'] ?? [];
if (empty($cartItems)) {
die("Error: Your cart is empty.");
}
// 3. Handle File Upload (Payment Proof)
$uploadDir = 'uploads/proofs/';
$proofPath = null;
// Create folder if it doesn't exist
if (!is_dir($uploadDir)) {
mkdir($uploadDir, 0777, true);
}
if (isset($_FILES['payment_proof']) && $_FILES['payment_proof']['error'] === UPLOAD_ERR_OK) {
$fileTmpPath = $_FILES['payment_proof']['tmp_name'];
$fileName = $_FILES['payment_proof']['name'];
// Sanitize filename and create unique path
$newFileName = time() . '_' . preg_replace('/[^a-zA-Z0-9-_\.]/', '', $fileName);
$dest_path = $uploadDir . $newFileName;
if(move_uploaded_file($fileTmpPath, $dest_path)) {
$proofPath = $dest_path;
}
}
try {
// START TRANSACTION
$pdo->beginTransaction();
// A. Check if User exists, otherwise create new
$stmt = $pdo->prepare("SELECT user_id FROM users WHERE email = ?");
$stmt->execute([$email]);
$user = $stmt->fetch();
if ($user) {
$userId = $user['user_id'];
} else {
// Create new user (using dummy password for guest checkout)
$dummyPass = password_hash('Guest@1234', PASSWORD_DEFAULT);
$stmt = $pdo->prepare("INSERT INTO users (first_name, last_name, email, password_hash) VALUES (?, ?, ?, ?)");
$stmt->execute([$firstName, $lastName, $email, $dummyPass]);
$userId = $pdo->lastInsertId();
}
// B. Create Donation Record
// Generates a unique Transaction ID (e.g., GRB-65A12B...)
$txnRef = 'GRB-' . strtoupper(substr(md5(uniqid()), 0, 8));
$stmt = $pdo->prepare("INSERT INTO donations
(user_id, total_amount, currency, payment_method, transaction_ref, payment_status, donor_email, donor_name, message)
VALUES (?, ?, ?, ?, ?, 'pending', ?, ?, ?)");
$fullName = $firstName . ' ' . $lastName;
// Combine notes and proof path into the message field
$finalMessage = $fullNotes . " | Proof File: " . ($proofPath ? $proofPath : 'None');
$stmt->execute([$userId, $total, $currency, $method, $txnRef, $email, $fullName, $finalMessage]);
$donationId = $pdo->lastInsertId();
// ---------------------------------------------------------
// C. Insert Cart Items (FIXED SECTION)
// ---------------------------------------------------------
$stmtItem = $pdo->prepare("INSERT INTO donation_items (donation_id, campaign_id, amount, frequency) VALUES (?, ?, ?, ?)");
// Logic to look up the correct Campaign ID based on the title
$stmtFindId = $pdo->prepare("SELECT campaign_id FROM campaigns WHERE title = ? LIMIT 1");
foreach ($cartItems as $item) {
$causeName = $item['cause'];
// Find ID
$stmtFindId->execute([$causeName]);
$row = $stmtFindId->fetch();
if ($row) {
$campaignId = $row['campaign_id'];
} else {
// Fallback to ID 1 (General Fund) if the specific cause isn't found
$campaignId = 1;
}
$stmtItem->execute([
$donationId,
$campaignId,
$item['amt'],
strtolower($item['freq'])
]);
}
// COMMIT CHANGES
$pdo->commit();
// D. Clean up Session
unset($_SESSION['checkout_cart']);
unset($_SESSION['checkout_currency']);
// E. Redirect to Success Page
header("Location: success.php?tid=" . $txnRef);
exit;
} catch (Exception $e) {
$pdo->rollBack();
die("Transaction Failed: " . $e->getMessage());
}
?>
b IDATxytVսϓ22 A@IR:hCiZ[v*E:WũZA ^dQeQ @ !jZ'>gsV仿$|?g)&x-E