<?php
ini_set('display_errors', 0);
ini_set('display_startup_errors', 0);
error_reporting(E_ALL);

require_once __DIR__ . '/../includes/db.php';
require_once __DIR__ . '/../includes/functions.php';
require_once __DIR__ . '/../includes/mailer.php';

if (session_status() === PHP_SESSION_NONE) session_start();

$user_id = $_SESSION['user_id'] ?? null;
if (!$user_id) {
    header("Location: /auth/login.php");
    exit;
}

$conn = db();
if (!$conn) die("Database connection failed");

// Fetch user + account
$stmt = $conn->prepare("
    SELECT u.*, a.account_number AS from_account, a.balance, a.currency 
    FROM users u 
    LEFT JOIN accounts a ON a.user_id = u.id
    WHERE u.id = ? LIMIT 1
");
$stmt->bind_param("i", $user_id);
$stmt->execute();
$user = $stmt->get_result()->fetch_assoc();
$stmt->close();

$balance = floatval($user['balance'] ?? 0);
$currency = $user['currency'] ?? 'USD';

// Currency symbol
$symbols = [
    'USD'=>'$','EUR'=>'€','GBP'=>'£','JPY'=>'¥','CNY'=>'¥',
    'NGN'=>'₦','GHS'=>'₵','INR'=>'₹','CAD'=>'C$','AUD'=>'A$'
];
$symbol = $symbols[$currency] ?? $currency;

$errors = [];

if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    // Get form data
    $type = $_POST['transfer_type'] ?? '';
    $recipient_bank = trim($_POST['bank'] ?? '');
    $recipient_account = trim($_POST['account_no'] ?? '');
    $recipient_name = trim($_POST['holder'] ?? '');
    $amount = floatval($_POST['amount'] ?? 0);

    $recipient_address = trim($_POST['holder_address'] ?? '');
    $recipient_country = trim($_POST['bank_address'] ?? '');
    $iban = trim($_POST['iban'] ?? '');
    $swift_code = trim($_POST['swift'] ?? '');
    $routing = trim($_POST['routing'] ?? '');
    $memo = trim($_POST['memo'] ?? '');

    // Fees
    $fee = ($type === 'local') ? 3 : (($type === 'international') ? 10 : 0);
    $total = $amount + $fee;

    // Validation
    if (!$type || !$recipient_bank || !$recipient_account || !$recipient_name || $amount <= 0) {
        $errors[] = "Fill all required fields.";
    }

    if ($total > $balance) {
        $errors[] = "Insufficient balance. Total: {$symbol}" . number_format($total,2);
    }

    if (empty($errors)) {

        $reference = strtoupper($type) . '-' . time() . '-' . rand(1000,9999);
        $from_account = $user['from_account'];

        // INSERT including from_balance
        $stmt = $conn->prepare("
            INSERT INTO transfers 
            (user_id, from_balance, from_account, type, recipient_name, recipient_account, recipient_bank, 
             recipient_address, recipient_country, iban, swift_code, routing, memo, 
             amount, currency, fee, total, reference, status, created_at)
            VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 'pending', NOW())
        ");

        if (!$stmt) {
            die("Prepare failed: " . $conn->error);
        }

        $stmt->bind_param(
            "idssssssssssssddds",
            $user_id,
            $balance,       // ✅ Save current user balance
            $from_account,
            $type,
            $recipient_name,
            $recipient_account,
            $recipient_bank,
            $recipient_address,
            $recipient_country,
            $iban,
            $swift_code,
            $routing,
            $memo,
            $amount,
            $currency,
            $fee,
            $total,
            $reference
        );

        if ($stmt->execute()) {
            $transfer_id = $stmt->insert_id;

            // Redirect to confirm transfer page
            ob_clean();
            header("Location: /transfer/confirm_transfer.php?transfer_id=" . $transfer_id);
            exit;
        } else {
            $errors[] = "Execute failed: " . $stmt->error;
        }

        $stmt->close();
    }
}

// ================= UI =================
ob_start();
?>

<h2>💸 Initiate Transfer</h2>

<?php if ($errors): foreach($errors as $e): ?>
    <div class="error"><?= htmlspecialchars($e) ?></div>
<?php endforeach; endif; ?>

<form id="transferForm" method="POST">
    <label>Transfer Type *</label>
    <select name="transfer_type" id="transfer_type" required>
        <option value="">Select</option>
        <option value="local">Local</option>
        <option value="international">International</option>
    </select>

    <input type="text" name="bank" placeholder="Enter Bank" required>

    <input type="text" name="account_no" placeholder="Enter Account Number" required>

    <input type="text" name="holder" placeholder="Enter Account Holder Name" required>

    <input type="number" step="0.01" name="amount" id="amount" placeholder="Enter Amount" required>

    <!-- Local transfer optional fields -->
    <div id="localFields" style="display:none; margin-top:10px;">
        <input type="text" name="swift" placeholder="SWIFT / Routing / IFSC (Optional)">
        <input type="text" name="memo" placeholder="Memo (Optional)">
    </div>

    <!-- International transfer fields -->
    <div id="intlFields" style="display:none; margin-top:10px;">
        <input type="text" name="bank_address" placeholder="Bank Address">
        <input type="text" name="holder_address" placeholder="Holder Address">
        <input type="text" name="iban" placeholder="IBAN">
        <input type="text" name="swift" placeholder="SWIFT">
        <input type="text" name="routing" placeholder="Routing">
        <input type="text" name="memo" placeholder="Memo">
    </div>

    <p>Balance: <b id="bal"><?= $symbol . number_format($balance,2) ?></b></p>
    <p>Fee: <b id="fee">0.00</b></p>
    <p>Total: <b id="total">0.00</b></p>

    <button type="submit">Continue</button>
</form>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(function(){
    const balance = parseFloat($('#bal').text().replace(/[^0-9.]/g,'')) || 0;
    const symbol = "<?= $symbol ?>";

    function update(){
        let amt = parseFloat($('#amount').val()) || 0;
        let type = $('#transfer_type').val();
        let fee = (type==='local')?3:(type==='international')?10:0;
        let total = amt + fee;

        $('#fee').text(symbol + fee.toFixed(2));
        $('#total').text(symbol + total.toFixed(2));
        $('#total').css('color', total>balance?'red':'black');
    }

    $('#transfer_type').change(function(){
        let type = $(this).val();
        $('#localFields').toggle(type==='local');           // show local only for local
        $('#intlFields').toggle(type==='international');   // show intl only for international
        update();
    });

    $('#amount').on('input', update);
});
</script>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
$(function(){
    const balance = parseFloat($('#bal').text().replace(/[^0-9.]/g,'')) || 0;
    const symbol = "<?= $symbol ?>";

    function update(){
        let amt = parseFloat($('#amount').val()) || 0;
        let type = $('#transfer_type').val();
        let fee = (type==='local')?3:(type==='international')?10:0;
        let total = amt + fee;

        $('#fee').text(symbol + fee.toFixed(2));
        $('#total').text(symbol + total.toFixed(2));
        $('#total').css('color', total>balance?'red':'black');
    }

    $('#transfer_type').change(function(){
        $('#intlFields').toggle($(this).val()==='international');
        update();
    });

    $('#amount').on('input', update);
});
</script>

<?php
$content = ob_get_clean();
renderLayout("Initiate Transfer", $content, $conn);
?>