<?php
// Show errors for debugging (disable in production)
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);

session_start();
require 'config.php';
require 'includes/mailer.php';

if (!isset($_SESSION['user_id'])) {
    header("Location: login.php");
    exit();
}

if ($_SERVER["REQUEST_METHOD"] === "POST") {
    $sender_id = $_SESSION['user_id'];
    $recipient_id = intval($_POST['recipient_id']);
    $amount = floatval($_POST['amount']);

    // Validate input
    if ($amount <= 0) {
        showMessageAndRedirect("Invalid amount entered.", false);
    }

    // Fetch sender's details
    $stmt = $conn->prepare("SELECT username, email, balance FROM users WHERE id = ?");
    $stmt->bind_param("i", $sender_id);
    $stmt->execute();
    $stmt->bind_result($sender_name, $sender_email, $sender_balance);
    if (!$stmt->fetch()) {
        $stmt->close();
        showMessageAndRedirect("Sender not found.", false);
    }
    $stmt->close();

    // Check if the sender has sufficient balance
    if ($sender_balance < $amount) {
        showMessageAndRedirect("Insufficient balance.", false);
    }

    // Fetch recipient's details
    $stmt = $conn->prepare("SELECT username, email, balance FROM users WHERE id = ?");
    $stmt->bind_param("i", $recipient_id);
    $stmt->execute();
    $stmt->bind_result($recipient_name, $recipient_email, $recipient_balance);
    if (!$stmt->fetch()) {
        $stmt->close();
        showMessageAndRedirect("Recipient not found.", false);
    }
    $stmt->close();

    // Start transaction to ensure atomicity
    $conn->begin_transaction();
    try {
        // Deduct from sender's balance
        $stmt = $conn->prepare("UPDATE users SET balance = balance - ? WHERE id = ?");
        $stmt->bind_param("di", $amount, $sender_id);
        $stmt->execute();
        $stmt->close();

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

        // Log the transfer in `tbl_transfers`
        $stmt = $conn->prepare("INSERT INTO tbl_transfers (sender_id, recipient_id, amount, status, created_at) VALUES (?, ?, ?, 'success', NOW())");
        $stmt->bind_param("iid", $sender_id, $recipient_id, $amount);
        $stmt->execute();
        $stmt->close();

        // Commit the transaction
        $conn->commit();

        // Send Emails to both sender and recipient
        $subject = "Money Transfer Notification";
        $message_sender = "Hi $sender_name,<br><br>You sent GHS " . number_format($amount, 2) . " to $recipient_name.";
        $message_recipient = "Hi $recipient_name,<br><br>You received GHS " . number_format($amount, 2) . " from $sender_name.";

        sendEmail($sender_email, $subject, $message_sender);
        sendEmail($recipient_email, $subject, $message_recipient);

        // Update the session for immediate dashboard update (sender balance)
        $_SESSION['balance'] = $sender_balance - $amount;

        // Redirect with success message
        showMessageAndRedirect("Money sent successfully!", true);
    } catch (Exception $e) {
        // Rollback transaction in case of failure
        $conn->rollback();
        showMessageAndRedirect("Transfer failed. Please try again.", false);
    }
}

// Helper function to show messages and redirect
function showMessageAndRedirect($message, $success)
{
    $redirect_url = "my-dashboard.php"; // Update for recipient's dashboard
    ?>
    <!DOCTYPE html>
    <html>
    <head>
        <title>Transfer Status</title>
        <meta http-equiv="refresh" content="3;url=<?php echo $redirect_url; ?>">
        <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    </head>
    <body class="bg-light d-flex align-items-center justify-content-center vh-100">
        <div class="text-center">
            <div class="alert alert-<?php echo $success ? 'success' : 'danger'; ?>" role="alert">
                <?php echo htmlspecialchars($message); ?>
            </div>
            <p>Redirecting to your dashboard...</p>
        </div>
    </body>
    </html>
    <?php
    exit();
}
?>
