77 lines
2.8 KiB
PHP
77 lines
2.8 KiB
PHP
<?php
|
|
session_start();
|
|
require_once 'db/config.php';
|
|
|
|
if (!isset($_SESSION['user_id'])) {
|
|
header('Location: login.php');
|
|
exit;
|
|
}
|
|
|
|
// For demonstration, we'll ensure a merchant user exists.
|
|
// In a real app, merchants would register separately.
|
|
$merchant_email = 'merchant@ubpay.com';
|
|
$stmt = $pdo->prepare('SELECT id FROM users WHERE email = ?');
|
|
$stmt->execute([$merchant_email]);
|
|
$merchant = $stmt->fetch();
|
|
|
|
if (!$merchant) {
|
|
$stmt = $pdo->prepare('INSERT INTO users (name, email, password, balance) VALUES (?, ?, ?, ?)');
|
|
$stmt->execute(['Default Merchant', $merchant_email, password_hash('password', PASSWORD_DEFAULT), 10000]);
|
|
$merchant_id = $pdo->lastInsertId();
|
|
} else {
|
|
$merchant_id = $merchant['id'];
|
|
}
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
|
$user_id = $_SESSION['user_id'];
|
|
$merchant_code = $_POST['merchant_code']; // In a real app, this would be validated more thoroughly
|
|
$amount = filter_input(INPUT_POST, 'amount', FILTER_VALIDATE_FLOAT);
|
|
|
|
if (!$merchant_code || !$amount || $amount <= 0) {
|
|
$_SESSION['error_message'] = 'Invalid input. Please check the merchant code and amount.';
|
|
header('Location: pay-merchant.php');
|
|
exit;
|
|
}
|
|
|
|
try {
|
|
$pdo->beginTransaction();
|
|
|
|
// Get sender's balance
|
|
$stmt = $pdo->prepare('SELECT balance FROM users WHERE id = ? FOR UPDATE');
|
|
$stmt->execute([$user_id]);
|
|
$sender = $stmt->fetch();
|
|
|
|
if ($sender['balance'] < $amount) {
|
|
$_SESSION['error_message'] = 'Insufficient funds.';
|
|
header('Location: pay-merchant.php');
|
|
$pdo->rollBack();
|
|
exit;
|
|
}
|
|
|
|
// Debit sender
|
|
$stmt = $pdo->prepare('UPDATE users SET balance = balance - ? WHERE id = ?');
|
|
$stmt->execute([$amount, $user_id]);
|
|
|
|
// Credit merchant (using the dummy merchant for this example)
|
|
$stmt = $pdo->prepare('UPDATE users SET balance = balance + ? WHERE id = ?');
|
|
$stmt->execute([$amount, $merchant_id]);
|
|
|
|
// Record transaction
|
|
$stmt = $pdo->prepare('INSERT INTO transactions (sender_id, receiver_id, amount, type, description) VALUES (?, ?, ?, ?, ?)');
|
|
$stmt->execute([$user_id, $merchant_id, $amount, 'merchant_payment', 'Payment to merchant ' . htmlspecialchars($merchant_code)]);
|
|
|
|
$pdo->commit();
|
|
|
|
$_SESSION['success_message'] = 'Payment of $' . number_format($amount, 2) . ' to merchant ' . htmlspecialchars($merchant_code) . ' was successful.';
|
|
header('Location: dashboard.php');
|
|
exit;
|
|
|
|
} catch (Exception $e) {
|
|
$pdo->rollBack();
|
|
$_SESSION['error_message'] = 'An error occurred. Please try again.';
|
|
error_log('Merchant Payment Error: ' . $e->getMessage());
|
|
header('Location: pay-merchant.php');
|
|
exit;
|
|
}
|
|
}
|