<?php
session_start();
require_once 'includes/auth_check.php';

$page = 'international-transfer';
$database = new Database();
$db = $database->getConnection();

// Get saved beneficiaries
$stmt = $db->prepare("SELECT b.*, u.id as recipient_id, u.first_name, u.last_name, u.account_number FROM beneficiaries b JOIN users u ON b.recipient_id = u.id WHERE b.user_id = ? ORDER BY b.name ASC");
$stmt->execute([$_SESSION['user_id']]);
$beneficiaries = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Check for success/error messages
$success_message = $_SESSION['success_message'] ?? null;
$error_message = $_SESSION['error_message'] ?? null;
unset($_SESSION['success_message'], $_SESSION['error_message']);

// Determine which step to show
$current_step = isset($_GET['step']) ? (int)$_GET['step'] : 1;
if ($current_step < 1 || $current_step > 3) $current_step = 1;

// Store form data in session to persist between steps
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['wizard_action'])) {
    if ($_POST['wizard_action'] === 'step1') {
        $_SESSION['wire_transfer_data'] = ['amount' => $_POST['amount'], 'currency' => $_POST['currency'], 'description' => $_POST['description']];
        header('Location: international-transfer.php?step=2');
        exit;
    } elseif ($_POST['wizard_action'] === 'step2') {
        $_SESSION['wire_transfer_data']['recipient_name'] = $_POST['recipient_name'];
        $_SESSION['wire_transfer_data']['bank_name'] = $_POST['bank_name'];
        $_SESSION['wire_transfer_data']['swift_code'] = $_POST['swift_code'];
        $_SESSION['wire_transfer_data']['account_number'] = $_POST['account_number'];
        $_SESSION['wire_transfer_data']['address'] = $_POST['address'];
        $_SESSION['wire_transfer_data']['country'] = $_POST['country'];
        header('Location: international-transfer.php?step=3');
        exit;
    }
}

// Helper functions
function calculateWireFee($amount) { return 25 + ($amount * 0.01); }
function getExchangeRate($from, $to) { $rates = ['USD' => 1.00, 'EUR' => 0.85, 'GBP' => 0.73, 'JPY' => 110.25, 'CAD' => 1.25, 'AUD' => 1.35, 'CHF' => 0.92, 'CNY' => 6.45, 'INR' => 74.50, 'SGD' => 1.35]; return ($from === $to) ? 1 : ($rates[$to] / $rates[$from]); }
$currencies = ['USD' => 'US Dollar', 'EUR' => 'Euro', 'GBP' => 'British Pound', 'JPY' => 'Japanese Yen', 'CAD' => 'Canadian Dollar', 'AUD' => 'Australian Dollar', 'CHF' => 'Swiss Franc', 'CNY' => 'Chinese Yuan', 'INR' => 'Indian Rupee', 'SGD' => 'Singapore Dollar'];
$countries = ['US' => 'United States', 'GB' => 'United Kingdom', 'CA' => 'Canada', 'AU' => 'Australia', 'DE' => 'Germany', 'FR' => 'France', 'JP' => 'Japan', 'CN' => 'China', 'IN' => 'India', 'SG' => 'Singapore', 'CH' => 'Switzerland', 'ES' => 'Spain', 'IT' => 'Italy', 'NL' => 'Netherlands', 'BR' => 'Brazil', 'MX' => 'Mexico', 'ZA' => 'South Africa', 'NG' => 'Nigeria', 'KE' => 'Kenya', 'AE' => 'United Arab Emirates'];

include 'includes/header.php';
include 'includes/sidebar.php';
?>

<style>
    .wizard-progress{display:flex;justify-content:space-between;margin-bottom:2rem;position:relative}.wizard-progress::before{content:'';position:absolute;top:50%;left:0;right:0;height:2px;background-color:#e9ecef;transform:translateY(-50%);z-index:1}.progress-line{position:absolute;top:50%;left:0;height:2px;background-color:#2563eb;transform:translateY(-50%);z-index:2;transition:width .4s ease}.wizard-step-item{position:relative;z-index:3;text-align:center}.step-icon{width:40px;height:40px;border-radius:50%;background-color:#fff;border:2px solid #e9ecef;color:#adb5bd;display:flex;align-items:center;justify-content:center;margin:0 auto .5rem;transition:all .4s ease}.wizard-step-item.active .step-icon{border-color:#2563eb;background-color:#2563eb;color:#fff}.wizard-step-item.completed .step-icon{border-color:#059669;background-color:#059669;color:#fff}.step-label{font-size:.875rem;color:#6c757d}.wizard-step-item.active .step-label{font-weight:600;color:#2563eb}.fee-breakdown{background-color:#f8f9fa;border-radius:.5rem;padding:1rem}.fee-breakdown .row{margin-bottom:.5rem}.fee-breakdown .total-row{border-top:1px solid #dee2e6;padding-top:.5rem;font-weight:600}
</style>

<div class="main-content">
    <div class="page-header mb-4"><h4 class="page-title">International Wire Transfer</h4></div>
    <?php if ($error_message): ?><div class="alert alert-danger"><?php echo htmlspecialchars($error_message); ?></div><?php endif; ?>

    <div class="card">
        <div class="card-body p-lg-5">
            <!-- Progress Bar -->
            <div class="wizard-progress">
                <div class="progress-line" style="width: <?php echo (($current_step - 1) / 2) * 100; ?>%"></div>
                <div class="wizard-step-item <?php echo $current_step >= 1 ? 'active' : ''; ?> <?php echo $current_step > 1 ? 'completed' : ''; ?>"><div class="step-icon"><i class='bx bx-dollar'></i></div><div class="step-label">Amount</div></div>
                <div class="wizard-step-item <?php echo $current_step >= 2 ? 'active' : ''; ?> <?php echo $current_step > 2 ? 'completed' : ''; ?>"><div class="step-icon"><i class='bx bx-building-house'></i></div><div class="step-label">Bank Details</div></div>
                <div class="wizard-step-item <?php echo $current_step >= 3 ? 'active' : ''; ?>"><div class="step-icon"><i class='bx bx-check-shield'></i></div><div class="step-label">Confirm</div></div>
            </div>

            <!-- Step 1: Amount -->
            <?php if ($current_step == 1): ?>
                <form method="POST" action="international-transfer.php"><input type="hidden" name="wizard_action" value="step1"><div class="row justify-content-center"><div class="col-md-6"><div class="mb-3"><label class="form-label">Select Currency</label><select class="form-select" name="currency" id="transferCurrency" required><?php foreach ($currencies as $code => $name): ?><option value="<?php echo $code; ?>" <?php echo ($code === ($user['currency'] ?? 'USD')) ? 'selected' : ''; ?>><?php echo "$code - $name"; ?></option><?php endforeach; ?></select></div><div class="input-group input-group-lg mb-3"><span class="input-group-text" id="currencySymbol"><?php echo htmlspecialchars($user['currency']); ?></span><input type="number" class="form-control text-center" name="amount" id="transferAmount" placeholder="0.00" step="0.01" min="1" required value="<?php echo htmlspecialchars($_SESSION['wire_transfer_data']['amount'] ?? ''); ?>"></div><div class="fee-breakdown mb-3"><h6 class="mb-3">Fee Breakdown</h6><div class="row"><div class="col">Transfer Amount</div><div class="col-auto" id="displayAmount"><?php echo htmlspecialchars($user['currency']); ?> 0.00</div></div><div class="row"><div class="col">Wire Transfer Fee</div><div class="col-auto" id="displayFee"><?php echo htmlspecialchars($user['currency']); ?> 0.00</div></div><div class="row total-row"><div class="col">Total Debit</div><div class="col-auto" id="displayTotal"><?php echo htmlspecialchars($user['currency']); ?> 0.00</div></div></div><div class="mb-3"><label for="description" class="form-label">Description (Optional)</label><input type="text" class="form-control" name="description" placeholder="e.g., Business payment" value="<?php echo htmlspecialchars($_SESSION['wire_transfer_data']['description'] ?? ''); ?>"></div><div class="d-grid"><button type="submit" class="btn btn-primary btn-lg">Next</button></div></div></div></form>
            
            <!-- Step 2: Bank Details -->
            <?php elseif ($current_step == 2): ?>
                <form method="POST" action="international-transfer.php"><input type="hidden" name="wizard_action" value="step2"><div class="row justify-content-center"><div class="col-md-8"><div class="mb-3"><label class="form-label">Recipient's Full Name</label><input type="text" class="form-control" name="recipient_name" required value="<?php echo htmlspecialchars($_SESSION['wire_transfer_data']['recipient_name'] ?? ''); ?>"></div><div class="mb-3"><label class="form-label">Bank Name</label><input type="text" class="form-control" name="bank_name" required value="<?php echo htmlspecialchars($_SESSION['wire_transfer_data']['bank_name'] ?? ''); ?>"></div><div class="row"><div class="col-md-6 mb-3"><label class="form-label">SWIFT/BIC Code</label><input type="text" class="form-control" name="swift_code" required value="<?php echo htmlspecialchars($_SESSION['wire_transfer_data']['swift_code'] ?? ''); ?>"></div><div class="col-md-6 mb-3"><label class="form-label">Account Number / IBAN</label><input type="text" class="form-control" name="account_number" required value="<?php echo htmlspecialchars($_SESSION['wire_transfer_data']['account_number'] ?? ''); ?>"></div></div><div class="mb-3"><label class="form-label">Bank Address</label><textarea class="form-control" name="address" rows="2" required><?php echo htmlspecialchars($_SESSION['wire_transfer_data']['address'] ?? ''); ?></textarea></div><div class="mb-3"><label class="form-label">Country</label><select class="form-select" name="country" required><option value="">-- Select Country --</option><?php foreach ($countries as $code => $name): ?><option value="<?php echo $code; ?>" <?php echo ($code === ($_SESSION['wire_transfer_data']['country'] ?? '')) ? 'selected' : ''; ?>><?php echo $name; ?></option><?php endforeach; ?></select></div><div class="d-flex justify-content-between mt-4"><a href="international-transfer.php?step=1" class="btn btn-secondary">Back</a><button type="submit" class="btn btn-primary">Next</button></div></div></div></form>
            
            <!-- Step 3: Confirm -->
<?php elseif ($current_step == 3): ?>
    <?php
    $amount = $_SESSION['wire_transfer_data']['amount'] ?? 0; $currency = $_SESSION['wire_transfer_data']['currency'] ?? $user['currency']; $fee = calculateWireFee($amount); $total = $amount + $fee;
    $userCurrencyTotal = ($currency !== $user['currency']) ? $total * getExchangeRate($currency, $user['currency']) : $total;
    ?>
    <form method="POST" action="process_wire_transfer.php">
        <input type="hidden" name="amount" value="<?php echo htmlspecialchars($amount); ?>">
        <input type="hidden" name="currency" value="<?php echo htmlspecialchars($currency); ?>">
        <input type="hidden" name="description" value="<?php echo htmlspecialchars($_SESSION['wire_transfer_data']['description']); ?>">
        <input type="hidden" name="recipient_name" value="<?php echo htmlspecialchars($_SESSION['wire_transfer_data']['recipient_name']); ?>">
        <input type="hidden" name="bank_name" value="<?php echo htmlspecialchars($_SESSION['wire_transfer_data']['bank_name']); ?>">
        <input type="hidden" name="swift_code" value="<?php echo htmlspecialchars($_SESSION['wire_transfer_data']['swift_code']); ?>">
        <input type="hidden" name="account_number" value="<?php echo htmlspecialchars($_SESSION['wire_transfer_data']['account_number']); ?>">
        <input type="hidden" name="address" value="<?php echo htmlspecialchars($_SESSION['wire_transfer_data']['address']); ?>">
        <input type="hidden" name="country" value="<?php echo htmlspecialchars($_SESSION['wire_transfer_data']['country']); ?>">
        <input type="hidden" name="fee" value="<?php echo $fee; ?>">
        
        <div class="row justify-content-center"><div class="col-md-8"><div class="alert alert-info text-center"><p class="mb-1">You are sending</p><h2 class="fw-bold"><?php echo htmlspecialchars($currency); ?> <?php echo number_format($amount, 2); ?></h2><p class="mb-1 mt-3">To</p><h5 class="fw-bold"><?php echo htmlspecialchars($_SESSION['wire_transfer_data']['recipient_name']); ?></h5></div><div class="mb-3"><label class="form-label">Enter your 4-digit PIN to authorize</label><input type="password" class="form-control form-control-lg text-center" name="pin" maxlength="4" required style="letter-spacing: 1em;"></div><div class="d-flex justify-content-between mt-4"><a href="international-transfer.php?step=2" class="btn btn-secondary">Back</a><button type="submit" class="btn btn-success btn-lg">Confirm & Send</button></div></div></div>
    </form>
<?php endif; ?>
        </div>
    </div>
</div>

<?php include 'includes/footer.php'; ?>

<script>
document.addEventListener('DOMContentLoaded', function() {
    const transferAmount = document.getElementById('transferAmount');
    if (transferAmount) {
        const transferCurrency = document.getElementById('transferCurrency');
        function updateFeeBreakdown() {
            const amount = parseFloat(transferAmount.value) || 0;
            const currency = transferCurrency.value;
            const fee = 25 + (amount * 0.01);
            document.getElementById('currencySymbol').textContent = currency;
            document.getElementById('displayAmount').textContent = `${currency} ${amount.toFixed(2)}`;
            document.getElementById('displayFee').textContent = `${currency} ${fee.toFixed(2)}`;
            document.getElementById('displayTotal').textContent = `${currency} ${(amount + fee).toFixed(2)}`;
        }
        transferCurrency.addEventListener('change', updateFeeBreakdown);
        transferAmount.addEventListener('input', updateFeeBreakdown);
        updateFeeBreakdown();
    }
});
</script>
