<?php
require_once __DIR__ . '/layout.php';

$db = db();

// Helper to check permissions
if (!hasPermission('view_orders')) {
    echo "权限不足";
    exit;
}

// Auto-settle expired orders
$db->beginTransaction();
try {
    $stmt = $db->prepare("SELECT o.*, u.win_loss_control as user_control FROM binary_orders o JOIN users u ON o.user_id = u.id WHERE o.status = 'pending' AND DATE_ADD(o.created_at, INTERVAL o.duration SECOND) <= NOW()");
    $stmt->execute();
    $expired = $stmt->fetchAll();
    foreach ($expired as $o) {
        $result = ($o['control_status'] == 1 || $o['user_control'] == 1) ? 'won' : (($o['control_status'] == 2 || $o['user_control'] == 2) ? 'lost' : ((rand(0, 100) > 50) ? 'won' : 'lost'));
        
        // Get a dummy close price if we don't have one (should match the result)
        $close_price = $o['entry_price'];
        if ($result === 'won') {
            $close_price = ($o['direction'] === 'up' || $o['direction'] === 'buy') ? $o['entry_price'] * 1.01 : $o['entry_price'] * 0.99;
        } else {
            $close_price = ($o['direction'] === 'up' || $o['direction'] === 'buy') ? $o['entry_price'] * 0.99 : $o['entry_price'] * 1.01;
        }

        $db->prepare("UPDATE binary_orders SET status = ?, close_price = ?, end_at = NOW() WHERE id = ?")->execute([$result, $close_price, $o['id']]);
        if ($result === 'won') {
            $win_amount = $o['amount'] + ($o['amount'] * $o['profit_rate'] / 100);
            $db->prepare("UPDATE user_balances SET available = available + ? WHERE user_id = ? AND symbol = 'USDT'")->execute([$win_amount, $o['user_id']]);
            $db->prepare("INSERT INTO transactions (user_id, type, amount, symbol, status) VALUES (?, 'binary_win', ?, 'USDT', 'completed')")->execute([$o['user_id'], $win_amount]);
        } else {
            $db->prepare("INSERT INTO transactions (user_id, type, amount, symbol, status) VALUES (?, 'binary_loss', ?, 'USDT', 'completed')")->execute([$o['user_id'], $o['amount']]);
        }
    }
    $db->commit();
} catch (Exception $e) {
    $db->rollBack();
}

// Handle Control Update
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action'])) {
    if ($_POST['action'] === 'set_control') {
        $id = (int)$_POST['order_id'];
        $status = (int)$_POST['control_status'];
        $db->prepare("UPDATE binary_orders SET control_status = ? WHERE id = ?")->execute([$status, $id]);
        header("Location: binary.php?msg=updated");
        exit;
    }
}

$title = '秒合约管理';
ob_start();

$user_id = isset($_GET['user_id']) ? (int)$_GET['user_id'] : null;
$sql = "SELECT o.*, u.username, u.uid FROM binary_orders o JOIN users u ON o.user_id = u.id";
$params = [];
if ($admin['is_agent']) {
    $sql .= ($params ? " AND" : " WHERE") . " u.agent_id = ?";
    $params[] = $admin['id'];
}
if ($user_id) {
    $sql .= (strpos($sql, 'WHERE') === false ? " WHERE" : " AND") . " o.user_id = ?";
    $params[] = $user_id;
}
$sql .= " ORDER BY o.created_at DESC";

$stmt = $db->prepare($sql);
$stmt->execute($params);
$orders = $stmt->fetchAll();
?>

<div class="d-flex justify-content-between align-items-center mb-4">
    <div class="d-flex align-items-center gap-3">
        <a href="<?= $user_id ? 'users.php' : 'index.php' ?>" class="btn btn-outline-secondary btn-sm"><i class="bi bi-arrow-left"></i> 返回</a>
        <h4 class="mb-0">秒合约下单记录 <?= $user_id ? "(用户ID: $user_id)" : "" ?></h4>
    </div>
</div>

<div class="card p-3 mb-4 border-0 shadow-sm card-dismissible card-auto-dismiss" data-card-id="binary_instructions">
    <h6 class="fw-bold mb-2"><i class="bi bi-info-circle me-2"></i>管理提示</h6>
    <p class="small text-muted mb-0">在此页面您可以实时监控用户的秒合约订单。对于进行中的订单，您可以手动设置“控赢”或“控亏”来干预交易结果。订单到期后系统会自动根据设置或市场价进行结算。</p>
</div>

<?php if (isset($_GET['msg'])): ?>
    <div class="alert alert-success mb-4">控制状态已更新！</div>
<?php endif; ?>

<div class="table-container">
    <table class="table table-hover align-middle">
        <thead>
            <tr class="text-muted small">
                <th>编号</th>
                <th>用户信息</th>
                <th>币种/方向</th>
                <th>金额/时长</th>
                <th>入场价/出场价</th>
                <th>盈亏</th>
                <th>状态</th>
                <th>控制</th>
                <th class="text-end">操作</th>
            </tr>
        </thead>
        <tbody>
            <?php foreach ($orders as $o): ?>
            <tr>
                <td><?= $o['id'] ?></td>
                <td>
                    <div><?= htmlspecialchars($o['username']) ?></div>
                    <code class="small"><?= $o['uid'] ?></code>
                </td>
                <td>
                    <span class="fw-bold"><?= $o['symbol'] ?></span>
                    <br>
                    <?php 
                    $is_up = in_array($o['direction'], ['buy', 'up', '涨']);
                    ?>
                    <span class="badge <?= $is_up ? 'bg-success' : 'bg-danger' ?>">
                        <?= $is_up ? '买涨 ↑' : '买跌 ↓' ?>
                    </span>
                </td>
                <td>
                    <div><?= number_format($o['amount'], 2) ?> USDT</div>
                    <div class="text-muted small"><?= $o['duration'] ?> 秒</div>
                </td>
                <td>
                    <div class="small">入: <?= $o['entry_price'] ?></div>
                    <div class="small">出: <?= $o['close_price'] ?? '-' ?></div>
                </td>
                <td>
                    <?php if ($o['status'] === 'won'): ?>
                        <span class="text-success fw-bold">+<?= number_format($o['amount'] * $o['profit_rate'] / 100, 2) ?></span>
                    <?php elseif ($o['status'] === 'lost'): ?>
                        <span class="text-danger fw-bold">-<?= number_format($o['amount'], 2) ?></span>
                    <?php else: ?>
                        <span class="text-muted">-</span>
                    <?php endif; ?>
                </td>
                <td>
                    <?php if ($o['status'] === 'pending'): ?>
                        <span class="badge bg-warning">进行中</span>
                    <?php elseif ($o['status'] === 'won'): ?>
                        <span class="badge bg-success">已盈利</span>
                    <?php elseif ($o['status'] === 'lost'): ?>
                        <span class="badge bg-danger">已亏损</span>
                    <?php else: ?>
                        <span class="badge bg-secondary">已取消</span>
                    <?php endif; ?>
                </td>
                <td>
                    <?php if ($o['control_status'] == 1): ?>
                        <span class="badge bg-success">控赢</span>
                    <?php elseif ($o['control_status'] == 2): ?>
                        <span class="badge bg-danger">控输</span>
                    <?php else: ?>
                        <span class="badge bg-secondary">正常</span>
                    <?php endif; ?>
                </td>
                <td class="text-end">
                    <?php if ($o['status'] === 'pending'): ?>
                    <form method="POST" class="d-inline">
                        <input type="hidden" name="order_id" value="<?= $o['id'] ?>">
                        <input type="hidden" name="action" value="set_control">
                        <div class="btn-group btn-group-sm">
                            <button name="control_status" value="1" class="btn btn-outline-success <?= $o['control_status'] == 1 ? 'active' : '' ?>">控赢</button>
                            <button name="control_status" value="2" class="btn btn-outline-danger <?= $o['control_status'] == 2 ? 'active' : '' ?>">控输</button>
                            <button name="control_status" value="0" class="btn btn-outline-secondary <?= $o['control_status'] == 0 ? 'active' : '' ?>">正常</button>
                        </div>
                    </form>
                    <?php endif; ?>
                </td>
            </tr>
            <?php endforeach; ?>
            <?php if (empty($orders)): ?>
            <tr><td colspan="9" class="text-center p-5 text-muted">暂无订单记录</td></tr>
            <?php endif; ?>
        </tbody>
    </table>
</div>

<?php
$content = ob_get_clean();
renderAdminPage($content, $title);
?>
