<?php
require_once "auth.php";
require_once '../db/config.php';
require_once '../includes/currency_helper.php';
$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]);
        $pdo->prepare("INSERT INTO messages (user_id, sender, message) VALUES (?, 'admin', ?)")->execute([$user_id, $info]);
        $pdo->prepare("INSERT INTO messages (user_id, sender, message) VALUES (?, 'admin', ?)")->execute([$user_id, "✅ 匹配成功！收款账户已下发。"]);
    } elseif ($_POST['action'] == 'complete') {
        $stmt = $pdo->prepare("SELECT amount, currency FROM fiat_orders WHERE id = ?");
        $stmt->execute([$oid]);
        $order = $stmt->fetch();
        $pdo->prepare("UPDATE users SET balance = balance + ? WHERE id = ?")->execute([$order['amount'], $user_id]);
        $pdo->prepare("UPDATE fiat_orders SET status = 'completed' WHERE id = ?")->execute([$oid]);
        $pdo->prepare("INSERT INTO messages (user_id, sender, message) VALUES (?, 'admin', ?)")->execute([$user_id, "🎉 充值已确认到账！"]);
    } elseif ($_POST['action'] == 'reject') {
        $pdo->prepare("UPDATE fiat_orders SET status = 'rejected' WHERE id = ?")->execute([$oid]);
    }
}

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

$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();
?>
<!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: sans-serif; background: #0B0E11; color: white; display: flex; flex-direction: column; height: 100vh; overflow: hidden; }
        .chat-header { padding: 10px 15px; background: #1E2329; border-bottom: 1px solid #2B3139; display: flex; justify-content: space-between; font-size: 13px; }
        #chat-box { flex: 1; padding: 15px; display: flex; flex-direction: column; gap: 12px; overflow-y: auto; scroll-behavior: smooth; }
        .msg { max-width: 85%; padding: 10px 14px; border-radius: 12px; font-size: 13px; line-height: 1.5; }
        .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; }
        .input-area { padding: 12px; background: #1E2329; border-top: 1px solid #2B3139; display: flex; gap: 10px; }
        input { flex: 1; background: #0B0E11; border: 1px solid #2B3139; color: white; padding: 10px; border-radius: 6px; outline: none; }
        button { background: #f0b90b; border: none; color: black; padding: 8px 15px; border-radius: 6px; cursor: pointer; font-weight: bold; }
        .order-card { background: #161A1E; border: 1px solid #2B3139; padding: 12px; border-radius: 10px; margin: 10px; font-size: 12px; }
    </style>
</head>
<body>

<div class="chat-header">
    <span><b><?php echo htmlspecialchars($userData['username'] ?? ''); ?></b> (UID: <?php echo $userData['uid'] ?? ''; ?>)</span>
    <span>Balance: <?php echo number_format($userData['balance'] ?? 0, 2); ?> USDT</span>
</div>

<div style="flex: 1; display: flex; flex-direction: column; overflow: hidden;">
    <?php if ($pending_orders): ?>
    <div style="background: #1E2329; border-bottom: 1px solid #2B3139; max-height: 200px; overflow-y: auto;">
        <?php foreach($pending_orders as $o):
        ?>
            <div class="order-card">
                <div style="display:flex; justify-content: space-between; margin-bottom:8px;">
                    <b style="color:#f0b90b;"><?php echo $o['amount']; ?> <?php echo $o['currency']; ?></b>
                    <span style="opacity:0.6;"><?php echo $o['status']; ?></span>
                </div>
                <?php if($o['status'] == 'matching'): ?>
                    <form method="POST" style="display:grid; grid-template-columns: 1fr 1fr; gap:5px;">
                        <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="Bank" required>
                        <input type="text" name="account_name" placeholder="Name" required>
                        <input type="text" name="account_number" placeholder="Number" required style="grid-column: span 2;">
                        <button type="submit" style="grid-column: span 2;">Match Account</button>
                    </form>
                <?php else:
                ?>
                    <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;">View Proof</a>
                        <?php endif;
                        ?>
                        <form method="POST" style="flex:1; display:flex; gap:5px;">
                            <input type="hidden" name="order_id" value="<?php echo $o['id']; ?>">
                            <input type="hidden" name="action" value="complete">
                            <button type="submit" style="flex:1; background:#00c087; color:white;">Approve</button>
                        </form>
                        <form method="POST" style="flex:1;">
                            <input type="hidden" name="order_id" value="<?php echo $o['id']; ?>">
                            <input type="hidden" name="action" value="reject">
                            <button type="submit" style="flex:1; background:#f6465d; color:white;">Reject</button>
                        </form>
                    </div>
                <?php endif;
                ?>
            </div>
        <?php endforeach;
        ?>
    </div>
    <?php endif;
    ?>

    <div id="chat-box"></div>
</div>

<form class="input-area" id="msg-form">
    <input type="text" id="msg-input" placeholder="Type a message..." autocomplete="off">
    <button type="submit"><i class="fas fa-paper-plane"></i></button>
</form>

<script>
    const chatBox = document.getElementById('chat-box');
    const msgInput = document.getElementById('msg-input');
    
    async function loadMessages() {
        try {
            const resp = await fetch('../api/get_messages.php?user_id=<?php echo $user_id; ?>');
            const res = await resp.json();
            if (res.success) {
                let html = '';
                res.data.forEach(m => {
                    html += `
                        <div class="msg ${m.sender}">
                            ${m.type === 'image' ? `<img src="../${m.message}" style="max-width:100%; border-radius:8px; cursor:pointer;" onclick="window.open(this.src)">` : m.message.replace(/\n/g, '<br>')}
                            <span class="msg-time">${new Date(m.created_at).toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})}</span>
                        </div>
                    `;
                });
                const isAtBottom = chatBox.scrollHeight - chatBox.scrollTop <= chatBox.clientHeight + 50;
                chatBox.innerHTML = html;
                if (isAtBottom) chatBox.scrollTop = chatBox.scrollHeight;
            }
        } catch (e) {}
    }

    document.getElementById('msg-form').onsubmit = async (e) => {
        e.preventDefault();
        const msg = msgInput.value.trim();
        if (!msg) return;
        msgInput.value = '';
        const formData = new FormData();
        formData.append('message', msg);
        await fetch(window.location.href, { method: 'POST', body: formData });
        loadMessages();
    };

    loadMessages();
    setInterval(loadMessages, 2000);
</script>
</body>
</html>