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

// Handle Actions
if (isset($_POST['action'])) {
    $id = $_POST['order_id'];
    $table = $_POST['order_table'] === 'fiat' ? 'fiat_orders' : 'orders';
    
    if ($_POST['action'] == 'match') {
        $info = $_POST['account_info'];
        $column = ($table === 'fiat_orders') ? 'bank_account_info' : 'account_info';
        $pdo->prepare("UPDATE $table SET status = 'matched', $column = ? WHERE id = ?")->execute([$info, $id]);
        
        $orderStmt = $pdo->prepare("SELECT user_id FROM $table WHERE id = ?");
        $orderStmt->execute([$id]);
        $order = $orderStmt->fetch();
        if ($order) {
            $msg = "您的充值订单 #$id 匹配成功。请刷新支付页面查看收款账户详情并按要求完成转账。";
            $pdo->prepare("INSERT INTO messages (user_id, sender, message) VALUES (?, 'admin', ?)")->execute([$order['user_id'], $msg]);
        }
    } elseif ($_POST['action'] == 'complete') {
        $orderStmt = $pdo->prepare("SELECT user_id, amount, currency FROM $table WHERE id = ?");
        $orderStmt->execute([$id]);
        $order = $orderStmt->fetch();
        if ($order) {
            $pdo->prepare("UPDATE users SET balance = balance + ? WHERE id = ?")->execute([$order['amount'], $order['user_id']]);
            $pdo->prepare("UPDATE $table SET status = 'completed' WHERE id = ?")->execute([$id]);
            
            $msg = "您的充值 " . $order['amount'] . " " . ($order['currency'] ?? 'USDT') . " 已确认到账。";
            $pdo->prepare("INSERT INTO messages (user_id, sender, message) VALUES (?, 'admin', ?)")->execute([$order['user_id'], $msg]);
        }
    } elseif ($_POST['action'] == 'reject') {
        $pdo->prepare("UPDATE $table SET status = 'rejected' WHERE id = ?")->execute([$id]);
    }
}

$fiat_orders = $pdo->query("SELECT o.*, u.username, u.uid, 'fiat' as tbl FROM fiat_orders o JOIN users u ON o.user_id = u.id ORDER BY o.id DESC")->fetchAll();
$usdt_orders = $pdo->query("SELECT o.*, u.username, u.uid, 'usdt' as tbl FROM orders o JOIN users u ON o.user_id = u.id ORDER BY o.id DESC")->fetchAll();
$all_deposits = array_merge($fiat_orders, $usdt_orders);

usort($all_deposits, function($a, $b) {
    $priority = ['matching' => 3, 'submitting' => 2, 'pending' => 2, 'matched' => 1, 'completed' => 0];
    $pA = $priority[$a['status']] ?? 0;
    $pB = $priority[$b['status']] ?? 0;
    if ($pA != $pB) return $pB - $pA;
    return $b['id'] - $a['id'];
});

$unread_msgs = $pdo->query("SELECT COUNT(*) FROM messages WHERE sender = 'user' AND is_read = 0")->fetchColumn();
$pending_orders_count = $pdo->query("SELECT COUNT(*) FROM fiat_orders WHERE status IN ('matching', 'submitting')")->fetchColumn();
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>充值管理 - NovaEx 管理后台</title>
    <link rel="icon" type="image/png" href="../assets/pasted-20260211-152742-c4035b1b.png">
    <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; }
        .main-content { flex: 1; padding: 2rem; background: #0B0E11; color: white; overflow-x: auto; }
        .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: var(--danger-color); color: white; border-radius: 10px; padding: 2px 8px; font-size: 0.7rem; margin-left: auto; }
        .table { width: 100%; border-collapse: collapse; margin-top: 1rem; margin-bottom: 3rem; }
        .table th, .table td { padding: 12px; text-align: left; border-bottom: 1px solid #2B3139; font-size: 0.85rem; }
        .status-badge { padding: 3px 8px; border-radius: 4px; font-size: 0.75rem; font-weight: bold; }
        .matching { background: rgba(255, 60, 0, 0.2); color: #ff3c00; border: 1px solid #ff3c00; animation: blink 1s infinite; }
        .submitting { background: rgba(0, 192, 135, 0.2); color: #00c087; border: 1px solid #00c087; }
        .matched { background: rgba(55, 122, 255, 0.1); color: #377aff; }
        .completed { background: rgba(0, 192, 135, 0.1); color: #00c087; opacity: 0.6; }
        @keyframes blink { 0% { opacity: 1; } 50% { opacity: 0.5; } 100% { opacity: 1; } }
        .back-btn { color: #848E9C; text-decoration: none; font-size: 0.9rem; margin-bottom: 20px; display: inline-block; }
        .admin-logo { width: 200px; height: 80px; object-fit: contain; }
    </style>
</head>
<body>
<div class="admin-layout">
    <div class="sidebar">
        <div style="display: flex; flex-direction: column; align-items: center; margin-bottom: 2rem; gap: 10px;">
            <img src="../assets/pasted-20260211-152742-c4035b1b.png" alt="Logo" class="admin-logo">
            <div style="color: white; font-weight: bold; font-size: 0.9rem;">NovaEx 管理员</div>
        </div>
        <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">
            <i class="fas fa-headset"></i> 客服管理
            <?php if($unread_msgs > 0 || $pending_orders_count > 0): ?><span class="badge"><?php echo ($unread_msgs + $pending_orders_count); ?></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 active"><i class="fas fa-wallet"></i> 充值记录</a>
        <a href="settings.php" class="menu-item"><i class="fas fa-cog"></i> 系统设置</a>
    </div>
    <div class="main-content">
        <a href="index.php" class="back-btn"><i class="fas fa-arrow-left"></i> 返回</a>
        <h2>充值申请管理</h2>
        
        <table class="table">
            <thead>
                <tr>
                    <th>ID</th><th>用户</th><th>类型</th><th>金额</th><th>凭证</th><th>状态</th><th>操作</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach($all_deposits as $o): ?>
                <tr>
                    <td>#<?php echo $o['id']; ?></td>
                    <td><?php echo htmlspecialchars($o['username']); ?> (UID: <?php echo $o['uid']; ?>)</td>
                    <td><span style="color: <?php echo $o['tbl'] == 'usdt' ? '#26a17b' : '#007bff'; ?>"><?php echo strtoupper($o['tbl']); ?></span></td>
                    <td><b><?php echo number_format($o['amount'], 2); ?> <?php echo $o['currency']; ?></b></td>
                    <td>
                        <?php 
                        $img = ($o['tbl'] == 'fiat' ? ($o['proof_image'] ?? null) : ($o['proof_img'] ?? null));
                        if($img): ?>
                            <a href="../<?php echo $img; ?>" target="_blank" style="color: #00c087; font-weight: bold;"><i class="fas fa-image"></i> 查看凭证</a>
                        <?php else: ?>
                            <span style="color: #555;">未上传</span>
                        <?php endif; ?>
                    </td>
                    <td><span class="status-badge <?php echo $o['status']; ?>"><?php echo strtoupper($o['status']); ?></span></td>
                    <td>
                        <?php if($o['status'] == 'matching'): ?>
                            <form method="POST" style="display: flex; gap: 5px;">
                                <input type="hidden" name="order_id" value="<?php echo $o['id']; ?>">
                                <input type="hidden" name="order_table" value="<?php echo $o['tbl']; ?>">
                                <input type="hidden" name="action" value="match">
                                <input type="text" name="account_info" placeholder="收款账户信息" required style="padding: 8px; background: #1e2329; border: 1px solid #2b3139; color: white; border-radius: 4px;">
                                <button type="submit" class="btn-primary" style="background: #ff3c00;">分配账户</button>
                            </form>
                        <?php elseif($o['status'] == 'submitting' || $o['status'] == 'matched'): ?>
                            <form method="POST">
                                <input type="hidden" name="order_id" value="<?php echo $o['id']; ?>">
                                <input type="hidden" name="order_table" value="<?php echo $o['tbl']; ?>">
                                <input type="hidden" name="action" value="complete">
                                <button type="submit" class="btn-primary" style="background: #00c087;">确认入金</button>
                            </form>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
</body>
</html>