<?php
// 数据库连接
$db_host = "127.0.0.1";
$db_user = "penguin_app";
$db_pass = "Fwh8DcGyRf2RYiJx";
$db_name = "penguin_iot";

$mysqli = new mysqli($db_host, $db_user, $db_pass, $db_name);
if ($mysqli->connect_error) die("Database connection failed");
$mysqli->set_charset("utf8mb4");

// 处理表单提交（保存WiFi配置）
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['device_id'])) {
    $deviceId = intval($_POST['device_id']);
    $wifiName = $_POST['wifi_name'] ?? '';
    $wifiPwd  = $_POST['wifi_pwd'] ?? '';

    $stmt = $mysqli->prepare("
        UPDATE device_config 
        SET wifi_name=?, wifi_pwd=? 
        WHERE device_id=?
    ");
    $stmt->bind_param("ssi", $wifiName, $wifiPwd, $deviceId);
    $stmt->execute();
    $stmt->close();
    $success = "保存成功！";
}

// 搜索逻辑
$search_imei = $_GET['search_imei'] ?? '';
$show_all    = isset($_GET['show_all']) ? true : false;

// 构建SQL
if ($show_all) {
    // 总览：显示所有设备
    $sql = "
    SELECT d.id, d.imei, d.last_seen, d.online,
           ds.ssid_name AS device_ssid, ds.wifi_pwd AS device_pwd,
           ds.connect_count, ds.current_ip,
           dc.wifi_name AS config_ssid, dc.wifi_pwd AS config_pwd,
           dc.next_report_time, dc.wifi_usb_switch, dc.is_open_auth, dc.wifi_status AS config_wifi_status
    FROM device d
    INNER JOIN device_status ds ON d.id = ds.device_id
    LEFT JOIN device_config dc ON d.id = dc.device_id
    ORDER BY d.last_seen DESC
    ";
    $result = $mysqli->query($sql);
} elseif (!empty($search_imei)) {
    // 搜索单个IMEI
    $stmt = $mysqli->prepare("
    SELECT d.id, d.imei, d.last_seen, d.online,
           ds.ssid_name AS device_ssid, ds.wifi_pwd AS device_pwd,
           ds.connect_count, ds.current_ip,
           dc.wifi_name AS config_ssid, dc.wifi_pwd AS config_pwd,
           dc.next_report_time, dc.wifi_usb_switch, dc.is_open_auth, dc.wifi_status AS config_wifi_status
    FROM device d
    INNER JOIN device_status ds ON d.id = ds.device_id
    LEFT JOIN device_config dc ON d.id = dc.device_id
    WHERE d.imei = ?
    ORDER BY d.last_seen DESC
    ");
    $stmt->bind_param("s", $search_imei);
    $stmt->execute();
    $result = $stmt->get_result();
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<!-- 允许手机正常缩放，解除锁定 -->
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=2.0, user-scalable=yes">
<title>设备管理</title>
<style>
* {
    box-sizing: border-box;
    margin: 0;
    padding: 0;
}
body {
    font-family: system-ui, -apple-system, sans-serif;
    background: #f5f7fa;
    padding: 20px;
    font-size: 15px;
    line-height: 1.5;
}

/* 搜索页面容器 */
.search-box {
    max-width: 480px;
    margin: 40px auto;
    background: #fff;
    padding: 30px 24px;
    border-radius: 16px;
    box-shadow: 0 2px 10px rgba(0,0,0,0.05);
}
.search-box h2 {
    text-align: center;
    margin-bottom: 24px;
    font-size: 20px;
    color: #222;
}
.search-input {
    width: 100%;
    padding: 12px 14px;
    border: 1px solid #ddd;
    border-radius: 10px;
    font-size: 16px;
    margin-bottom: 14px;
}
.search-btn,
.all-btn {
    width: 100%;
    padding: 12px;
    border: none;
    border-radius: 10px;
    font-size: 16px;
    cursor: pointer;
    margin-bottom: 8px;
}
.search-btn {
    background: #007bff;
    color: #fff;
}
.all-btn {
    background: #6c757d;
    color: #fff;
}

/* 总览页面 */
.container {
    max-width: 1200px;
    margin: 0 auto;
}
.header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 16px;
}
.header h2 {
    font-size: 19px;
    color: #222;
}
.back-btn {
    padding: 8px 14px;
    background: #6c757d;
    color: #fff;
    border-radius: 8px;
    text-decoration: none;
    font-size: 14px;
}
.success {
    background: #e6f9ee;
    color: #00a854;
    padding: 10px 14px;
    border-radius: 8px;
    margin-bottom: 16px;
}
.table-wrapper {
    background: #fff;
    border-radius: 14px;
    overflow: hidden;
    box-shadow: 0 2px 8px rgba(0,0,0,0.04);
    width: 100%;
    max-width: 100%;
overflow-x: auto;
}
table {
    border-collapse: collapse;
    width: 100%;
    min-width: 800px;
}
th, td {
    border-bottom: 1px solid #f2f2f2;
    padding: 12px 8px;
    text-align: center;
    vertical-align: middle;
    white-space: nowrap;
}
th {
    background: #fafbfc;
    font-weight: 600;
    color: #444;
}
td input {
    width: 100%;
    padding: 6px 8px;
    border: 1px solid #ddd;
    border-radius: 6px;
}
.pwd-container {
    position: relative;
}
.eye-btn {
    position: absolute;
    right: 6px;
    top: 50%;
    transform: translateY(-50%);
    cursor: pointer;
    user-select: none;
}
.save-btn {
    padding: 6px 10px;
    background: #007bff;
    color: #fff;
    border: none;
    border-radius: 6px;
    cursor: pointer;
}
.online { color: #00a854; }
.offline { color: #f53f3f; }
</style>
</head>

<body>

<?php if (!$show_all && empty($search_imei)): ?>

<!-- ====================== -->
<!-- 默认：搜索页面 -->
<!-- ====================== -->
<div class="search-box">
    <h2>设备WiFi管理</h2>
    <form method="get">
        <input 
            type="text" 
            name="search_imei" 
            class="search-input" 
            placeholder="请输入IMEI" 
            required
        >
        <button type="submit" class="search-btn">搜索设备</button>
    </form>
    <form method="get">
        <input type="hidden" name="show_all" value="1">
        <button type="submit" class="all-btn">总览</button>
    </form>
</div>

<?php else: ?>

<!-- ====================== -->
<!-- 搜索结果 / 总览页面 -->
<!-- ====================== -->
<div class="container">
    <div class="header">
        <h2>
            <?php if ($show_all): ?>
            设备总览
            <?php else: ?>
            IMEI：<?= htmlspecialchars($search_imei) ?>
            <?php endif; ?>
        </h2>
        <a href="?" class="back-btn">返回搜索</a>
    </div>

    <?php if (isset($success)): ?>
    <div class="success"><?= $success ?></div>
    <?php endif; ?>

    <div class="table-wrapper">
        <table>
            <thead>
                <tr>
                    <th>IMEI</th>
                    <th>最后在线</th>
                    <th>状态</th>
                    <th>当前WiFi</th>
                    <th>密码</th>
                    <th>连接数</th>
                    <th>IP地址</th>
                    <th>下发WiFi名</th>
                    <th>下发WiFi密码</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
            <?php if (isset($result) && $result->num_rows > 0): ?>
                <?php while($row = $result->fetch_assoc()): ?>
                <tr>
                <form method="post">
                <input type="hidden" name="device_id" value="<?= $row['id'] ?>">

                <?php
                $device_ssid = htmlspecialchars($row['device_ssid'] ?? '', ENT_QUOTES);
                $device_pwd  = htmlspecialchars($row['device_pwd'] ?? '', ENT_QUOTES);
                $config_ssid = htmlspecialchars($row['config_ssid'] ?? '', ENT_QUOTES);
                $config_pwd  = htmlspecialchars($row['config_pwd'] ?? '', ENT_QUOTES);
                ?>

                <td><?= htmlspecialchars($row['imei']) ?></td>
                <td><?= $row['last_seen'] ?? '-' ?></td>
                <td class="<?= $row['online'] ? 'online' : 'offline' ?>">
                    <?= $row['online'] ? '在线' : '离线' ?>
                </td>
                <td><?= $device_ssid ?></td>
                <td><?= $device_pwd ?></td>
                <td><?= $row['connect_count'] ?? 0 ?></td>
                <td><?= htmlspecialchars($row['current_ip'] ?? '-') ?></td>

                <td><input type="text" name="wifi_name" value="<?= $config_ssid ?>"></td>

                <td>
                    <div class="pwd-container">
                        <input type="password" id="pwd_<?= $row['id'] ?>" name="wifi_pwd" value="<?= $config_pwd ?>">
                        <span class="eye-btn" onclick="togglePwd(<?= $row['id'] ?>)">👁️</span>
                    </div>
                </td>

                <td><button type="submit" class="save-btn">保存</button></td>
                </form>
                </tr>
                <?php endwhile; ?>
            <?php else: ?>
                <tr><td colspan="10" style="padding:20px;">暂无设备</td></tr>
            <?php endif; ?>
            </tbody>
        </table>
    </div>
</div>

<?php endif; ?>

<script>
function togglePwd(id){
    var input = document.getElementById('pwd_'+id);
    input.type = input.type === 'password' ? 'text' : 'password';
}
</script>

</body>
</html>
