92 lines
2.9 KiB
PHP
92 lines
2.9 KiB
PHP
<?php
|
|
session_start();
|
|
require_once 'db/config.php';
|
|
|
|
if (!isset($_SESSION['user_id'])) {
|
|
header("Location: login.php");
|
|
exit;
|
|
}
|
|
|
|
// Check if 'notes' column exists and add it if not
|
|
try {
|
|
$pdo->query("SELECT notes FROM transactions LIMIT 1");
|
|
} catch (PDOException $e) {
|
|
if ($e->getCode() == '42S22') { // Column not found
|
|
$pdo->exec("ALTER TABLE transactions ADD COLUMN notes TEXT");
|
|
}
|
|
}
|
|
|
|
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
|
|
$sender_id = $_SESSION['user_id'];
|
|
$recipient_mobile = $_POST['recipient'];
|
|
$amount = (float)$_POST['amount'];
|
|
$notes = !empty($_POST['notes']) ? trim($_POST['notes']) : null;
|
|
|
|
// Validate amount
|
|
if ($amount <= 0) {
|
|
$_SESSION['message'] = "Invalid amount.";
|
|
$_SESSION['message_type'] = "danger";
|
|
header("Location: send-money.php");
|
|
exit;
|
|
}
|
|
|
|
try {
|
|
$pdo->beginTransaction();
|
|
|
|
// Get sender
|
|
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ? FOR UPDATE");
|
|
$stmt->execute([$sender_id]);
|
|
$sender = $stmt->fetch();
|
|
|
|
// Get recipient
|
|
$stmt = $pdo->prepare("SELECT * FROM users WHERE mobile = ? FOR UPDATE");
|
|
$stmt->execute([$recipient_mobile]);
|
|
$recipient = $stmt->fetch();
|
|
|
|
if (!$recipient) {
|
|
throw new Exception("Recipient not found.");
|
|
}
|
|
|
|
if ($sender['id'] === $recipient['id']) {
|
|
throw new Exception("You cannot send money to yourself.");
|
|
}
|
|
|
|
if ($sender['balance'] < $amount) {
|
|
throw new Exception("Insufficient funds.");
|
|
}
|
|
|
|
// Perform transaction
|
|
$new_sender_balance = $sender['balance'] - $amount;
|
|
$stmt = $pdo->prepare("UPDATE users SET balance = ? WHERE id = ?");
|
|
$stmt->execute([$new_sender_balance, $sender_id]);
|
|
|
|
$new_recipient_balance = $recipient['balance'] + $amount;
|
|
$stmt = $pdo->prepare("UPDATE users SET balance = ? WHERE id = ?");
|
|
$stmt->execute([$new_recipient_balance, $recipient['id']]);
|
|
|
|
// Record transaction
|
|
$stmt = $pdo->prepare("INSERT INTO transactions (user_id, type, amount, description, notes) VALUES (?, ?, ?, ?, ?)");
|
|
$stmt->execute([$sender_id, 'debit', $amount, "Sent money to {$recipient['name']}", $notes]);
|
|
$stmt->execute([$recipient['id'], 'credit', $amount, "Received money from {$sender['name']}", $notes]);
|
|
|
|
$pdo->commit();
|
|
|
|
$_SESSION['message'] = "Money sent successfully!";
|
|
$_SESSION['message_type'] = "success";
|
|
header("Location: dashboard.php");
|
|
exit;
|
|
|
|
} catch (Exception $e) {
|
|
if ($pdo->inTransaction()) {
|
|
$pdo->rollBack();
|
|
}
|
|
$_SESSION['message'] = "Error: " . $e->getMessage();
|
|
$_SESSION['message_type'] = "danger";
|
|
header("Location: send-money.php");
|
|
exit;
|
|
}
|
|
} else {
|
|
header("Location: send-money.php");
|
|
exit;
|
|
}
|