<?php
require_once '../db/config.php';
require_once '../includes/currency_helper.php';
session_start();
$pdo = db();

$user_id = $_GET['user_id'] ?? null;
if (!$user_id) die("User ID required");

// Mark as read
$pdo->prepare("UPDATE messages SET is_read = 1 WHERE user_id = ? AND sender = 'user'")->execute([$user_id]);

// Handle Message Sending
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['message'])) {
    $msg = $_POST['message'];
    $pdo->prepare("INSERT INTO messages (user_id, sender, message, type) VALUES (?, 'admin', ?, 'text')")->execute([$user_id, $msg]);
    exit;
}

// Handle Recharge Actions
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action'])) {
    $oid = $_POST['order_id'];
    if ($_POST['action'] == 'match') {
        $bank = $_POST['bank_name'] ?? '';
        $name = $_POST['account_name'] ?? '';
        $number = $_POST['account_number'] ?? '';
        $remarks = $_POST['remarks'] ?? '';
        
        $info = "🏦 银行名称：$bank\n👤 收款姓名：$name\n💳 收款账号：$number\n📝 备注说明：$remarks";
        
        $pdo->prepare("UPDATE fiat_orders SET status = 'matched', bank_account_info = ? WHERE id = ?")->execute([$info, $oid]);
        
        // Send the info as a chat message
        $pdo->prepare("INSERT INTO messages (user_id, sender, message) VALUES (?, 'admin', ?)")->execute([$user_id, $info]);
        
        $notif = "✅ 匹配成功！收款账户已下发。请在页面强制弹窗中查看详细信息并进行转账。";
        $pdo->prepare("INSERT INTO messages (user_id, sender, message) VALUES (?, 'admin', ?)")->execute([$user_id, $notif]);
    } elseif ($_POST['action'] == 'complete') {
        $stmt = $pdo->prepare("SELECT amount, currency, exchange_rate FROM fiat_orders WHERE id = ?");
        $stmt->execute([$oid]);
        $order = $stmt->fetch();
        $amt = $order['amount'];
        $cur = $order['currency'];
        
        $fiat_rates = get_fiat_rates();
        $real_time_rate = $fiat_rates[$cur] ?? $order['exchange_rate'];
        $usdt_amt = ($real_time_rate > 0) ? ($amt / $real_time_rate) : $amt;
        
        $pdo->prepare("UPDATE users SET balance = balance + ? WHERE id = ?")->execute([$usdt_amt, $user_id]);
        $pdo->prepare("UPDATE fiat_orders SET status = 'completed', usdt_amount = ?, exchange_rate = ? WHERE id = ?")
            ->execute([$usdt_amt, $real_time_rate, $oid]);
        
        $notif = "🎉 充值已确认到账！\n金额：" . number_format($amt, 2) . " $cur\n实时汇率：1 USDT = " . number_format($real_time_rate, 4) . " $cur\n入账：" . number_format($usdt_amt, 2) . " USDT";
        $pdo->prepare("INSERT INTO messages (user_id, sender, message) VALUES (?, 'admin', ?)")->execute([$user_id, $notif]);
    } elseif ($_POST['action'] == 'reject') {
        $pdo->prepare("UPDATE fiat_orders SET status = 'rejected' WHERE id = ?")->execute([$oid]);
        $pdo->prepare("INSERT INTO messages (user_id, sender, message) VALUES (?, 'admin', ?)")->execute([$user_id, "❌ 您的充值申请 #$oid 已被拒绝。"]);
    }
}

$user = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$user->execute([$user_id]);
$userData = $user->fetch();

$messages = $pdo->prepare("SELECT * FROM messages WHERE user_id = ? ORDER BY created_at ASC");
$messages->execute([$user_id]);
$msgs = $messages->fetchAll();

$orders = $pdo->prepare("SELECT * FROM fiat_orders WHERE user_id = ? AND status IN ('matching', 'submitting', 'matched') ORDER BY id DESC");
$orders->execute([$user_id]);
$pending_orders = $orders->fetchAll();

$current_rates = get_fiat_rates();
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        body { margin: 0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, Helvetica, Arial, sans-serif; background: #0B0E11; color: white; display: flex; flex-direction: column; height: 100vh; overflow: hidden; }
        .chat-header { padding: 15px 20px; background: #1E2329; border-bottom: 1px solid #2B3139; display: flex; justify-content: space-between; align-items: center; z-index: 10; }
        .main-content { flex: 1; display: flex; flex-direction: column; overflow-y: auto; }
        .chat-box { flex: 1; padding: 20px; display: flex; flex-direction: column; gap: 15px; }
        .msg { max-width: 85%; padding: 12px 16px; border-radius: 12px; font-size: 14px; line-height: 1.6; position: relative; }
        .msg.admin { align-self: flex-end; background: #f0b90b; color: black; border-bottom-right-radius: 2px; }
        .msg.user { align-self: flex-start; background: #2B3139; color: #EAECEF; border-bottom-left-radius: 2px; }
        .msg-time { font-size: 10px; color: #848E9C; margin-top: 5px; display: block; text-align: right; }
        .recharge-panel { background: #1E2329; border-bottom: 1px solid #2B3139; padding: 15px 20px; }
        .order-card { background: #161A1E; border: 1px solid #2B3139; border-radius: 16px; padding: 15px; margin-bottom: 12px; }
        .input-area { padding: 15px 20px; background: #1E2329; border-top: 1px solid #2B3139; display: flex; gap: 12px; }
        input[type="text"], input[type="number"], textarea { width: 100%; background: #0B0E11; border: 1px solid #2B3139; color: white; padding: 10px; border-radius: 8px; outline: none; margin-bottom: 8px; font-size: 13px; }
        button { background: #f0b90b; border: none; color: black; padding: 10px 20px; border-radius: 8px; cursor: pointer; font-weight: bold; }
        .status-badge { font-size: 10px; padding: 4px 10px; border-radius: 6px; font-weight: 800; }
        .matching { background: rgba(240, 185, 11, 0.1); color: #f0b90b; }
        .submitting { background: rgba(0, 192, 135, 0.1); color: #00c087; }
        .btn-complete { background: #00c087; color: white; }
        .btn-reject { background: #f6465d; color: white; }
    </style>
</head>
<body>

<div class="chat-header">
    <div>
        <span style="font-weight: 800;"><?php echo htmlspecialchars($userData['username'] ?? 'User'); ?></span>
        <span style="color: #848E9C; font-size: 11px; margin-left: 8px;">UID: <?php echo $userData['uid'] ?? 'N/A'; ?></span>
        <span style="color: #848E9C; font-size: 11px; margin-left: 8px;">IP: <?php echo $userData['last_ip'] ?: '127.0.0.1'; ?></span>
    </div>
    <div style="text-align: right;">
        <div style="font-size: 11px; color: #848E9C;">余额: <span style="color: #00c087;"><?php echo number_format($userData['balance'] ?? 0, 2); ?> USDT</span></div>
    </div>
</div>

<div class="main-content">
    <?php if (!empty($pending_orders)): ?>
    <div class="recharge-panel">
        <div style="font-weight: bold; color: #F0B90B; margin-bottom: 10px; font-size: 12px;">待处理充值</div>
        <?php foreach($pending_orders as $o):
            $is_matching = ($o['status'] == 'matching');
            $live_rate = $current_rates[$o['currency']] ?? $o['exchange_rate'];
            $live_usdt = ($live_rate > 0) ? ($o['amount'] / $live_rate) : $o['amount'];
        ?>
            <div class="order-card">
                <div style="display: flex; justify-content: space-between; margin-bottom: 10px;">
                    <div>
                        <div style="font-size: 1rem; font-weight: 900;"><?php echo number_format($o['amount'], 2); ?> <?php echo $o['currency']; ?></div>
                        <div style="font-size: 11px; color: #848E9C;">≈ <?php echo number_format($live_usdt, 2); ?> USDT (汇率: <?php echo number_format($live_rate, 4); ?>)</div>
                    </div>
                    <span class="status-badge <?php echo $o['status']; ?>">
                        <?php 
                            if($o['status'] == 'matching') echo '等待分配账户';
                            elseif($o['status'] == 'matched') echo '已分配/待支付';
                            elseif($o['status'] == 'submitting') echo '已提交凭证';
                        ?>
                    </span>
                </div>
                
                <?php if($is_matching): ?>
                    <form method="POST">
                        <input type="hidden" name="order_id" value="<?php echo $o['id']; ?>">
                        <input type="hidden" name="action" value="match">
                        <input type="text" name="bank_name" placeholder="银行名称 (如: 中国工商银行)" required>
                        <input type="text" name="account_name" placeholder="收款人姓名" required>
                        <input type="text" name="account_number" placeholder="银行账号" required>
                        <textarea name="remarks" placeholder="注意事项 (可选)" style="height: 50px;"></textarea>
                        <button type="submit" style="width: 100%;">确认匹配账户</button>
                    </form>
                <?php else:
                ?>
                    <div style="background: rgba(255,255,255,0.03); padding: 10px; border-radius: 8px; margin-bottom: 10px; font-size: 12px;">
                        <?php echo nl2br(htmlspecialchars($o['bank_account_info'])); ?>
                    </div>
                    <div style="display: flex; gap: 10px; align-items: center;">
                        <?php if($o['proof_image']): ?>
                            <a href="../<?php echo $o['proof_image']; ?>" target="_blank" style="color: #00c087; font-size: 12px; text-decoration: none; border: 1px solid #00c087; padding: 5px 10px; border-radius: 5px;">查看凭证</a>
                        <?php endif; ?>
                        <div style="flex: 1; display: flex; gap: 5px; justify-content: flex-end;">
                            <form method="POST">
                                <input type="hidden" name="order_id" value="<?php echo $o['id']; ?>">
                                <input type="hidden" name="action" value="complete">
                                <button type="submit" class="btn-complete" style="padding: 5px 10px; font-size: 12px;">同意</button>
                            </form>
                            <form method="POST">
                                <input type="hidden" name="order_id" value="<?php echo $o['id']; ?>">
                                <input type="hidden" name="action" value="reject">
                                <button type="submit" class="btn-reject" style="padding: 5px 10px; font-size: 12px;">拒绝</button>
                            </form>
                        </div>
                    </div>
                <?php endif; ?>
            </div>
        <?php endforeach; ?>
    </div>
    <?php endif; ?>

    <div class="chat-box" id="chat-box">
        <?php foreach($msgs as $m): ?>
            <?php if (strpos($m['message'], '[RECHARGE_NOTIFICATION]') !== false):
            ?>
                <div style="align-self: center; background: rgba(240, 185, 11, 0.1); color: #f0b90b; padding: 10px 20px; border-radius: 10px; font-size: 12px; border: 1px dashed #f0b90b; margin: 10px 0; text-align: center;">
                    <i class="fas fa-bell"></i> <?php echo nl2br(htmlspecialchars($m['message'])); ?>
                </div>
            <?php else:
            ?>
                <div class="msg <?php echo $m['sender']; ?>">
                    <?php if ($m['type'] === 'image'): ?>
                        <img src="../<?php echo $m['message']; ?>" style="max-width: 100%; border-radius: 8px; cursor: pointer;" onclick="window.open(this.src)">
                    <?php else:
                    ?>
                        <?php echo nl2br(htmlspecialchars($m['message'])); ?>
                    <?php endif;
                    ?>
                    <span class="msg-time"><?php echo date('H:i', strtotime($m['created_at'])); ?></span>
                </div>
            <?php endif;
            ?>
        <?php endforeach;
        ?>
    </div>
</div>

<form class="input-area" id="msg-form">
    <input type="text" id="msg-input" placeholder="输入消息..." autocomplete="off">
    <button type="submit"><i class="fas fa-paper-plane"></i></button>
</form>

<script>
    const chatBox = document.getElementById('chat-box');
    chatBox.scrollTop = chatBox.scrollHeight;

    document.getElementById('msg-form').onsubmit = async (e) => {
        e.preventDefault();
        const input = document.getElementById('msg-input');
        const msg = input.value.trim();
        if (!msg) return;

        const formData = new FormData();
        formData.append('message', msg);
        input.value = '';
        
        const msgDiv = document.createElement('div');
        msgDiv.className = 'msg admin';
        msgDiv.innerHTML = msg.replace(/\n/g, '<br>') + `<span class="msg-time">${new Date().getHours()}:${new Date().getMinutes()}</span>`;
        chatBox.appendChild(msgDiv);
        chatBox.scrollTop = chatBox.scrollHeight;

        await fetch(window.location.href, { method: 'POST', body: formData });
    };

    let lastCount = <?php echo count($msgs); ?>;
    setInterval(async () => {
        const res = await fetch('../api/get_messages.php?user_id=<?php echo $user_id; ?>');
        const data = await res.json();
        if (data && data.count > lastCount) {
            location.reload();
        }
    }, 4000);
</script>

</body>
</html>