<?php
include_once 'config.php';

if (!isset($_SESSION['admin_id'])) {
    header("Location: admin_login.php");
    exit;
}

$action = $_GET['action'] ?? 'dashboard';

// Handle Post Actions
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_POST['update_balance'])) {
        $stmt = db()->prepare("UPDATE accounts SET balance = ? WHERE id = ?");
        $stmt->execute([$_POST['balance'], $_POST['account_id']]);
        $msg = "余额更新成功";
    }
    if (isset($_POST['update_win_loss'])) {
        $stmt = db()->prepare("UPDATE accounts SET win_loss_control = ? WHERE id = ?");
        $stmt->execute([$_POST['win_loss_control'], $_POST['account_id']]);
        $msg = "输赢控制已更新";
    }
    if (isset($_POST['update_kyc'])) {
        $stmt = db()->prepare("UPDATE accounts SET kyc_status = ? WHERE id = ?");
        $stmt->execute([$_POST['kyc_status'], $_POST['account_id']]);
        $msg = "认证状态已更新";
    }
    if (isset($_POST['approve_deposit'])) {
        db()->beginTransaction();
        $stmt = db()->prepare("SELECT * FROM transactions WHERE id = ? AND status = 'pending' AND transaction_type = 'deposit'");
        $stmt->execute([$_POST['transaction_id']]);
        $trx = $stmt->fetch();
        if ($trx) {
            db()->prepare("UPDATE accounts SET balance = balance + ? WHERE id = ?")->execute([$trx['amount'], $trx['account_id']]);
            db()->prepare("UPDATE transactions SET status = 'completed' WHERE id = ?")->execute([$trx['id']]);
            $msg = "充值已批准";
        }
        db()->commit();
    }
    if (isset($_POST['approve_withdraw'])) {
        db()->beginTransaction();
        $stmt = db()->prepare("SELECT * FROM transactions WHERE id = ? AND status = 'pending' AND transaction_type = 'withdraw'");
        $stmt->execute([$_POST['transaction_id']]);
        $trx = $stmt->fetch();
        if ($trx) {
            db()->prepare("UPDATE accounts SET frozen_balance = frozen_balance - ? WHERE id = ?")->execute([$trx['amount'], $trx['account_id']]);
            db()->prepare("UPDATE transactions SET status = 'completed' WHERE id = ?")->execute([$trx['id']]);
            $msg = "提现已批准";
        }
        db()->commit();
    }
    if (isset($_POST['reject_transaction'])) {
        db()->beginTransaction();
        $stmt = db()->prepare("SELECT * FROM transactions WHERE id = ? AND status = 'pending'");
        $stmt->execute([$_POST['transaction_id']]);
        $trx = $stmt->fetch();
        if ($trx && $trx['transaction_type'] === 'withdraw') {
            // Unfreeze balance
            db()->prepare("UPDATE accounts SET balance = balance + ?, frozen_balance = frozen_balance - ? WHERE id = ?")->execute([$trx['amount'], $trx['amount'], $trx['account_id']]);
        }
        db()->prepare("UPDATE transactions SET status = 'failed' WHERE id = ?")->execute([$_POST['transaction_id']]);
        $msg = "交易已驳回";
        db()->commit();
    }
    if (isset($_POST['update_site_settings'])) {
        $stmt = db()->prepare("UPDATE site_settings SET site_name = ?, contact_email = ?, deposit_address = ? WHERE id = 1");
        $stmt->execute([$_POST['site_name'], $_POST['contact_email'], $_POST['deposit_address']]);
        $msg = "站点设置已更新";
    }
    if (isset($_POST['update_price'])) {
        $stmt = db()->prepare("UPDATE cryptocurrencies SET manual_price = ? WHERE id = ?");
        $stmt->execute([$_POST['manual_price'], $_POST['coin_id']]);
        $msg = "价格已手动调整";
    }
}

$settings = get_site_settings();
?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>管理后台 - <?php echo $settings['site_name']; ?></title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.10.0/font/bootstrap-icons.css">
    <style>
        body { background: #f4f7f6; }
        .sidebar { min-height: 100vh; background: #2c3e50; color: white; }
        .sidebar a { color: #bdc3c7; text-decoration: none; padding: 10px 20px; display: block; }
        .sidebar a:hover, .sidebar a.active { background: #34495e; color: white; }
        .card { border: none; box-shadow: 0 0.125rem 0.25rem rgba(0, 0, 0, 0.075); margin-bottom: 20px; }
    </style>
</head>
<body>
<div class="container-fluid">
    <div class="row">
        <!-- Sidebar -->
        <div class="col-md-2 sidebar p-0">
            <div class="p-3 text-center border-bottom border-secondary">
                <h4>管理后台</h4>
            </div>
            <a href="?action=dashboard" class="<?php echo $action === 'dashboard' ? 'active' : ''; ?>"><i class="bi bi-speedometer2 me-2"></i> 控制台</a>
            <a href="?action=users" class="<?php echo $action === 'users' ? 'active' : ''; ?>"><i class="bi bi-people me-2"></i> 用户管理</a>
            <a href="?action=transactions" class="<?php echo $action === 'transactions' ? 'active' : ''; ?>"><i class="bi bi-cash-stack me-2"></i> 充值提现</a>
            <a href="?action=orders" class="<?php echo $action === 'orders' ? 'active' : ''; ?>"><i class="bi bi-list-check me-2"></i> 交易记录</a>
            <a href="?action=market" class="<?php echo $action === 'market' ? 'active' : ''; ?>"><i class="bi bi-graph-up me-2"></i> 市场管理</a>
            <a href="?action=settings" class="<?php echo $action === 'settings' ? 'active' : ''; ?>"><i class="bi bi-gear me-2"></i> 系统设置</a>
            <a href="logout.php" class="mt-5 text-danger"><i class="bi bi-box-arrow-right me-2"></i> 退出登录</a>
        </div>

        <!-- Main Content -->
        <div class="col-md-10 p-4">
            <?php if (isset($msg)): ?>
                <div class="alert alert-success alert-dismissible fade show" role="alert">
                    <?php echo $msg; ?>
                    <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                </div>
            <?php endif; ?>

            <?php if ($action === 'dashboard'): ?>
                <h2 class="mb-4">控制台概览</h2>
                <div class="row">
                    <div class="col-md-3">
                        <div class="card bg-primary text-white p-3">
                            <h6>总用户</h6>
                            <h3><?php echo db()->query("SELECT COUNT(*) FROM accounts")->fetchColumn(); ?></h3>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-success text-white p-3">
                            <h6>待处理充值</h6>
                            <h3><?php echo db()->query("SELECT COUNT(*) FROM transactions WHERE transaction_type='deposit' AND status='pending'")->fetchColumn(); ?></h3>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-warning text-dark p-3">
                            <h6>待处理提现</h6>
                            <h3><?php echo db()->query("SELECT COUNT(*) FROM transactions WHERE transaction_type='withdraw' AND status='pending'")->fetchColumn(); ?></h3>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="card bg-info text-white p-3">
                            <h6>今日订单</h6>
                            <h3><?php echo db()->query("SELECT COUNT(*) FROM orders WHERE DATE(created_at) = CURRENT_DATE")->fetchColumn(); ?></h3>
                        </div>
                    </div>
                </div>
            <?php endif; ?>

            <?php if ($action === 'users'): ?>
                <h2 class="mb-4">用户管理</h2>
                <div class="card p-3">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>用户名</th>
                                <th>余额 (USDT)</th>
                                <th>认证状态</th>
                                <th>输赢控制</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            $users = db()->query("SELECT * FROM accounts ORDER BY id DESC")->fetchAll();
                            foreach ($users as $u):
                            ?>
                            <tr>
                                <td><?php echo $u['id']; ?></td>
                                <td><?php echo $u['username']; ?></td>
                                <td><?php echo number_format($u['balance'], 2); ?></td>
                                <td>
                                    <span class="badge bg-<?php echo $u['kyc_status'] === 'VERIFIED' ? 'success' : ($u['kyc_status'] === 'PENDING' ? 'warning' : 'secondary'); ?>">
                                        <?php echo $u['kyc_status']; ?>
                                    </span>
                                </td>
                                <td>
                                    <span class="badge bg-<?php echo $u['win_loss_control'] == 1 ? 'success' : ($u['win_loss_control'] == -1 ? 'danger' : 'secondary'); ?>">
                                        <?php echo $u['win_loss_control'] == 1 ? '必赢' : ($u['win_loss_control'] == -1 ? '必输' : '正常'); ?>
                                    </span>
                                </td>
                                <td>
                                    <button class="btn btn-sm btn-outline-primary" data-bs-toggle="modal" data-bs-target="#editUser<?php echo $u['id']; ?>">编辑</button>
                                </td>
                            </tr>
                            <!-- Modal -->
                            <div class="modal fade" id="editUser<?php echo $u['id']; ?>" tabindex="-1">
                                <div class="modal-dialog">
                                    <div class="modal-content">
                                        <div class="modal-header">
                                            <h5 class="modal-title">编辑用户: <?php echo $u['username']; ?></h5>
                                            <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
                                        </div>
                                        <div class="modal-body">
                                            <form method="POST" class="mb-3">
                                                <input type="hidden" name="account_id" value="<?php echo $u['id']; ?>">
                                                <div class="mb-3">
                                                    <label class="form-label">调整余额</label>
                                                    <div class="input-group">
                                                        <input type="number" step="0.01" name="balance" class="form-control" value="<?php echo $u['balance']; ?>">
                                                        <button class="btn btn-primary" name="update_balance">更新余额</button>
                                                    </div>
                                                </div>
                                            </form>
                                            <form method="POST" class="mb-3">
                                                <input type="hidden" name="account_id" value="<?php echo $u['id']; ?>">
                                                <div class="mb-3">
                                                    <label class="form-label">输赢控制</label>
                                                    <select name="win_loss_control" class="form-select mb-2">
                                                        <option value="0" <?php echo $u['win_loss_control'] == 0 ? 'selected' : ''; ?>>正常 (随机)</option>
                                                        <option value="1" <?php echo $u['win_loss_control'] == 1 ? 'selected' : ''; ?>>必赢 (Always Win)</option>
                                                        <option value="-1" <?php echo $u['win_loss_control'] == -1 ? 'selected' : ''; ?>>必输 (Always Loss)</option>
                                                    </select>
                                                    <button class="btn btn-warning w-100" name="update_win_loss">应用控制</button>
                                                </div>
                                            </form>
                                            <form method="POST">
                                                <input type="hidden" name="account_id" value="<?php echo $u['id']; ?>">
                                                <div class="mb-3">
                                                    <label class="form-label">认证状态</label>
                                                    <select name="kyc_status" class="form-select mb-2">
                                                        <option value="UNVERIFIED" <?php echo $u['kyc_status'] === 'UNVERIFIED' ? 'selected' : ''; ?>>未认证</option>
                                                        <option value="PENDING" <?php echo $u['kyc_status'] === 'PENDING' ? 'selected' : ''; ?>>待审核</option>
                                                        <option value="VERIFIED" <?php echo $u['kyc_status'] === 'VERIFIED' ? 'selected' : ''; ?>>已认证</option>
                                                    </select>
                                                    <button class="btn btn-info w-100 text-white" name="update_kyc">更新状态</button>
                                                </div>
                                            </form>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>

            <?php if ($action === 'transactions'): ?>
                <h2 class="mb-4">充值提现审核</h2>
                <div class="card p-3">
                    <table class="table table-hover">
                        <thead>
                            <tr>
                                <th>ID</th>
                                <th>用户</th>
                                <th>类型</th>
                                <th>金额</th>
                                <th>哈希/地址</th>
                                <th>状态</th>
                                <th>日期</th>
                                <th>操作</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            $trxs = db()->query("SELECT t.*, a.username FROM transactions t JOIN accounts a ON t.account_id = a.id ORDER BY t.id DESC")->fetchAll();
                            foreach ($trxs as $t):
                            ?>
                            <tr>
                                <td><?php echo $t['id']; ?></td>
                                <td><?php echo $t['username']; ?></td>
                                <td><span class="badge bg-<?php echo $t['transaction_type'] === 'deposit' ? 'primary' : 'warning'; ?>"><?php echo strtoupper($t['transaction_type']); ?></span></td>
                                <td><?php echo $t['amount']; ?></td>
                                <td><small class="text-truncate" style="max-width: 150px; display: inline-block;"><?php echo $t['tx_hash']; ?></small></td>
                                <td>
                                    <span class="badge bg-<?php echo $t['status'] === 'completed' ? 'success' : ($t['status'] === 'pending' ? 'info' : 'danger'); ?>">
                                        <?php echo strtoupper($t['status']); ?>
                                    </span>
                                </td>
                                <td><?php echo $t['timestamp']; ?></td>
                                <td>
                                    <?php if ($t['status'] === 'pending'): ?>
                                        <form method="POST" class="d-inline">
                                            <input type="hidden" name="transaction_id" value="<?php echo $t['id']; ?>">
                                            <button class="btn btn-sm btn-success" name="<?php echo $t['transaction_type'] === 'deposit' ? 'approve_deposit' : 'approve_withdraw'; ?>">批准</button>
                                            <button class="btn btn-sm btn-danger" name="reject_transaction">拒绝</button>
                                        </form>
                                    <?php endif; ?>
                                </td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>

            <?php if ($action === 'orders'): ?>
                <h2 class="mb-4">所有交易记录</h2>
                <div class="card p-3">
                    <table class="table table-sm table-hover">
                        <thead>
                            <tr>
                                <th>用户</th>
                                <th>币种</th>
                                <th>类型</th>
                                <th>方向</th>
                                <th>价格</th>
                                <th>数量</th>
                                <th>时间</th>
                            </tr>
                        </thead>
                        <tbody>
                            <?php 
                            $orders = db()->query("SELECT o.*, a.username FROM orders o JOIN accounts a ON o.account_id = a.id ORDER BY o.id DESC LIMIT 50")->fetchAll();
                            foreach ($orders as $o):
                            ?>
                            <tr>
                                <td><?php echo $o['username']; ?></td>
                                <td><?php echo $o['symbol']; ?></td>
                                <td><?php echo $o['trade_type']; ?></td>
                                <td class="text-<?php echo $o['side'] === 'BUY' ? 'success' : 'danger'; ?>"><?php echo $o['side']; ?></td>
                                <td><?php echo $o['price']; ?></td>
                                <td><?php echo $o['amount']; ?></td>
                                <td><?php echo $o['created_at']; ?></td>
                            </tr>
                            <?php endforeach; ?>
                        </tbody>
                    </table>
                </div>
            <?php endif; ?>

            <?php if ($action === 'market'): ?>
                <h2 class="mb-4">市场与币种管理</h2>
                <div class="row">
                    <?php 
                    $coins = db()->query("SELECT * FROM cryptocurrencies")->fetchAll();
                    foreach ($coins as $c):
                    ?>
                    <div class="col-md-4">
                        <div class="card p-3">
                            <h5><?php echo $c['name']; ?> (<?php echo $c['symbol']; ?>)</h5>
                            <p class="mb-1">当前市场价: <?php echo $c['current_price']; ?></p>
                            <form method="POST">
                                <input type="hidden" name="coin_id" value="<?php echo $c['id']; ?>">
                                <div class="mb-2">
                                    <label class="form-label small text-muted">手动价格 (0为跟随市场)</label>
                                    <input type="number" step="0.000001" name="manual_price" class="form-control" value="<?php echo $c['manual_price']; ?>">
                                </div>
                                <button class="btn btn-sm btn-primary w-100" name="update_price">设置手动价格</button>
                            </form>
                        </div>
                    </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>

            <?php if ($action === 'settings'): ?>
                <h2 class="mb-4">系统全局设置</h2>
                <div class="card p-4 shadow-sm">
                    <form method="POST">
                        <div class="mb-3">
                            <label class="form-label">站点名称</label>
                            <input type="text" name="site_name" class="form-control" value="<?php echo $settings['site_name']; ?>">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">联系邮箱</label>
                            <input type="email" name="contact_email" class="form-control" value="<?php echo $settings['contact_email']; ?>">
                        </div>
                        <div class="mb-3">
                            <label class="form-label">USDT 充值地址</label>
                            <input type="text" name="deposit_address" class="form-control" value="<?php echo $settings['deposit_address']; ?>">
                            <div class="form-text">用户在充值页面看到的钱包地址</div>
                        </div>
                        <button type="submit" name="update_site_settings" class="btn btn-primary px-5">保存所有设置</button>
                    </form>
                </div>
            <?php endif; ?>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.0/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>