<?php
session_start();
require_once '../includes/db.php';
require_once '../includes/mailer.php';
require_once '../includes/user_check.php'; // ensures user is logged in

$user_id = $_SESSION['user_id'];

// Fetch user balance
$stmt = $conn->prepare("SELECT balance, currency, account_number, full_name, email FROM users WHERE id=?");
if (!$stmt) { die("DB Error: " . $conn->error); }
$stmt->bind_param("i", $user_id);
$stmt->execute();
$stmt->bind_result($balance, $currency, $account_number, $full_name, $email);
$stmt->fetch();
$stmt->close();

// Handle form submission
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $recipient_account = $_POST['recipient_account'];
    $amount = floatval($_POST['amount']);
    $description = $_POST['description'];

    $fee = 3; // local transfer fixed fee
    if (($amount + $fee) > $balance) {
        $error = "Insufficient balance for this transfer (including fee $currency$fee).";
    } else {
        // Save transfer in a pending state
        $stmt = $conn->prepare("INSERT INTO transfers (user_id, recipient_account, amount, fee, description, status) VALUES (?, ?, ?, ?, ?, 'pending')");
        if (!$stmt) die("DB Error: " . $conn->error);
        $stmt->bind_param("isdss", $user_id, $recipient_account, $amount, $fee, $description);
        $stmt->execute();
        $transfer_id = $stmt->insert_id;
        $stmt->close();

        // Redirect to review page
        header("Location: transfer_review.php?transfer_id=$transfer_id");
        exit;
    }
}
?>
<h2>Initiate Transfer</h2>
<p>Balance: <?php echo $currency . number_format($balance, 2); ?></p>
<?php if(!empty($error)) echo "<p style='color:red;'>$error</p>"; ?>
<form method="post">
    Recipient Account: <input type="text" name="recipient_account" required><br>
    Amount: <input type="number" step="0.01" name="amount" required><br>
    Description: <input type="text" name="description"><br>
    <button type="submit">Review Transfer</button>
</form>