<?php
require_once '../core/bootstrap.php';

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

if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    header('Location: wallet.php');
    exit();
}

$recipient_email = trim($_POST['recipient_email'] ?? '');
$amount = filter_input(INPUT_POST, 'amount', FILTER_VALIDATE_FLOAT);
$description = trim($_POST['description'] ?? 'Transfer');
$sender_id = $_SESSION['user_id'];

if (empty($recipient_email) || !$amount || $amount <= 0) {
    header('Location: wallet.php?error=' . urlencode('Invalid recipient or amount.'));
    exit();
}

$userModel = new User();
$recipient = $userModel->findByEmail($recipient_email);

if (!$recipient) {
    header('Location: wallet.php?error=' . urlencode('Recipient not found.'));
    exit();
}

if ($recipient->id == $sender_id) {
    header('Location: wallet.php?error=' . urlencode('You cannot transfer funds to yourself.'));
    exit();
}

$walletModel = new Wallet();
$senderWallet = $walletModel->getOrCreateWallet('user', $sender_id);
$recipientWallet = $walletModel->getOrCreateWallet('user', $recipient->id);

if ($senderWallet->balance < $amount) {
    header('Location: wallet.php?error=' . urlencode('Insufficient funds.'));
    exit();
}

if ($walletModel->transfer($senderWallet->id, $recipientWallet->id, $amount, $description)) {
    // Notify recipient
    $notificationModel = new Notification();
    $sender = $userModel->findById($sender_id);
    $sender_name = $sender ? ($sender->first_name . ' ' . $sender->last_name) : 'Someone';
    
    $notificationModel->create($recipient->id, 'funds_received', "You received " . number_format($amount, 2) . " from {$sender_name}.");
    
    header('Location: wallet.php?status=success&msg=' . urlencode('Transfer successful.'));
} else {
    header('Location: wallet.php?error=' . urlencode('Transfer failed. Please try again.'));
}
exit();