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

$success_msg = "";
$error_msg = "";

// Handle Actions
if (isset($_POST['action'])) {
    $id = $_POST['order_id'];
    
    if ($_POST['action'] == 'complete') {
        $pdo->prepare("UPDATE orders SET status = 'completed' WHERE id = ?")->execute([$id]);
        
        $orderStmt = $pdo->prepare("SELECT user_id, amount, currency FROM orders WHERE id = ?");
        $orderStmt->execute([$id]);
        $order = $orderStmt->fetch();
        if ($order) {
            $msg = "您的提现 " . $order['amount'] . " " . ($order['currency'] ?? 'USDT') . " 已汇出，请查收。";
            $pdo->prepare("INSERT INTO messages (user_id, sender, message) VALUES (?, 'admin', ?)")->execute([$order['user_id'], $msg]);
        }
        $success_msg = "确认成功，提现已处理。";
    } elseif ($_POST['action'] == 'reject') {
        $orderStmt = $pdo->prepare("SELECT user_id, amount FROM orders 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 orders SET status = 'rejected' WHERE id = ?")->execute([$id]);
            
            $remark = !empty($_POST['remark']) ? $_POST['remark'] : '违反规定';
            $msg = "您的提现申请 #$id 已被拒绝，资金已退回您的余额。原因: " . $remark;
            $pdo->prepare("INSERT INTO messages (user_id, sender, message) VALUES (?, 'admin', ?)")->execute([$order['user_id'], $msg]);
            $success_msg = "拒绝成功";
        } else {
            $error_msg = "订单不存在。";
        }
    } elseif ($_POST['action'] == 'send_format') {
        $orderStmt = $pdo->prepare("SELECT user_id FROM orders WHERE id = ?");
        $orderStmt->execute([$id]);
        $order = $orderStmt->fetch();
        if ($order) {
            $format = "【出款格式】\n提现单号: #$id\n请确认您的收货地址及相关信息准确无误。管理员正在进行最后审核。";
            $pdo->prepare("INSERT INTO messages (user_id, sender, message) VALUES (?, 'admin', ?)")->execute([$order['user_id'], $format]);
            $success_msg = "出款格式已发送。";
        }
    }
}

$withdrawals = $pdo->query("SELECT o.*, u.username, u.uid FROM orders o JOIN users u ON o.user_id = u.id WHERE o.type = 'usdt' ORDER BY o.id DESC")->fetchAll();

$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();
$pending_kyc = $pdo->query("SELECT COUNT(*) FROM users WHERE kyc_status = 1")->fetchColumn();

?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>提现管理 - NovaEx 管理员</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css">
    <style>
        :root { --primary: #f0b90b; --bg: #ffffff; --text: #1e2329; --border: #eaecef; }
        body { background: #f4f6f9; color: var(--text); font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; margin: 0; }
        .admin-layout { display: flex; min-height: 100vh; }
        .sidebar { width: 250px; background: #ffffff; border-right: 1px solid var(--border); padding: 1.5rem; }
        .main-content { flex: 1; padding: 2rem; background: #ffffff; }
        .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: var(--primary); 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; }
        .table th, .table td { padding: 15px; text-align: left; border-bottom: 1px solid var(--border); font-size: 0.9rem; }
        .table th { background: #fafafa; color: #707a8a; font-weight: 600; }
        
        .status-badge { padding: 4px 10px; border-radius: 6px; font-size: 0.75rem; font-weight: bold; }
        .pending { background: #fff9e6; color: #f0b90b; }
        .completed { background: #e6fff1; color: #03ad5d; }
        .rejected { background: #fff1f0; color: #f6465d; }
        
        .alert { padding: 15px; border-radius: 8px; margin-bottom: 20px; font-weight: bold; }
        .alert-success { background: #e6fff1; color: #03ad5d; border: 1px solid #03ad5d; }
        .alert-error { background: #fff1f0; color: #f6465d; border: 1px solid #f6465d; }
        
        .btn { padding: 8px 15px; border: none; border-radius: 6px; cursor: pointer; font-size: 0.85rem; font-weight: 600; transition: 0.2s; }
        .btn-success { background: #03ad5d; color: white; }
        .btn-danger { background: #f6465d; color: white; }
        .btn-info { background: #4facfe; color: white; }
        .btn:hover { opacity: 0.9; }
        
        input[type="text"] { padding: 8px; border: 1px solid var(--border); border-radius: 6px; font-size: 0.85rem; outline: none; width: 120px; }
    </style>
</head>
<body>
<div class="admin-layout">
    <div class="sidebar">
        <h2 style="color: var(--primary); 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 审核
            <?php if($pending_kyc > 0): ?><span class="badge"><?php echo $pending_kyc; ?></span><?php endif; ?>
        </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"><i class="fas fa-wallet"></i> 充值记录</a>
        <a href="withdrawals.php" class="menu-item active"><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">
        <h1>提现申请管理</h1>

        <?php if($success_msg): ?>
            <div class="alert alert-success"><i class="fas fa-check-circle"></i> <?php echo $success_msg; ?></div>
        <?php endif; ?>
        
        <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($withdrawals as $o): ?>
                <tr>
                    <td>#<?php echo $o['id']; ?></td>
                    <td><b><?php echo htmlspecialchars($o['username']); ?></b> (<?php echo $o['uid']; ?>)</td>
                    <td><?php echo number_format($o['amount'], 2); ?></td>
                    <td><?php echo strtoupper($o['currency'] ?? 'USDT'); ?></td>
                    <td><small><?php echo htmlspecialchars($o['account_info'] ?? ''); ?></small></td>
                    <td><span class="status-badge <?php echo $o['status']; ?>"><?php echo strtoupper($o['status']); ?></span></td>
                    <td>
                        <?php if($o['status'] == 'pending'): ?>
                            <div style="display: flex; gap: 8px;">
                                <form method="POST" style="margin: 0;">
                                    <input type="hidden" name="order_id" value="<?php echo $o['id']; ?>">
                                    <input type="hidden" name="action" value="send_format">
                                    <button type="submit" class="btn btn-info">发格式</button>
                                </form>
                                <form method="POST" style="margin: 0;">
                                    <input type="hidden" name="order_id" value="<?php echo $o['id']; ?>">
                                    <input type="hidden" name="action" value="complete">
                                    <button type="submit" class="btn btn-success" onclick="return confirm('确认汇出？')">汇出</button>
                                </form>
                                <form method="POST" style="margin: 0; display: flex; gap: 3px;">
                                    <input type="hidden" name="order_id" value="<?php echo $o['id']; ?>">
                                    <input type="hidden" name="action" value="reject">
                                    <input type="text" name="remark" placeholder="原因" required>
                                    <button type="submit" class="btn btn-danger">驳回</button>
                                </form>
                            </div>
                        <?php else: ?>
                            --
                        <?php endif; ?>
                    </td>
                </tr>
                <?php endforeach; ?>
            </tbody>
        </table>
    </div>
</div>
</body>
</html>