<?php
require_once 'includes/header.php';

if (!$user) {
    header('Location: login.php');
    exit;
}

$error = '';
$success = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $from_coin = $_POST['from_coin'] ?? 'USDT';
    $to_coin = $_POST['to_coin'] ?? 'BTC';
    $amount = (float)($_POST['amount'] ?? 0);

    if ($amount <= 0) {
        $error = 'Invalid amount.';
    } elseif ($from_coin === $to_coin) {
        $error = 'Cannot exchange same currency.';
    } else {
        try {
            $pdo = db();
            if ($from_coin === 'USDT') {
                if ($user['balance_usdt'] < $amount) {
                    $error = 'Insufficient USDT balance.';
                } else {
                    $rate = 43250.50;
                    if ($to_coin === 'ETH') $rate = 2345.20;
                    if ($to_coin === 'SOL') $rate = 102.45;
                    
                    $receive = $amount / $rate;
                    
                    $pdo->prepare("UPDATE users SET balance_usdt = balance_usdt - ? WHERE id = ?")->execute([$amount, $user['id']]);
                    $success = mt('Successful') . ": " . number_format($receive, 6) . " $to_coin";
                    $user['balance_usdt'] -= $amount;
                }
            } else {
                $error = "Only USDT to Crypto exchange is currently supported.";
            }
        } catch (Exception $e) {
            $error = 'Exchange failed: ' . $e->getMessage();
        }
    }
}
?>

<div class="container my-5 py-5">
    <div class="row justify-content-center">
        <div class="col-md-6">
            <div class="card bg-dark border-secondary p-4 shadow-lg" style="border-radius: 20px;">
                <h2 class="fw-bold mb-4 text-center text-white"><?php echo mt('Exchange'); ?></h2>
                <p class="text-center text-muted mb-4"><?php echo mt('Zero fees'); ?></p>
                
                <?php if ($error): ?>
                    <div class="alert alert-danger"><?php echo $error; ?></div>
                <?php endif; ?>
                <?php if ($success): ?>
                    <div class="alert alert-success"><?php echo $success; ?></div>
                <?php endif; ?>

                <form method="POST">
                    <div class="mb-4">
                        <label class="small text-muted mb-2"><?php echo mt('Amount'); ?></label>
                        <div class="input-group input-group-lg">
                            <input type="number" name="amount" class="form-control bg-dark text-white border-secondary" placeholder="0.00" required step="any">
                            <select name="from_coin" class="btn btn-dark border-secondary">
                                <option value="USDT">USDT</option>
                            </select>
                        </div>
                        <div class="small text-muted mt-2"><?php echo mt('Available'); ?>: <?php echo number_format($user['balance_usdt'], 2); ?> USDT</div>
                    </div>

                    <div class="text-center mb-4">
                        <i class="fas fa-exchange-alt fa-rotate-90 text-muted"></i>
                    </div>

                    <div class="mb-4">
                        <label class="small text-muted mb-2">To</label>
                        <div class="input-group input-group-lg">
                            <input type="text" class="form-control bg-dark text-white border-secondary" placeholder="0.00" readonly id="receive-amount">
                            <select name="to_coin" id="to-coin" class="btn btn-dark border-secondary">
                                <option value="BTC">BTC</option>
                                <option value="ETH">ETH</option>
                                <option value="SOL">SOL</option>
                            </select>
                        </div>
                    </div>

                    <div class="p-3 bg-secondary bg-opacity-10 rounded mb-4">
                        <div class="d-flex justify-content-between small">
                            <span class="text-muted"><?php echo mt('Estimated Price'); ?></span>
                            <span class="text-white fw-bold" id="est-price">1 BTC ≈ 43,250 USDT</span>
                        </div>
                    </div>

                    <button type="submit" class="btn btn-primary w-100 py-3 fw-bold fs-5" style="background-color: var(--okx-blue); border: none; border-radius: 12px;">
                        <?php echo mt('Convert Now'); ?>
                    </button>
                </form>
            </div>
        </div>
    </div>
</div>

<script>
const rates = { 'BTC': 43250.50, 'ETH': 2345.20, 'SOL': 102.45 };
function updateReceive() {
    const amount = document.querySelector('input[name="amount"]').value;
    const coin = document.getElementById('to-coin').value;
    const rate = rates[coin];
    if (amount && rate) {
        document.getElementById('receive-amount').value = (amount / rate).toFixed(6);
        document.getElementById('est-price').innerText = `1 ${coin} ≈ ${rate.toLocaleString()} USDT`;
    }
}
document.querySelector('input[name="amount"]').addEventListener('input', updateReceive);
document.getElementById('to-coin').addEventListener('change', updateReceive);
</script>

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