<?php
include 'header.php';

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

require_once 'db/config.php';
require_once 'includes/currency_helper.php';

$db = db();
$stmt = $db->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$_SESSION['user_id']]);
$user = $stmt->fetch();

$fiat_rates = get_fiat_rates();
$fiat_currencies_info = [
    'USD' => 'US Dollar', 'EUR' => 'Euro', 'GBP' => 'British Pound', 'CNY' => 'Chinese Yuan', 'HKD' => 'Hong Kong Dollar', 'JPY' => 'Japanese Yen', 'KRW' => 'Korean Won', 'SGD' => 'Singapore Dollar', 'TWD' => 'Taiwan Dollar', 'THB' => 'Thai Baht', 'VND' => 'Vietnamese Dong', 'IDR' => 'Indonesian Rupiah', 'MYR' => 'Malaysian Ringgit',
];

$error = '';

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $type = $_POST['type'] ?? 'usdt';
    $amount = (float)($_POST['amount'] ?? 0);
    $currency = $_POST['currency'] ?? 'USDT';
    $trading_pass = $_POST['trading_password'] ?? '';
    $address = $_POST['address'] ?? '';
    $network = $_POST['network'] ?? '';

    if ($trading_pass !== $user['trading_password']) {
        $error = "Incorrect trading password / 交易密码错误";
    } elseif ($amount > $user['balance']) {
        $error = "Insufficient balance / 余额不足";
    } elseif ($amount < 10) {
        $error = "Minimum withdrawal amount is 10 USDT / 最低提现金额为 10 USDT";
    } else {
        $db->beginTransaction();
        try {
            // Deduct balance
            $stmt = $db->prepare("UPDATE users SET balance = balance - ? WHERE id = ?");
            $stmt->execute([$amount, $_SESSION['user_id']]);
            
            // Log withdrawal order
            $info = ($type === 'usdt') ? "USDT Network: $network, Address: $address" : "Fiat Currency: $currency";
            $stmt = $db->prepare("INSERT INTO orders (user_id, type, amount, currency, account_info, status) VALUES (?, ?, ?, ?, ?, 'pending')");
            $stmt->execute([$_SESSION['user_id'], $type, $amount, $currency, $info]);
            $order_id = $db->lastInsertId();
            
            // Insert notification message for chat
            $method_info = ($type === 'usdt') ? "USDT ($network)" : "法币 ($currency)";
            $msg = "👈 用户申请提现，金额 $amount USDT\n订单号: #$order_id\n方式: $method_info\n详情: $info\n请及时处理。";
            $stmt = $db->prepare("INSERT INTO messages (user_id, sender, message) VALUES (?, 'user', ?)");
            $stmt->execute([$_SESSION['user_id'], $msg]);
            
            $db->commit();
            // Redirect to chat with a flag to show a toast or message
            echo "<script>alert('".__('withdraw_tip')."'); location.href='chat.php';</script>";
            exit;
        } catch (Exception $e) {
            $db->rollBack();
            $error = "System error, please try again later / 系统错误，请稍后再试";
        }
    }
}
?>

<main style="padding: 40px 20px; background: #0b0e11; min-height: calc(100vh - 64px);">
    <div style="max-width: 1000px; margin: 0 auto;">
        
        <a href="profile.php" class="back-btn"><i class="fas fa-arrow-left"></i> <?php echo __('nav_profile'); ?></a>

        <div style="margin-bottom: 40px;">
            <h1 style="font-size: 2.5rem; font-weight: bold; margin-bottom: 10px;"><?php echo __('nav_withdraw'); ?></h1>
            <p style="color: var(--text-muted);"><?php echo __('withdraw_method_tip', '请选择您偏好的提现方式'); ?></p>
        </div>

        <?php if($error): ?>
            <div style="background: rgba(246,70,93,0.1); color: var(--danger-color); padding: 15px; border-radius: 8px; margin-bottom: 20px; border: 1px solid var(--danger-color);">
                <i class="fas fa-exclamation-circle"></i> <?php echo $error; ?>
            </div>
        <?php endif; ?>

        <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 30px; margin-bottom: 40px;">
            <div id="card-fiat" style="background: var(--card-bg); padding: 35px; border-radius: 24px; border: 2px solid transparent; cursor: pointer;" onclick="switchMethod('fiat')">
                <div style="display: flex; align-items: center; gap: 20px; margin-bottom: 25px;">
                    <div style="width: 60px; height: 60px; background: rgba(0, 82, 255, 0.1); border-radius: 16px; display: flex; align-items: center; justify-content: center; color: var(--primary-color); font-size: 24px;">
                        <i class="fas fa-university"></i>
                    </div>
                    <div>
                        <h3 style="margin: 0;"><?php echo __('fiat_withdraw', '法币提现'); ?></h3>
                        <p style="margin: 5px 0 0; color: var(--text-muted); font-size: 14px;"><?php echo __('bank_transfer', '银行转账 / OTC'); ?></p>
                    </div>
                </div>
            </div>

            <div id="card-usdt" style="background: var(--card-bg); padding: 35px; border-radius: 24px; border: 2px solid var(--success-color); cursor: pointer;" onclick="switchMethod('usdt')">
                <div style="display: flex; align-items: center; gap: 20px; margin-bottom: 25px;">
                    <div style="width: 60px; height: 60px; background: rgba(14, 203, 129, 0.1); border-radius: 16px; display: flex; align-items: center; justify-content: center; color: var(--success-color); font-size: 24px;">
                        <i class="fas fa-coins"></i>
                    </div>
                    <div>
                        <h3 style="margin: 0;"><?php echo __('crypto_withdraw', '数字货币提现'); ?></h3>
                        <p style="margin: 5px 0 0; color: var(--text-muted); font-size: 14px;">Blockchain Transfer</p>
                    </div>
                </div>
            </div>
        </div>

        <div style="background: var(--card-bg); padding: 40px; border-radius: 24px; border: 1px solid var(--border-color);">
            <form method="POST">
                <input type="hidden" name="type" id="withdraw-type" value="usdt">
                
                <div id="fiat-options" style="display: none; margin-bottom: 25px;">
                    <label style="display: block; margin-bottom: 12px; color: var(--text-muted); font-size: 14px;"><?php echo __('select_currency', '选择币种'); ?></label>
                    <select name="currency" style="width: 100%; padding: 15px; background: #161a1e; border: 1px solid var(--border-color); color: white; border-radius: 12px; font-size: 1rem; outline: none;">
                        <?php foreach ($fiat_rates as $code => $rate): ?>
                            <option value="<?php echo $code; ?>"><?php echo $code; ?> - <?php echo $fiat_currencies_info[$code] ?? $code; ?></option>
                        <?php endforeach; ?>
                    </select>
                </div>

                <div id="usdt-options" style="margin-bottom: 25px;">
                    <div style="margin-bottom: 25px;">
                        <label style="display: block; margin-bottom: 12px; color: var(--text-muted); font-size: 14px;">Select Network</label>
                        <select name="network" style="width: 100%; padding: 15px; background: #161a1e; border: 1px solid var(--border-color); color: white; border-radius: 12px; outline: none;">
                            <option value="TRC20">USDT - TRC20 (Recommended)</option>
                            <option value="ERC20">USDT - ERC20</option>
                            <option value="BEP20">USDT - BEP20 (BSC)</option>
                        </select>
                    </div>
                    <div style="margin-bottom: 25px;">
                        <label style="display: block; margin-bottom: 12px; color: var(--text-muted); font-size: 14px;"><?php echo __('withdraw_address'); ?></label>
                        <input type="text" name="address" placeholder="Paste your USDT wallet address" style="width: 100%; padding: 15px; background: #161a1e; border: 1px solid var(--border-color); color: white; border-radius: 12px; outline: none;">
                    </div>
                </div>

                <div style="margin-bottom: 25px;">
                    <label style="display: block; margin-bottom: 12px; color: var(--text-muted); font-size: 14px;"><?php echo __('withdraw_amount'); ?> (USDT)</label>
                    <div style="position: relative;">
                        <input type="number" name="amount" id="amount-input" placeholder="<?php echo __('min_withdraw'); ?>: 10" step="0.01" required style="width: 100%; padding: 15px; background: #161a1e; border: 1px solid var(--border-color); color: white; border-radius: 12px; font-size: 1.2rem; font-weight: bold; outline: none;">
                        <span onclick="document.getElementById('amount-input').value = '<?php echo $user['balance']; ?>'" style="position: absolute; right: 20px; top: 50%; transform: translateY(-50%); color: var(--primary-color); font-weight: bold; cursor: pointer; font-size: 14px;"><?php echo __('withdraw_all'); ?></span>
                    </div>
                    <div style="margin-top: 10px; font-size: 13px; color: var(--text-muted);">
                        <?php echo __('available'); ?>: <span style="color: white; font-weight: bold;"><?php echo number_format($user['balance'], 2); ?> USDT</span>
                    </div>
                </div>

                <div style="margin-bottom: 35px;">
                    <label style="display: block; margin-bottom: 12px; color: var(--text-muted); font-size: 14px;"><?php echo __('fund_password'); ?></label>
                    <input type="password" name="trading_password" placeholder="Enter 6-digit trading password" required style="width: 100%; padding: 15px; background: #161a1e; border: 1px solid var(--border-color); color: white; border-radius: 12px; outline: none;">
                </div>

                <button type="submit" class="btn-primary" style="width: 100%; padding: 18px; font-size: 1.1rem; border-radius: 12px; background: var(--danger-color);">
                    <?php echo __('withdraw_submit'); ?>
                </button>
            </form>
        </div>
    </div>
</main>

<script>
    function switchMethod(method) {
        if(method === 'fiat') {
            document.getElementById('fiat-options').style.display = 'block';
            document.getElementById('usdt-options').style.display = 'none';
            document.getElementById('card-fiat').style.borderColor = 'var(--primary-color)';
            document.getElementById('card-usdt').style.borderColor = 'transparent';
            document.getElementById('withdraw-type').value = 'fiat';
        } else {
            document.getElementById('fiat-options').style.display = 'none';
            document.getElementById('usdt-options').style.display = 'block';
            document.getElementById('card-fiat').style.borderColor = 'transparent';
            document.getElementById('card-usdt').style.borderColor = 'var(--success-color)';
            document.getElementById('withdraw-type').value = 'usdt';
        }
    }
</script>

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