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

// Handle Actions
if (isset($_POST['action'])) {
    $id = $_POST['order_id'];
    $table = 'fiat_orders';
    
    if ($_POST['action'] == 'match') {
        $info = $_POST['account_info'];
        $pdo->prepare("UPDATE $table SET status = 'matched', bank_account_info = ? 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, usdt_amount FROM $table WHERE id = ?");
        $orderStmt->execute([$id]);
        $order = $orderStmt->fetch();
        if ($order) {
            $credit_amount = $order['usdt_amount'] > 0 ? $order['usdt_amount'] : $order['amount'];
            $pdo->prepare("UPDATE users SET balance = balance + ? WHERE id = ?")->execute([$credit_amount, $order['user_id']]);
            $pdo->prepare("UPDATE $table SET status = 'completed' WHERE id = ?")->execute([$id]);
            
            $msg = "您的充值 " . $credit_amount . " 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]);
    }
}

$all_deposits = $pdo->query("SELECT o.*, u.username, u.uid FROM fiat_orders o JOIN users u ON o.user_id = u.id ORDER BY o.id DESC")->fetchAll();

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="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: #ffffff; border-right: 1px solid #eaecef; padding: 1.5rem; }
        .main-content { flex: 1; padding: 2rem; background: #ffffff; color: #1e2329; overflow-x: auto; }
        .menu-item { padding: 12px 15px; color: #474d57; text-decoration: none; display: flex; align-items: center; gap: 12px; border-radius: 8px; margin-bottom: 8px; transition: 0.2s; }
        .menu-item:hover, .menu-item.active { background: #f5f5f5; color: #f0b90b; font-weight: bold; }
        .badge { background: #f6465d; 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 #eaecef; 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; }
        .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; }
        .back-btn { color: #848E9C; text-decoration: none; font-size: 0.9rem; margin-bottom: 20px; display: inline-block; }
        .btn-primary { background: #f0b90b; color: black; border: none; padding: 8px 15px; border-radius: 6px; font-weight: bold; cursor: pointer; }
    </style>
</head>
<body>
<div class="admin-layout">
    <div class="sidebar">
        <h2 style="color: #f0b90b; margin-bottom: 2rem;">NovaEx Admin</h2>
        <a href="index.php" class="menu-item"><i class="fas fa-home"></i> 仪表盘</a>
        <a href="users.php" class="menu-item"><i class="fas fa-users"></i> 用户管理</a>
        <a href="agents.php" class="menu-item"><i class="fas fa-user-shield"></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-comments"></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="options_orders.php" class="menu-item"><i class="fas fa-clock"></i> 秒合约</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="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="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>换算 USDT</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: #007bff"><?php echo strtoupper($o['currency']); ?></span></td>
                    <td><b><?php echo number_format($o['amount'], 2); ?></b></td>
                    <td><b style="color: #00c087"><?php echo number_format($o['usdt_amount'], 2); ?></b></td>
                    <td>
                        <?php if($o['proof_image']): ?>
                            <a href="../<?php echo $o['proof_image']; ?>" 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="action" value="match">
                                <input type="text" name="account_info" placeholder="收款账户信息" required style="padding: 8px; background: #f9fafb; border: 1px solid #eaecef; border-radius: 4px;">
                                <button type="submit" class="btn-primary" style="background: #ff3c00; color: white;">分配账户</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="action" value="complete">
                                <button type="submit" class="btn-primary" style="background: #00c087; color: white;">确认入金</button>
                            </form>
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
</body>
</html>