<?php
session_start();

// 如果未登录则跳转到 login.php
if (!isset($_SESSION['logged_in']) || $_SESSION['logged_in'] !== true) {
    header('Location: login.php');
    exit;
}

// 处理登出
if (isset($_GET['action']) && $_GET['action'] === 'logout') {
    session_destroy();
    header('Location: login.php');
    exit;
}

// ===== 已登录后的设备管理逻辑 =====
$logFile = __DIR__ . '/user/user_list.json';
$jsonDir = __DIR__ . '/duocang'; // JSON 文件目录

// 获取 JSON 文件列表
$jsonFiles = [];
if (is_dir($jsonDir)) {
    foreach (scandir($jsonDir) as $file) {
        if (pathinfo($file, PATHINFO_EXTENSION) === 'json') {
            $jsonFiles[] = $file;
        }
    }
}

// 读取日志
$logs = [];
if (file_exists($logFile)) {
    $content = file_get_contents($logFile);
    $logs = json_decode($content, true);
    if (!is_array($logs)) $logs = [];
}

// 删除设备
if (isset($_GET['delete'])) {
    $deleteId = trim($_GET['delete']);
    $logs = array_filter($logs, fn($log) => $log['device_id'] !== $deleteId);
    $logs = array_values($logs);
    file_put_contents($logFile, json_encode($logs, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
    header("Location: " . strtok($_SERVER['REQUEST_URI'], '?'));
    exit;
}

// 保存单行修改
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['old_device_id'])) {
    $oldId = trim($_POST['old_device_id']);
    foreach ($logs as &$log) {
        if ($log['device_id'] === $oldId) {
            $log['device_id']  = trim($_POST['device_id'] ?? $log['device_id']);
            $log['server']     = trim($_POST['server'] ?? $log['server'] ?? '');
            $log['remark']     = trim($_POST['remark'] ?? $log['remark'] ?? '');
            $log['expire_at']  = trim($_POST['expire_at'] ?? $log['expire_at'] ?? '');
            // 时间字段保持原样
        }
    }
    unset($log);
    file_put_contents($logFile, json_encode($logs, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
    header("Location: " . $_SERVER['PHP_SELF']);
    exit;
}

// ===== 搜索和分页处理 =====
$search = trim($_GET['search'] ?? '');
$page = max(1, intval($_GET['page'] ?? 1));
$perPage = 10;

// 搜索过滤
if ($search !== '') {
    $logs = array_filter($logs, fn($log) =>
        str_contains($log['device_id'], $search) || str_contains($log['remark'] ?? '', $search)
    );
    $logs = array_values($logs);
}

// 统计总数和过期数
$total = count($logs);
$expiredCount = 0;
$today = date('Y-m-d');
foreach ($logs as $log) {
    if (!empty($log['expire_at']) && $log['expire_at'] < $today) {
        $expiredCount++;
    }
}

$totalPages = ceil($total / $perPage);
$start = ($page - 1) * $perPage;
$logs = array_slice($logs, $start, $perPage);

// 输出管理页面 HTML
?>
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>用户管理</title>
<style>
body { font-family: "Segoe UI", Arial, sans-serif; margin: 30px; background:#f9fafc; color:#333; }
h2 { margin-bottom: 20px; color:#2c3e50; }
input[type=text], input[type=date], select { padding:8px; border-radius:5px; border:1px solid #ccc; width:160px; box-sizing:border-box; }
button, .btn { padding:6px 12px; border-radius:6px; border:none; cursor:pointer; font-size:13px; margin:2px; text-decoration: none; }
button:hover, .btn:hover { opacity:0.9; }
.btn-green { background:#4caf50; color:white; }
.btn-blue { background:#2196F3; color:white; }
.btn-red { background:#f44336; color:white; }
.logout { float:right; text-decoration:none; margin-bottom:15px; }
table { border-collapse: collapse; width:100%; margin-top:15px; background:#fff; border-radius:6px; overflow:hidden; box-shadow:0 1px 5px rgba(0,0,0,0.1); }
th, td { border:1px solid #ddd; padding:8px; text-align:center; }
th { background:#f4f6f8; color:#333; }
tr:hover { background:#f9f9f9; }
.pagination a { margin: 0 3px; text-decoration: none; padding: 4px 9px; border: 1px solid #ccc; border-radius: 4px; }
.pagination a.current { background: #2196F3; color: #fff; border: 1px solid #2196F3; }
.search-form { margin-bottom: 15px; }
.expired { background: #ffe6e6; color: #d9534f; font-weight: bold; }
.stats { margin-top: 20px; padding:10px; background:#fff; border-radius:6px; box-shadow:0 1px 5px rgba(0,0,0,0.1);}
</style>
</head>
<body>
<h2>📋 用户管理 | <a href="edit_duocang.php">编辑多仓 </a></h2>
<a class="btn btn-red logout" href="?action=logout">✈ 退出登录</a>

<form class="search-form" method="get">
    <input type="text" name="search" placeholder="搜索 Device ID 或备注" value="<?=htmlspecialchars($search)?>">
    <button type="submit" class="btn btn-blue">🔍 搜索</button>
</form>

<table>
<tr>
    <th>设备ID</th>
    <th>授权文件</th>
    <th>备注</th>
    <th>到期时间</th>
    <th>剩余天数</th>
    <th>创建时间</th>
    <th>最后登录</th>
    <th>操作</th>
</tr>
<?php foreach ($logs as $i => $log): 
    $expireAt = $log['expire_at'] ?? '';
    $isExpired = ($expireAt !== '' && $expireAt < $today);

    // 计算剩余天数
    $daysText = "未设置";
    if ($expireAt !== '') {
        $diff = (strtotime($expireAt) - strtotime($today)) / 86400;
        if ($diff >= 0) {
            $daysText = "还剩 " . intval($diff) . " 天";
        } else {
            $daysText = "已过期 " . abs(intval($diff)) . " 天";
        }
    }
?>
<tr>
    <form method="post">
        <input type="hidden" name="old_device_id" value="<?=htmlspecialchars($log['device_id'])?>">
        <td><input type="text" name="device_id" value="<?=htmlspecialchars($log['device_id'])?>"></td>
        <td>
            <select name="server">
                <option value="">-- 未选择 --</option>
                <?php foreach ($jsonFiles as $jsonFile): ?>
                    <option value="<?=$jsonFile?>" <?=($log['server'] ?? '') === $jsonFile ? 'selected':''?>><?=$jsonFile?></option>
                <?php endforeach; ?>
            </select>
        </td>
        <td><input type="text" name="remark" value="<?=htmlspecialchars($log['remark'] ?? '')?>"></td>
        <td class="<?=$isExpired ? 'expired' : ''?>">
            <input type="date" name="expire_at" value="<?=htmlspecialchars($expireAt)?>">
        </td>
        <td class="<?=$isExpired ? 'expired' : ''?>"><?=$daysText?></td>
        <td><?=htmlspecialchars($log['created_at'] ?? '')?></td>
        <td><?=htmlspecialchars($log['last_login'] ?? '')?></td>
        <td>
            <button type="submit" class="btn btn-green">💾 保存</button>
            <a class="btn btn-red" href="?delete=<?=urlencode($log['device_id'])?>" onclick="return confirm('确定删除此设备吗？')">✖ 删除</a>
        </td>
    </form>
</tr>
<?php endforeach; ?>
</table>

<?php if ($totalPages > 1): ?>
<div class="pagination">
    <?php for ($p = 1; $p <= $totalPages; $p++): 
        $class = $p === $page ? 'current' : '';
        $url = '?page='.$p.'&search='.urlencode($search);
    ?>
        <a href="<?=$url?>" class="<?=$class?>"><?=$p?></a>
    <?php endfor; ?>
</div>
<?php endif; ?>

<div class="stats">
    <strong>📊 用户统计：</strong><br>
    总用户数：<?=$total?><br>
    已过期用户数：<?=$expiredCount?>
</div>

</body>
</html>
