<?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;
}

$dir = __DIR__ . '/duocang';

// 确保目录存在
if (!is_dir($dir)) {
    mkdir($dir, 0777, true);
}

$files = array_values(array_filter(scandir($dir), fn($f) => pathinfo($f, PATHINFO_EXTENSION) === 'json'));

$newFileMessage = '';
// ===== 新建文件 =====
if ($_SERVER['REQUEST_METHOD'] === 'POST' && !empty($_POST['new_file'])) {
    $newFile = trim($_POST['new_file']);
    if ($newFile !== '') {
        if (pathinfo($newFile, PATHINFO_EXTENSION) !== 'json') $newFile .= '.json';
        if (!file_exists($dir . '/' . $newFile)) {
            file_put_contents($dir . '/' . $newFile, json_encode(['urls'=>[]], JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES));
            $newFileMessage = "文件 {$newFile} 创建成功！";
            $files[] = $newFile;
        } else {
            $newFileMessage = "文件 {$newFile} 已存在！";
        }
    }
}

// ===== 删除文件 =====
if (isset($_GET['delete']) && $_GET['delete'] !== '') {
    $delFile = basename($_GET['delete']); // 避免路径穿越
    $delPath = $dir . '/' . $delFile;
    if (file_exists($delPath)) {
        unlink($delPath);
        header("Location: " . $_SERVER['PHP_SELF']);
        exit;
    }
}
?>
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>JSON 文件管理</title>
<style>
    body { font-family: "Segoe UI", Arial, sans-serif; margin: 30px; background:#f9fafc; color:#333; }
    h2 { margin-bottom: 20px; color:#2c3e50; }
    h3 { color:#34495e; margin-top:30px; }
    .message { padding:10px; margin:15px 0; border-radius:5px; background:#eafaf1; color:#2d7a46; border:1px solid #c3e6cb; }
    form { margin-bottom: 20px; display:inline-block; }
    input[type=text], select { padding:8px; border-radius:5px; border:1px solid #ccc; width:220px; box-sizing:border-box; }
    button { padding:8px 16px; border-radius:5px; border:none; cursor:pointer; font-size:14px; margin:2px; }
    button:hover { opacity:0.9; }
    .btn-green { background:#4caf50; color:white; }
    .btn-blue { background:#2196F3; color:white; }
    .btn-red { background:#f44336; color:white; }
    table { border-collapse: collapse; width:100%; margin-top:15px; background:#fff; border-radius:6px; overflow:hidden; }
    th, td { border:1px solid #ddd; padding:10px; text-align:center; }
    th { background:#f4f6f8; color:#333; }
    tr:hover { background:#f9f9f9; }
</style>
<script>
function confirmDelete(file) {
    if (confirm("确定要删除文件 " + file + " 吗？")) {
        window.location = "?delete=" + encodeURIComponent(file);
    }
}
</script>
</head>
<body>
<h2>多仓管理|<a href="index.php">返回用户管理</a></h2>

<?php if($newFileMessage) echo "<div class='message'>{$newFileMessage}</div>"; ?>

<form method="post" style="margin-bottom:30px;">
    <input type="text" name="new_file" placeholder="新 JSON 文件名">
    <button type="submit" class="btn-green">➕ 创建文件</button>
</form>

<h3>选择要编辑的文件</h3>
<form method="get">
    <select name="edit" onchange="this.form.submit()">
        <option value="">-- 请选择文件 --</option>
        <?php foreach($files as $file): ?>
            <option value="<?=htmlspecialchars($file)?>" <?=isset($_GET['edit']) && $_GET['edit']===$file ? 'selected':''?>><?=htmlspecialchars($file)?></option>
        <?php endforeach; ?>
    </select>
</form>

<?php if(isset($_GET['edit']) && $_GET['edit']!==''): ?>
    <button type="button" class="btn-red" onclick="confirmDelete('<?=htmlspecialchars($_GET['edit'])?>')">🗑 删除当前文件</button>
<?php endif; ?>

<?php
// ===== 编辑页面 =====
if (isset($_GET['edit']) && $_GET['edit'] !== ''):
    $editFile = basename($_GET['edit']); // 避免路径穿越
    $editPath = $dir . '/' . $editFile;

    if (!file_exists($editPath)) {
        echo "<p>文件不存在</p>";
        exit;
    }

    $data = json_decode(file_get_contents($editPath), true) ?? ['urls'=>[]];
    
    if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['name'], $_POST['url'], $_POST['save_edit'])) {
        $names = $_POST['name'];
        $urls = $_POST['url'];
        $newData = ['urls'=>[]];
        foreach ($names as $i => $name) {
            $n = trim($name);
            $u = trim($urls[$i]);
            if ($n === '' && $u === '') continue;
            $newData['urls'][] = ['name'=>$n,'url'=>$u];
        }
        file_put_contents($editPath, json_encode($newData, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));

        $data = $newData;
        echo "<div class='message'>✅ 保存成功</div>";
    }
?>
<hr>
<h3>✏️ 编辑文件：<?=htmlspecialchars($editFile)?></h3>
<form method="post">
<table>
<tr>
    <th>名称</th>
    <th>网址</th>
    <th>操作</th>
</tr>
<?php foreach ($data['urls'] as $i => $item): ?>
<tr>
    <td><input type="text" name="name[]" value="<?=htmlspecialchars($item['name'])?>"></td>
    <td><input type="text" name="url[]" value="<?=htmlspecialchars($item['url'])?>"></td>
    <td><button type="button" class="btn-red" onclick="this.parentNode.parentNode.remove()">🗑 删除</button></td>
</tr>
<?php endforeach; ?>
</table>
<br>
<button type="button" class="btn-blue" onclick="addRow()">➕ 新增一行</button>
<button type="submit" name="save_edit" class="btn-green">💾 保存修改</button>
</form>

<script>
function addRow() {
    const table = document.querySelector('table');
    const row = table.insertRow(-1);
    row.innerHTML = `
        <td><input type="text" name="name[]" placeholder="名称"></td>
        <td><input type="text" name="url[]" placeholder="网址"></td>
        <td><button type="button" class="btn-red" onclick="this.parentNode.parentNode.remove()">🗑 删除</button></td>
    `;
}
</script>
<?php endif; ?>

</body>
</html>
