index.php 6.83 KB
<?php
require_once __DIR__ . '/../vendor/autoload.php';

// 加载配置 (.env 手动加载逻辑同 start.php)
if (file_exists(__DIR__ . '/../.env')) {
    $lines = file(__DIR__ . '/../.env', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
    foreach ($lines as $line) {
        if (strpos(trim($line), '#') === 0) continue;
        list($name, $value) = explode('=', $line, 2);
        $_ENV[trim($name)] = trim($value);
    }
}

$pdo = null;
$message = '';

// 连接数据库
try {
    $dsn = "mysql:host={$_ENV['DB_HOST']};dbname={$_ENV['DB_NAME']};charset=utf8mb4";
    $pdo = new PDO($dsn, $_ENV['DB_USER'], $_ENV['DB_PASS']);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    // FATAL: Do NOT use die() in Workerman, it kills the worker process!
    $message = "<div style='color: red; padding: 20px; text-align: center; border: 1px solid red; background: #ffe6e6;'>Database Connection Failed: " . htmlspecialchars($e->getMessage()) . "</div>";
    $pdo = null; 
}

// 处理绑定表单提交
if ($pdo && $_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'bind') {
    $deviceId = trim($_POST['device_id']);
    $phone = trim($_POST['phone']);
    $isPrimary = isset($_POST['is_primary']) ? 1 : 0;

    if ($deviceId && $phone) {
        // 1. 查找用户
        try {
            $stmt = $pdo->prepare("SELECT id, nickname FROM users WHERE phone = ?");
            $stmt->execute([$phone]);
            $user = $stmt->fetch(PDO::FETCH_ASSOC);
    
            if ($user) {
                // 2. 插入/更新绑定
                // 先检查是否已存在
                $check = $pdo->prepare("SELECT id FROM user_device_bindings WHERE user_id = ? AND device_id = ?");
                $check->execute([$user['id'], $deviceId]);
                
                if (!$check->fetch()) {
                    $bind = $pdo->prepare("INSERT INTO user_device_bindings (user_id, device_id, is_primary, created_at) VALUES (?, ?, ?, NOW())");
                    $bind->execute([$user['id'], $deviceId, $isPrimary]);
                    $message = "<div style='color: green; margin-bottom: 20px; background: #e6fffa; padding: 10px; border-radius: 4px;'> 成功将设备 <b>$deviceId</b> 绑定给用户 <b>{$user['nickname']}</b></div>";
                } else {
                    $message = "<div style='color: orange; margin-bottom: 20px;'>⚠️ 该用户已经绑定过此设备,无需重复操作。</div>";
                }
            } else {
                $message = "<div style='color: red; margin-bottom: 20px;'> 手机号 <b>$phone</b> 未找到。请确保用户已在小程序登录过。</div>";
            }
        } catch (Exception $e) {
             $message = "<div style='color: red;'>Operation Failed: " . $e->getMessage() . "</div>";
        }
    }
}

// 获取设备列表 (Mock Data + Binding Count)
$bindings = [];
if ($pdo) {
    try {
        $bindings = $pdo->query("
            SELECT b.id, u.nickname, u.phone, b.device_id, b.is_primary, b.created_at
            FROM user_device_bindings b
            JOIN users u ON b.user_id = u.id
            ORDER BY b.created_at DESC
        ")->fetchAll(PDO::FETCH_ASSOC);
    } catch (Exception $e) {
        if (empty($message)) $message = "<div style='color: red;'>Load Error: " . $e->getMessage() . "</div>";
    }
}

?>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Moltbot 管理后台</title>
    <link rel="stylesheet" href="style.css">
    <link rel="icon" href="data:,">
</head>
<body>

<div class="header">
    <div class="brand">Moltbot Admin</div>
    <div><?php echo date('Y-m-d H:i'); ?></div>
</div>

<div class="container">
    
    <?php echo $message; ?>

    <?php if (!$pdo): ?>
        <div class="card">
            <h3 style="color: red;">System Error</h3>
            <p>Cannot connect to the database. Please check your configuration.</p>
        </div>
    <?php else: ?>

    <!-- 新增绑定卡片 -->
    <div class="card">
        <div class="title">新增绑定</div>
        <form method="POST" action="">
            <input type="hidden" name="action" value="bind">
            <div style="display: flex; gap: 20px;">
                <div class="form-group" style="flex: 1;">
                    <label class="form-label">设备 ID</label>
                    <input type="text" name="device_id" class="form-control" placeholder="例如: dev_test_001" required>
                </div>
                <div class="form-group" style="flex: 1;">
                    <label class="form-label">用户手机号</label>
                    <input type="text" name="phone" class="form-control" placeholder="输入用户注册手机号" required>
                </div>
            </div>
            <div class="form-group">
                <label>
                    <input type="checkbox" name="is_primary" value="1" checked> 设为主设备 (默认)
                </label>
            </div>
            <button type="submit" class="btn btn-primary">立即绑定</button>
        </form>
    </div>

    <!-- 绑定列表卡片 -->
    <div class="card">
        <div class="title">绑定记录 (<?php echo count($bindings); ?>)</div>
        <table>
            <thead>
                <tr>
                    <th>用户</th>
                    <th>手机号</th>
                    <th>设备 ID</th>
                    <th>主设备</th>
                    <th>绑定时间</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <?php foreach ($bindings as $row): ?>
                <tr>
                    <td><?php echo htmlspecialchars($row['nickname']); ?></td>
                    <td><?php echo htmlspecialchars($row['phone']); ?></td>
                    <td><?php echo htmlspecialchars($row['device_id']); ?></td>
                    <td>
                        <?php if ($row['is_primary']): ?>
                            <span style="color: var(--primary-color);">✔</span>
                        <?php endif; ?>
                    </td>
                    <td><?php echo $row['created_at']; ?></td>
                    <td>
                        <a href="#" style="color: red; font-size: 12px; text-decoration: none;">解绑</a>
                    </td>
                </tr>
                <?php endforeach; ?>
                <?php if (empty($bindings)): ?>
                    <tr><td colspan="6" style="text-align: center; color: #999;">暂无数据</td></tr>
                <?php endif; ?>
            </tbody>
        </table>
    </div>
    
    <?php endif; ?>

</div>

</body>
</html>