<?php
ob_start();
include 'master.php';

$_balance        = (float)(getUserDetails('balance', $_SESSION['email']) ?: 0);
$_btc_balance    = (float)(getUserDetails('btcBalance', $_SESSION['email']) ?: 0);
$_btc_price      = (float)(getBtcPrice($_SESSION['currency'] ?? 'usd') ?: 0);
$_btc_fiat_value = $_btc_balance * $_btc_price;
$_curr_code      = strtoupper($_SESSION['currency'] ?? 'USD');

$_swap_success = '';
$_swap_error   = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $from_currency = trim($_POST['from_currency'] ?? '');
    $amount        = (float)($_POST['amount'] ?? 0);
    $email         = $_SESSION['email'];

    if ($amount <= 0) {
        $_swap_error = 'Please enter a valid amount greater than zero.';
    } elseif ($from_currency === 'fiat') {
        if ($amount > $_balance) {
            $_swap_error = 'Insufficient ' . $_curr_code . ' balance.';
        } elseif ($_btc_price <= 0) {
            $_swap_error = 'BTC price unavailable. Please try again later.';
        } else {
            $btc_received = $amount / $_btc_price;
            $new_balance  = $_balance - $amount;
            $new_btc      = $_btc_balance + $btc_received;

            $stmt = $connect->prepare("UPDATE users SET balance = ?, btcBalance = ? WHERE email = ?");
            $stmt->bind_param("dds", $new_balance, $new_btc, $email);
            if ($stmt->execute()) {
                $_swap_success = 'Swapped ' . $_curr_sym . number_format($amount, 2) . ' → ' . number_format($btc_received, 8) . ' BTC successfully.';
                $_balance     = $new_balance;
                $_btc_balance = $new_btc;
            } else {
                $_swap_error = 'Swap failed. Please try again.';
            }
            $stmt->close();
        }
    } elseif ($from_currency === 'btc') {
        if ($amount > $_btc_balance) {
            $_swap_error = 'Insufficient Bitcoin balance.';
        } elseif ($_btc_price <= 0) {
            $_swap_error = 'BTC price unavailable. Please try again later.';
        } else {
            $fiat_received = $amount * $_btc_price;
            $new_btc       = $_btc_balance - $amount;
            $new_balance   = $_balance + $fiat_received;

            $stmt = $connect->prepare("UPDATE users SET balance = ?, btcBalance = ? WHERE email = ?");
            $stmt->bind_param("dds", $new_balance, $new_btc, $email);
            if ($stmt->execute()) {
                $_swap_success = 'Swapped ' . number_format($amount, 8) . ' BTC → ' . $_curr_sym . number_format($fiat_received, 2) . ' successfully.';
                $_balance     = $new_balance;
                $_btc_balance = $new_btc;
            } else {
                $_swap_error = 'Swap failed. Please try again.';
            }
            $stmt->close();
        }
    } else {
        $_swap_error = 'Invalid swap direction.';
    }
}
?>

                <!-- Main Content -->
                <main class="flex-1 overflow-y-auto bg-gray-50 dark:bg-gray-900 min-h-0">
                    <div class="h-full overflow-y-auto">

<div class="p-4 space-y-4">

    <!-- Mobile Header -->
    <div class="lg:hidden mb-2">
        <div class="lg:hidden" x-data="{ showMobileNotifications: false }">
    <div class="flex items-center justify-between mb-6">
        <div class="flex items-center space-x-2">
            <a href="../dashboard" class="w-10 h-10 bg-gray-100 dark:bg-gray-800 rounded-full flex items-center justify-center backdrop-blur-sm transition-all duration-200 hover:bg-gray-200 dark:hover:bg-gray-700 mr-2">
                <i class="fa-solid fa-arrow-left text-gray-700 dark:text-gray-300 text-base"></i>
            </a>
            <div>
                <p class="text-gray-900 dark:text-white font-semibold text-base">Currency Swap</p>
            </div>
        </div>
        <div class="flex items-center space-x-2">
            <button @click="toggleDarkMode()"
                    class="w-10 h-10 bg-gray-100 dark:bg-gray-800 rounded-full flex items-center justify-center backdrop-blur-sm transition-all duration-200 hover:bg-gray-200 dark:hover:bg-gray-700">
                <i x-show="!darkMode" class="fa-solid fa-moon text-gray-700 text-base"></i>
                <i x-show="darkMode" class="fa-solid fa-sun text-yellow-400 text-base"></i>
            </button>
            <div class="relative">
                <button @click="showMobileNotifications = !showMobileNotifications" class="w-10 h-10 bg-gray-100 dark:bg-gray-800 rounded-full flex items-center justify-center backdrop-blur-sm transition-all duration-200 hover:bg-gray-200 dark:hover:bg-gray-700">
                    <i class="fa-solid fa-bell text-gray-700 dark:text-gray-300 text-base"></i>
                </button>
            </div>
        </div>
    </div>
    </div></div>

    <!-- Desktop Header -->
    <div class="hidden lg:block">
        <div class="bg-white/80 dark:bg-gray-800/80 backdrop-blur-xl rounded-2xl shadow-lg dark:shadow-gray-900/50 border border-white/20 dark:border-gray-700/50 p-4">
            <div class="flex items-center space-x-3">
                <div class="w-10 h-10 bg-gradient-to-r from-primary-500 to-primary-600 rounded-2xl flex items-center justify-center">
                    <i class="fa-solid fa-arrows-rotate text-white text-lg"></i>
                </div>
                <div>
                    <h1 class="text-xl font-bold text-gray-900 dark:text-white">Currency Swap</h1>
                    <p class="text-sm text-gray-600 dark:text-gray-400">Convert between <?php echo $_curr_code; ?> and Bitcoin</p>
                </div>
            </div>
        </div>
    </div>

    <!-- Alerts -->
    <?php if (!empty($_swap_success)): ?>
    <div class="p-4 bg-emerald-50 dark:bg-emerald-900/20 border border-emerald-300 dark:border-emerald-700 rounded-xl flex items-center space-x-3">
        <i class="fas fa-check-circle text-emerald-500 text-lg flex-shrink-0"></i>
        <p class="text-sm font-medium text-emerald-700 dark:text-emerald-300"><?php echo htmlspecialchars($_swap_success); ?></p>
    </div>
    <?php endif; ?>
    <?php if (!empty($_swap_error)): ?>
    <div class="p-4 bg-red-50 dark:bg-red-900/20 border border-red-300 dark:border-red-700 rounded-xl flex items-center space-x-3">
        <i class="fas fa-exclamation-circle text-red-500 text-lg flex-shrink-0"></i>
        <p class="text-sm font-medium text-red-700 dark:text-red-300"><?php echo htmlspecialchars($_swap_error); ?></p>
    </div>
    <?php endif; ?>

    <!-- Main Card -->
    <div class="bg-white/80 dark:bg-gray-800/80 backdrop-blur-xl rounded-2xl shadow-lg dark:shadow-gray-900/50 border border-white/20 dark:border-gray-700/50 overflow-hidden">
        <div class="p-4">
            <div class="grid grid-cols-1 lg:grid-cols-2 gap-4 mb-6">

                <!-- Balances & Rate -->
                <div class="bg-gray-50 dark:bg-gray-700/50 rounded-xl p-4">
                    <h3 class="text-base font-semibold text-gray-800 dark:text-gray-200 mb-3">Current Balances</h3>

                    <!-- Fiat Balance -->
                    <div class="flex items-center justify-between p-3 bg-white dark:bg-gray-800 rounded-lg shadow-sm mb-3">
                        <div class="flex items-center">
                            <div class="bg-blue-100 dark:bg-blue-900/30 p-2 rounded-full mr-3">
                                <i class="fa-solid fa-wallet text-blue-600 dark:text-blue-400 text-sm"></i>
                            </div>
                            <span class="text-gray-700 dark:text-gray-300 text-sm"><?php echo $_curr_code; ?> Balance</span>
                        </div>
                        <span class="font-semibold text-gray-900 dark:text-white text-sm"><?php echo $_curr_sym . number_format($_balance, 2); ?></span>
                    </div>

                    <!-- BTC Balance -->
                    <div class="flex items-center justify-between p-3 bg-white dark:bg-gray-800 rounded-lg shadow-sm mb-3">
                        <div class="flex items-center">
                            <div class="bg-amber-100 dark:bg-amber-900/30 p-2 rounded-full mr-3">
                                <i class="fa-brands fa-bitcoin text-amber-600 dark:text-amber-400 text-sm"></i>
                            </div>
                            <span class="text-gray-700 dark:text-gray-300 text-sm">Bitcoin Balance</span>
                        </div>
                        <span class="font-semibold text-gray-900 dark:text-white text-sm"><?php echo number_format($_btc_balance, 8); ?> BTC</span>
                    </div>

                    <!-- Exchange Rate -->
                    <div class="p-3 bg-gradient-to-r from-primary-50 to-blue-50 dark:from-gray-700 dark:to-gray-600 rounded-lg border border-primary-100 dark:border-gray-600">
                        <h4 class="text-xs font-medium text-primary-700 dark:text-primary-300 mb-2 text-center">Current Exchange Rate</h4>
                        <div class="flex justify-center items-center space-x-2">
                            <div class="bg-amber-100 dark:bg-amber-900/50 p-1.5 rounded-full">
                                <i class="fa-brands fa-bitcoin text-amber-600 dark:text-amber-400 text-xs"></i>
                            </div>
                            <span class="font-semibold text-gray-900 dark:text-white text-xs">
                                1 BTC = <?php echo $_curr_sym . ($_btc_price ? number_format($_btc_price, 2) : '—') . ' ' . $_curr_code; ?>
                            </span>
                        </div>
                    </div>
                </div>

                <!-- Swap Form -->
                <div>
                    <form action="swap" method="POST" id="swapForm" onsubmit="return requireTransactionAccess()">

                        <!-- From Currency -->
                        <div class="mb-4">
                            <label class="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">From Currency</label>
                            <select id="from_currency" name="from_currency"
                                class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white shadow-sm focus:border-primary-500 px-3 py-2 border focus:ring focus:ring-primary-500 focus:ring-opacity-50 text-sm"
                                required>
                                <option value="fiat"><?php echo $_curr_code; ?> (<?php echo $_curr_sym . number_format($_balance, 2); ?>)</option>
                                <option value="btc">BTC (<?php echo number_format($_btc_balance, 8); ?>)</option>
                            </select>
                        </div>

                        <!-- To Currency (auto-set by JS) -->
                        <div class="mb-4">
                            <label class="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">To Currency</label>
                            <select id="to_currency" name="to_currency"
                                class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white shadow-sm focus:border-primary-500 px-3 py-2 border focus:ring focus:ring-primary-500 focus:ring-opacity-50 text-sm"
                                required>
                                <option value="btc">BTC</option>
                                <option value="fiat"><?php echo $_curr_code; ?></option>
                            </select>
                            <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">Automatically set to the opposite currency</p>
                        </div>

                        <!-- Amount -->
                        <div class="mb-4">
                            <label class="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">Amount</label>
                            <div class="relative rounded-md shadow-sm">
                                <input type="number" id="amount" name="amount"
                                    class="w-full rounded-lg border-gray-300 dark:border-gray-600 dark:bg-gray-700 dark:text-white shadow-sm focus:border-primary-500 px-3 py-2 border focus:ring focus:ring-primary-500 focus:ring-opacity-50 pr-16 text-sm"
                                    step="any" min="0.00000001" placeholder="0.00" required>
                                <div class="absolute inset-y-0 right-0 flex items-center">
                                    <span id="currencyLabel" class="h-full inline-flex items-center px-3 rounded-r-md border border-l-0 border-gray-300 dark:border-gray-600 bg-gray-50 dark:bg-gray-600 text-gray-500 dark:text-gray-300 text-xs"><?php echo $_curr_code; ?></span>
                                </div>
                            </div>
                            <p class="mt-1 text-xs text-gray-500 dark:text-gray-400">Enter the amount you want to swap</p>
                        </div>

                        <!-- Conversion Preview -->
                        <div class="mb-4">
                            <label class="block text-xs font-medium text-gray-700 dark:text-gray-300 mb-1">Estimated Conversion</label>
                            <div id="conversionResult" class="p-3 bg-gray-50 dark:bg-gray-700/50 border border-gray-200 dark:border-gray-600 rounded-lg">
                                <div class="text-center text-gray-500 dark:text-gray-400 text-xs">Enter an amount to see conversion</div>
                            </div>
                        </div>

                        <!-- Submit -->
                        <button type="submit"
                            class="w-full bg-primary-600 hover:bg-primary-700 text-white font-medium py-2.5 px-4 rounded-lg transition-colors duration-150 focus:outline-none focus:ring-2 focus:ring-primary-500 focus:ring-offset-2 flex items-center justify-center text-sm">
                            <i class="fa-solid fa-arrows-rotate text-xs mr-2"></i>
                            <span>Swap Currencies</span>
                        </button>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
(function() {
    const currCode  = '<?php echo $_curr_code; ?>';
    const currSym   = '<?php echo $_curr_sym; ?>';
    const btcPrice  = <?php echo (float)$_btc_price ?: 0; ?>;

    function updateCurrencyLabel() {
        const from = document.getElementById('from_currency').value;
        document.getElementById('currencyLabel').textContent = from === 'fiat' ? currCode : 'BTC';
    }

    function updateToCurrency() {
        const from = document.getElementById('from_currency').value;
        const sel  = document.getElementById('to_currency');
        if (from === 'fiat') {
            sel.innerHTML = '<option value="btc">BTC</option>';
        } else {
            sel.innerHTML = '<option value="fiat">' + currCode + '</option>';
        }
    }

    function calculateConversion() {
        const from   = document.getElementById('from_currency').value;
        const amount = parseFloat(document.getElementById('amount').value) || 0;
        const el     = document.getElementById('conversionResult');

        if (amount <= 0 || btcPrice <= 0) {
            el.innerHTML = '<div class="text-center text-gray-500 dark:text-gray-400 text-xs">Enter an amount to see conversion</div>';
            return;
        }

        let fromLabel, fromVal, toLabel, toVal;
        if (from === 'fiat') {
            fromLabel = currSym + amount.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2}) + ' ' + currCode;
            toVal     = amount / btcPrice;
            toLabel   = toVal.toLocaleString('en-US', {minimumFractionDigits: 8, maximumFractionDigits: 8}) + ' BTC';
        } else {
            fromLabel = amount.toLocaleString('en-US', {minimumFractionDigits: 8, maximumFractionDigits: 8}) + ' BTC';
            toVal     = amount * btcPrice;
            toLabel   = currSym + toVal.toLocaleString('en-US', {minimumFractionDigits: 2, maximumFractionDigits: 2}) + ' ' + currCode;
        }

        el.innerHTML = '<div class="flex items-center justify-between">'
            + '<div class="flex flex-col"><span class="text-xs text-gray-500 dark:text-gray-400">From:</span>'
            + '<span class="font-medium text-gray-900 dark:text-white text-sm">' + fromLabel + '</span></div>'
            + '<i class="fa-solid fa-arrow-right text-gray-400 mx-3"></i>'
            + '<div class="flex flex-col items-end"><span class="text-xs text-gray-500 dark:text-gray-400">To:</span>'
            + '<span class="font-medium text-gray-900 dark:text-white text-sm">' + toLabel + '</span></div>'
            + '</div>';
    }

    document.getElementById('from_currency').addEventListener('change', function() {
        updateCurrencyLabel();
        updateToCurrency();
        calculateConversion();
    });
    document.getElementById('amount').addEventListener('input', calculateConversion);

    // Init
    updateCurrencyLabel();
    updateToCurrency();
})();
</script>

                    </div>
                </main>
<?php include 'footer.php'; ?>
