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 & Clean Form Data
$firstName = trim($_POST['first_name'] ?? '');
$lastName = trim($_POST['last_name'] ?? '');
$email = trim(strtolower($_POST['email'] ?? ''));
$total = $_POST['final_total'] ?? 0.00;
$method = $_POST['payment_method'] ?? 'Unknown';
$notes = trim($_POST['order_notes'] ?? '');
$currency = $_SESSION['checkout_currency'] ?? '£';
// Retrieve Cart
$cartItems = $_SESSION['checkout_cart'] ?? [];
if (empty($cartItems)) {
die("Error: Your cart is empty.");
}
// Handle Contact Preferences
$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 the message field
$fullNotes = "Order Notes: $notes | Contact via: " . ($contactPreferences ?: 'None');
// 3. Handle File Upload (Payment Proof) securely
// FIX: Use __DIR__ to force the absolute server path for uploading
$absoluteUploadDir = __DIR__ . '/uploads/proofs/';
$relativeDbDir = 'uploads/proofs/';
$proofPath = null;
// Create the directory if it doesn't exist
if (!is_dir($absoluteUploadDir)) {
// Note: If this fails, you have a strict permission issue on the parent folder
mkdir($absoluteUploadDir, 0755, true);
}
if (isset($_FILES['payment_proof']) && $_FILES['payment_proof']['error'] === UPLOAD_ERR_OK) {
$fileTmpPath = $_FILES['payment_proof']['tmp_name'];
$fileName = $_FILES['payment_proof']['name'];
$fileSize = $_FILES['payment_proof']['size'];
// SECURITY: Validate file extension
$allowedExtensions = ['jpg', 'jpeg', 'png', 'pdf'];
$fileExtension = strtolower(pathinfo($fileName, PATHINFO_EXTENSION));
if (!in_array($fileExtension, $allowedExtensions)) {
die("Error: Invalid file format. Only JPG, PNG, and PDF are allowed.");
}
// Sanitize filename and create paths
$cleanFileName = preg_replace('/[^a-zA-Z0-9-_\.]/', '', pathinfo($fileName, PATHINFO_FILENAME));
$newFileName = time() . '_' . $cleanFileName . '.' . $fileExtension;
$dest_path = $absoluteUploadDir . $newFileName; // Used for moving the file
$db_path = $relativeDbDir . $newFileName; // Used for saving to the DB
// FIX: Catch the exact system error if it fails
if (move_uploaded_file($fileTmpPath, $dest_path)) {
$proofPath = $db_path;
} else {
$error = error_get_last();
$sysMessage = $error ? $error['message'] : 'Unknown file permission or path error';
die("Error: Failed to save the uploaded file. System says: " . $sysMessage);
}
}
// 4. Process Database Transaction
try {
$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
$dummyPass = password_hash('Guest@' . bin2hex(random_bytes(4)), 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
$txnRef = 'GRB-' . strtoupper(substr(md5(uniqid()), 0, 8));
$fullName = $firstName . ' ' . $lastName;
$finalMessage = $fullNotes . " | Proof File: " . ($proofPath ? $proofPath : 'None');
$stmt = $pdo->prepare("INSERT INTO donations
(user_id, total_amount, currency, payment_method, transaction_ref, payment_status, donor_email, donor_name, message)
VALUES (?, ?, ?, ?, ?, 'pending', ?, ?, ?)");
$stmt->execute([$userId, $total, $currency, $method, $txnRef, $email, $fullName, $finalMessage]);
$donationId = $pdo->lastInsertId();
// C. Insert Cart Items (With Frequency Fix)
$stmtItem = $pdo->prepare("INSERT INTO donation_items (donation_id, campaign_id, amount, frequency) VALUES (?, ?, ?, ?)");
$stmtFindId = $pdo->prepare("SELECT campaign_id FROM campaigns WHERE title = ? LIMIT 1");
foreach ($cartItems as $item) {
// 1. Find Campaign ID
$stmtFindId->execute([$item['cause'] ?? '']);
$row = $stmtFindId->fetch();
$campaignId = $row ? $row['campaign_id'] : 1;
// 2. Sanitize and map the frequency
$rawFreq = trim(strtolower($item['freq'] ?? 'one-off'));
$dbFrequency = match($rawFreq) {
'monthly' => 'Monthly',
'yearly', 'annually' => 'Yearly',
'weekly' => 'Weekly',
default => 'One-Off'
};
// 3. Insert Item
$stmtItem->execute([
$donationId,
$campaignId,
$item['amt'] ?? 0.00,
$dbFrequency
]);
}
// 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: " . htmlspecialchars($e->getMessage()));
}
?>
b IDATxytVսϓ22 A@IR:hCiZ[v*E:WũZA ^dQeQ @ !jZ'>gsV仿$|?g)&x-E