<?php
session_start();
if (!isset($_SESSION['user_id'])) {
    echo "User not logged in!";
    exit;
}

include 'config.php'; // Database connection

$sender_id = $_SESSION['user_id']; // Sender's ID from session
$recipient_id = $_POST['recipient_id']; // Recipient ID from form
$amount = floatval($_POST['amount']); // Transfer amount

// Ensure amount is valid and positive
if ($amount <= 0) {
    echo "Invalid amount!";
    exit;
}

// Start transaction for consistency
$conn->begin_transaction();

try {
    // Fetch sender's balance
    $query = "SELECT balance FROM users WHERE id = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $sender_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $sender_balance = $result->fetch_assoc()['balance'];
    $stmt->close();

    // Check sufficient balance
    if ($sender_balance < $amount) {
        echo "Insufficient balance!";
        exit;
    }

    // Fetch recipient's balance
    $query = "SELECT balance FROM users WHERE id = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("i", $recipient_id);
    $stmt->execute();
    $result = $stmt->get_result();
    $recipient_balance = $result->fetch_assoc()['balance'];
    $stmt->close();

    // Update sender's balance
    $new_sender_balance = $sender_balance - $amount;
    $query = "UPDATE users SET balance = ? WHERE id = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("di", $new_sender_balance, $sender_id);
    $stmt->execute();
    $stmt->close();

    // Update recipient's balance
    $new_recipient_balance = $recipient_balance + $amount;
    $query = "UPDATE users SET balance = ? WHERE id = ?";
    $stmt = $conn->prepare($query);
    $stmt->bind_param("di", $new_recipient_balance, $recipient_id);
    $stmt->execute();
    $stmt->close();

    // Record transfer in tbl_transfers
    $stmt = $conn->prepare("INSERT INTO tbl_transfers (sender_id, recipient_id, amount, status) VALUES (?, ?, ?, 'successful')");
    $stmt->bind_param("iid", $sender_id, $recipient_id, $amount);
    $stmt->execute();
    $stmt->close();

    // Format amount for notification
    $formattedAmount = number_format($amount, 2);

    // Fetch recipient's username
    $stmt = $conn->prepare("SELECT username FROM users WHERE id = ?");
    $stmt->bind_param("i", $recipient_id);
    $stmt->execute();
    $stmt->bind_result($recipient_username);
    $stmt->fetch();
    $stmt->close();

    // Insert sender notification
    $sender_message = "You sent GHS $formattedAmount to $recipient_username.";
    $stmt = $conn->prepare("INSERT INTO notifications (user_id, message, is_read) VALUES (?, ?, 0)");
    $stmt->bind_param("is", $sender_id, $sender_message);
    $stmt->execute();
    $stmt->close();

    // Insert recipient notification
    $recipient_message = "You received GHS $formattedAmount from another user.";
    $stmt = $conn->prepare("INSERT INTO notifications (user_id, message, is_read) VALUES (?, ?, 0)");
    $stmt->bind_param("is", $recipient_id, $recipient_message);
    $stmt->execute();
    $stmt->close();

    // Commit all changes
    $conn->commit();

    // Redirect to dashboard
    header("Location: my-dashboard.php?message=Transfer successful");
    exit;

} catch (Exception $e) {
    $conn->rollback();
    echo "Error: " . $e->getMessage();
}
?>
