<?php
require_once "auth.php";
require_once '../db/config.php';
$pdo = db();

// Handle deletion of chat
if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['delete_user_id'])) {
    $del_id = $_GET['delete_user_id'];
    // Delete messages
    $pdo->prepare("DELETE FROM messages WHERE user_id = ?")->execute([$del_id]);
    // Optionally update orders to not show in chat
    $pdo->prepare("UPDATE fiat_orders SET status = 'rejected' WHERE user_id = ? AND status IN ('matching', 'submitting')")->execute([$del_id]);
    header("Location: chat.php");
    exit;
}

$user_id = $_GET['user_id'] ?? null;
$unread_msgs = $pdo->query("SELECT COUNT(*) FROM messages WHERE sender = 'user' AND is_read = 0")->fetchColumn();
$pending_orders = $pdo->query("SELECT COUNT(*) FROM fiat_orders WHERE status IN ('matching', 'submitting')")->fetchColumn();

// Fetch users with messages or active recharge orders
$chat_users = $pdo->query("
    SELECT DISTINCT u.id, u.username, u.uid, 
    (SELECT message FROM messages WHERE user_id = u.id ORDER BY id DESC LIMIT 1) as last_msg,
    (SELECT created_at FROM messages WHERE user_id = u.id ORDER BY id DESC LIMIT 1) as last_time,
    (SELECT COUNT(*) FROM messages WHERE user_id = u.id AND sender = 'user' AND is_read = 0) as unread_count,
    (SELECT status FROM fiat_orders WHERE user_id = u.id AND status IN ('matching', 'submitting') LIMIT 1) as recharge_status
    FROM users u
    JOIN messages m ON u.id = m.user_id
    UNION
    SELECT DISTINCT u.id, u.username, u.uid,
    '发起充值申请' as last_msg,
    o.created_at as last_time,
    0 as unread_count,
    o.status as recharge_status
    FROM users u
    JOIN fiat_orders o ON u.id = o.user_id
    WHERE o.status IN ('matching', 'submitting')
    ORDER BY last_time DESC
")->fetchAll();

?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>客服管理 - NovaEx 管理后台</title>
    <link rel="stylesheet" href="../assets/css/custom.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        .admin-layout { display: flex; min-height: 100vh; }
        .sidebar { width: 250px; background: #1E2329; border-right: 1px solid #2B3139; padding: 1rem; }
        .chat-container { flex: 1; display: flex; background: #0B0E11; height: 100vh; overflow: hidden; }
        .user-list { width: 300px; border-right: 1px solid #2B3139; background: #1E2329; overflow-y: auto; }
        .chat-main { flex: 1; display: flex; flex-direction: column; }
        .menu-item { padding: 12px; color: #848E9C; text-decoration: none; display: flex; align-items: center; gap: 10px; border-radius: 4px; margin-bottom: 5px; }
        .menu-item:hover, .menu-item.active { background: #2B3139; color: white; }
        .badge { background: #f6465d; color: white; border-radius: 10px; padding: 2px 8px; font-size: 0.7rem; margin-left: auto; }
        
        .user-item { padding: 15px; border-bottom: 1px solid #2B3139; cursor: pointer; position: relative; display: flex; flex-direction: column; }
        .user-item:hover, .user-item.active { background: #2B3139; }
        .user-info-row { display: flex; justify-content: space-between; align-items: center; width: 100%; }
        .user-name { font-weight: bold; color: white; font-size: 0.9rem; flex: 1; }
        .delete-btn { color: #848E9C; font-size: 0.9rem; padding: 5px; cursor: pointer; z-index: 10; }
        .delete-btn:hover { color: #f6465d; }
        .last-msg { color: #848E9C; font-size: 0.75rem; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; margin-top: 5px; width: 90%; }
        .dot { width: 10px; height: 10px; background: #f6465d; border-radius: 50%; }
        .recharge-label { font-size: 0.7rem; background: rgba(240, 185, 11, 0.2); color: #f0b90b; padding: 2px 5px; border-radius: 3px; margin-left: 5px; }
        
        .back-btn { color: #848E9C; text-decoration: none; font-size: 0.9rem; padding: 15px; border-bottom: 1px solid #2B3139; display: block; }
        .back-btn:hover { color: white; background: #2B3139; }
        
        /* Custom alert */
        #custom-alert { display: none; position: fixed; top: 20px; right: 20px; background: #f0b90b; color: black; padding: 20px; border-radius: 12px; box-shadow: 0 10px 30px rgba(0,0,0,0.5); z-index: 10000; animation: slideIn 0.5s; width: 300px; }
        @keyframes slideIn { from { transform: translateX(100%); opacity: 0; } to { transform: translateX(0); opacity: 1; } }
    </style>
</head>
<body>
<div id="custom-alert">
    <div style="display: flex; align-items: center; gap: 12px; margin-bottom: 10px;">
        <i class="fas fa-bell fa-lg"></i>
        <strong style="font-size: 1.1rem;">新通知 / NEW NOTIFICATION</strong>
    </div>
    <div id="alert-msg">您有新的充值申请或用户消息。</div>
    <button onclick="location.reload()" style="margin-top: 15px; width: 100%; padding: 8px; background: black; color: white; border: none; border-radius: 6px; cursor: pointer; font-weight: bold;">立即查看</button>
</div>

<div class="admin-layout">
    <div class="sidebar">
        <h3 style="color: white; margin-bottom: 2rem;">NovaEx 管理员</h3>
        <a href="index.php" class="menu-item"><i class="fas fa-chart-pie"></i> 仪表盘</a>
        <a href="users.php" class="menu-item"><i class="fas fa-users"></i> 用户管理</a>
        <a href="kyc.php" class="menu-item"><i class="fas fa-id-card"></i> KYC 审核</a>
        <a href="chat.php" class="menu-item active">
            <i class="fas fa-headset"></i> 客服管理
            <?php if($unread_msgs > 0 || $pending_orders > 0): ?><span class="badge"><?php echo ($unread_msgs + $pending_orders); ?></span><?php endif; ?>
        </a>
        <a href="spot_orders.php" class="menu-item"><i class="fas fa-exchange-alt"></i> 现货交易</a>
        <a href="futures_orders.php" class="menu-item"><i class="fas fa-file-contract"></i> 合约交易</a>
        <a href="orders.php" class="menu-item"><i class="fas fa-wallet"></i> 充值记录</a>
        <a href="withdrawals.php" class="menu-item"><i class="fas fa-hand-holding-usd"></i> 提现记录</a>
        <a href="settings.php" class="menu-item"><i class="fas fa-cog"></i> 系统设置</a>
        <a href="logout.php" class="menu-item"><i class="fas fa-sign-out-alt"></i> 退出登录</a>
    </div>
    
    <div class="chat-container">
        <div class="user-list">
            <a href="index.php" class="back-btn"><i class="fas fa-arrow-left"></i> 返回</a>
            <div style="padding: 15px; color: #848E9C; font-size: 0.8rem; border-bottom: 1px solid #2B3139;">最近联系人 / 充值申请</div>
            <?php foreach($chat_users as $u): ?>
                <div class="user-item <?php echo $user_id == $u['id'] ? 'active' : ''; ?>" onclick="if(event.target.closest('.delete-btn')) return; location.href='chat.php?user_id=<?php echo $u['id']; ?>'">
                    <div class="user-info-row">
                        <div class="user-name">
                            <?php echo htmlspecialchars($u['username']); ?>
                            <?php if($u['recharge_status']): ?><span class="recharge-label">充值申请</span><?php endif; ?>
                        </div>
                        <div style="display: flex; align-items: center; gap: 10px;">
                            <?php if($u['unread_count'] > 0 || $u['recharge_status'] == 'matching'): ?><div class="dot"></div><?php endif; ?>
                            <i class="fas fa-trash delete-btn" title="删除记录" onclick="if(confirm('确定要删除与该用户的聊天及充值申请吗？')) window.location.href='chat.php?action=delete&delete_user_id=<?php echo $u['id']; ?>'"></i>
                        </div>
                    </div>
                    <div class="last-msg"><?php echo htmlspecialchars($u['last_msg']); ?></div>
                </div>
            <?php endforeach; ?>
        </div>
        
        <div class="chat-main">
            <?php if($user_id): ?>
                <iframe src="chat_iframe.php?user_id=<?php echo $user_id; ?>" style="width: 100%; height: 100%; border: none;"></iframe>
            <?php else: ?>
                <div style="flex: 1; display: flex; align-items: center; justify-content: center; color: #5e6673; flex-direction: column;">
                    <i class="fas fa-comments" style="font-size: 4rem; margin-bottom: 20px;"></i>
                    <p>请在左侧选择一个用户或处理中的充值申请</p>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<audio id="notif-sound" src="https://assets.mixkit.co/active_storage/sfx/2869/2869-preview.mp3" preload="auto"></audio>

<script>
let lastTotal = <?php echo ($unread_msgs + $pending_orders); ?>;
function checkNotifications() {
    fetch('../api/get_messages.php?action=count_unread')
        .then(res => res.json())
        .then(data => {
            if (data.total > lastTotal) {
                document.getElementById('notif-sound').play().catch(e => {});
                document.getElementById('custom-alert').style.display = 'block';
                document.getElementById('alert-msg').innerText = "您有新的充值申请或用户消息 (当前未读: " + data.total + ")";
            }
            lastTotal = data.total;
        });
}
setInterval(checkNotifications, 5000);
</script>

</body>
</html>