<?php
session_start();

// 读取JSON文件内容
$jsonString = file_get_contents('data.json');
$data = json_decode($jsonString, true);

// 检查是否有解码错误
if (json_last_error() !== JSON_ERROR_NONE) {
    $error = 'JSON解码错误: ' . json_last_error_msg();
} else {
    $error = null;
}

// 检查用户是否已登录
$isLoggedIn = isset($_SESSION['username']);
?>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>滑雪板儿俱乐部 Snowboarder Club</title>
    <style>
        ul {
            list-style-type: none;
            padding-left: 20px;
        }
        li {
            margin-bottom: 5px;
        }
        strong {
            color: #333;
        }
        .hidden {
            display: none;
        }
    </style>
</head>
<body>
    <h1>PHP对象结构输出</h1>
    <?php if ($isLoggedIn): ?>
        <p>欢迎, <?php echo htmlspecialchars($_SESSION['username']); ?>!</p>
        <a href="logout.php">登出</a>
    <?php else: ?>
        <!-- <p>您当前是游客身份，无法编辑数据。</p> -->
        <!-- <a href="login.php">登录</a> -->
    <?php endif; ?>

    <?php if ($error): ?>
        <p style="color: red;"><?php echo $error; ?></p>
    <?php else: ?>
        <div id="data-container"></div>
        <?php if ($isLoggedIn): ?>
            <button onclick="addResort()">添加Resort</button>
            <button onclick="saveData()">保存数据</button>
        <?php endif; ?>
    <?php endif; ?>

    <script>
        let data = <?php echo json_encode($data); ?>;
        let isLoggedIn = <?php echo json_encode($isLoggedIn); ?>;

        function renderData() {
            const container = document.getElementById('data-container');
            container.innerHTML = '';
            data.forEach((resort, resortIndex) => {
                const resortDiv = document.createElement('div');
                resortDiv.innerHTML = `
                    <h2>Resort ID: ${isLoggedIn ? `<input type="text" value="${resort.resortId}" onchange="updateResortId(${resortIndex}, this.value)">` : resort.resortId}</h2>
                    ${isLoggedIn ? `<button onclick="addTopic(${resortIndex})">添加Topic</button><button onclick="deleteResort(${resortIndex})">删除Resort</button>` : ''}
                    <ul>
                        ${resort.topicList.map((topic, topicIndex) => `
                            <li>
                                Topic ID: ${isLoggedIn ? `<input type="text" value="${topic.topicId}" onchange="updateTopic(${resortIndex}, ${topicIndex}, 'topicId', this.value)">` : topic.topicId}
                                Title: ${isLoggedIn ? `<input type="text" value="${topic.topicTitle}" onchange="updateTopic(${resortIndex}, ${topicIndex}, 'topicTitle', this.value)">` : topic.topicTitle}
                                URL: ${isLoggedIn ? `<input type="text" value="${topic.topicURL}" onchange="updateTopic(${resortIndex}, ${topicIndex}, 'topicURL', this.value)">` : topic.topicURL}
                                ${isLoggedIn ? `<button onclick="deleteTopic(${resortIndex}, ${topicIndex})">删除Topic</button>` : ''}
                            </li>
                        `).join('')}
                    </ul>
                `;
                container.appendChild(resortDiv);
            });
        }

        function updateResortId(resortIndex, value) {
            data[resortIndex].resortId = value;
        }

        function addResort() {
            data.push({ resortId: '', topicList: [] });
            renderData();
        }

        function deleteResort(resortIndex) {
            data.splice(resortIndex, 1);
            renderData();
        }

        function addTopic(resortIndex) {
            data[resortIndex].topicList.push({ topicId: '', topicTitle: '', topicURL: '' });
            renderData();
        }

        function deleteTopic(resortIndex, topicIndex) {
            data[resortIndex].topicList.splice(topicIndex, 1);
            renderData();
        }

        function updateTopic(resortIndex, topicIndex, key, value) {
            data[resortIndex].topicList[topicIndex][key] = value;
        }

        function saveData() {
            fetch('save.php', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(data)
            })
            .then(response => response.text())
            .then(result => {
                alert(result);
            })
            .catch(error => {
                console.error('Error:', error);
            });
        }

        renderData();
    </script>
</body>
</html>