<?php
/**
 * 站点配置模块 — logo上传 + 团队信息 + 维护原因
 */
$db = getDB();
$siteSettings = $db->query("SELECT * FROM settings WHERE group_name = 'site' ORDER BY sort_order")->fetchAll();

// 将设置转为键值对方便使用
$siteMap = [];
foreach ($siteSettings as $s) {
    $siteMap[$s['key_name']] = $s;
}
?>

<div class="toolbar">
    <div class="toolbar-title">站点配置</div>
</div>

<!-- 站点基础设置 -->
<div class="panel-card" style="margin-bottom:16px;">
    <div class="config-group">
        <div class="config-group-title"><i class="fas fa-globe"></i> 站点基础设置</div>
        <?php foreach ($siteSettings as $s): ?>
            <?php if ($s['key_name'] === 'site_logo'): ?>
            <div class="config-item">
                <div class="config-key">站点Logo</div>
                <div class="config-desc">网站Logo图片</div>
                <div class="config-value">
                    <div style="display:flex;align-items:center;gap:12px;">
                        <button class="btn-primary" onclick="uploadSiteLogo()" style="font-size:13px;padding:6px 12px;"><i class="fas fa-upload"></i> 上传Logo</button>
                        <input type="hidden" id="setting_<?php echo $s['id']; ?>" value="<?php echo htmlspecialchars($s['value']); ?>">
                        <span id="logo_status" style="font-size:13px;color:#6b7280;"><?php echo $s['value'] ? '已上传' : '未上传'; ?></span>
                    </div>
                    <?php if ($s['value']): ?>
                    <div style="margin-top:8px;"><img src="<?php echo htmlspecialchars($s['value']); ?>" style="max-width:80px;max-height:40px;border-radius:6px;"></div>
                    <?php endif; ?>
                </div>
            </div>
            <?php elseif ($s['key_name'] === 'site_closed'): ?>
            <div class="config-item">
                <div class="config-key">站点状态</div>
                <div class="config-desc"><?php echo htmlspecialchars($s['remark']); ?></div>
                <div class="config-value">
                    <select id="setting_<?php echo $s['id']; ?>" onchange="toggleMaintainReason()">
                        <option value="0" <?php echo $s['value'] === '0' ? 'selected' : ''; ?>>正常开放</option>
                        <option value="1" <?php echo $s['value'] === '1' ? 'selected' : ''; ?>>站点维护</option>
                    </select>
                </div>
            </div>
            <?php elseif ($s['key_name'] === 'site_closed_reason'): ?>
            <div class="config-item" id="maintain_reason_row" style="<?php echo ($siteMap['site_closed']['value'] === '1') ? '' : 'display:none;'; ?>">
                <div class="config-key">维护原因</div>
                <div class="config-desc">维护期间展示给用户的原因说明</div>
                <div class="config-value">
                    <textarea id="setting_<?php echo $s['id']; ?>" style="width:100%;max-width:300px;padding:8px 12px;border:1px solid #d1d5db;border-radius:6px;font-size:14px;min-height:60px;resize:vertical;"><?php echo htmlspecialchars($s['value']); ?></textarea>
                </div>
            </div>
            <?php else: ?>
            <div class="config-item">
                <div class="config-key"><?php echo htmlspecialchars($s['key_name']); ?></div>
                <div class="config-desc"><?php echo htmlspecialchars($s['remark']); ?></div>
                <div class="config-value">
                    <input type="text" id="setting_<?php echo $s['id']; ?>" value="<?php echo htmlspecialchars($s['value']); ?>">
                </div>
            </div>
            <?php endif; ?>
        <?php endforeach; ?>
    </div>
    <div style="text-align:right; margin-top:16px;">
        <button class="btn-primary" onclick="saveSiteConfig()"><i class="fas fa-save"></i> 保存站点配置</button>
    </div>
</div>

<!-- 团队信息设置 -->
<div class="panel-card" style="margin-bottom:16px;">
    <div class="config-group">
        <div class="config-group-title"><i class="fas fa-users"></i> 团队信息</div>
        <div style="padding:12px 0 8px; font-size:13px; color:#9ca3af;">
            前端"关于我们"页面将展示此处填写的团队标题和联系方式。
        </div>
        <?php
        $teamSettings = $db->query("SELECT * FROM settings WHERE group_name = 'team' ORDER BY sort_order")->fetchAll();
        $teamMap = [];
        foreach ($teamSettings as $s) {
            $teamMap[$s['key_name']] = $s;
        }
        ?>
        <?php foreach ($teamSettings as $s): ?>
            <div class="config-item">
                <div class="config-key"><?php echo htmlspecialchars($s['key_name']); ?></div>
                <div class="config-desc"><?php echo htmlspecialchars($s['remark']); ?></div>
                <div class="config-value">
                    <?php if ($s['key_name'] === 'team_contact'): ?>
                    <textarea id="setting_<?php echo $s['id']; ?>" style="width:100%;max-width:300px;padding:8px 12px;border:1px solid #d1d5db;border-radius:6px;font-size:14px;min-height:80px;resize:vertical;"><?php echo htmlspecialchars($s['value']); ?></textarea>
                    <?php else: ?>
                    <input type="text" id="setting_<?php echo $s['id']; ?>" value="<?php echo htmlspecialchars($s['value']); ?>">
                    <?php endif; ?>
                </div>
            </div>
        <?php endforeach; ?>
    </div>
    <div style="text-align:right; margin-top:16px;">
        <button class="btn-primary" onclick="saveTeamConfig()"><i class="fas fa-save"></i> 保存团队信息</button>
    </div>
</div>

<script>
function uploadSiteLogo() {
    var input = document.createElement('input');
    input.type = 'file';
    input.accept = 'image/jpeg,image/png,image/gif';
    input.onchange = function(e) {
        var file = e.target.files[0];
        if (!file) return;
        if (file.size > 2 * 1024 * 1024) {
            showToast('图片大小不能超过2MB', 'error');
            return;
        }
        var formData = new FormData();
        formData.append('action', 'upload_image');
        formData.append('file', file);
        formData.append('type', 'logo');

        fetch('<?php echo SITE_URL; ?>/admin/api.php', {
            method: 'POST',
            body: formData
        })
        .then(function(res) {
            return res.text().then(function(text) {
                try { return JSON.parse(text); }
                catch(e) { throw new Error('服务器响应异常'); }
            });
        })
        .then(function(result) {
            if (result.code === 1) {
                // 找到logo对应的隐藏input并设置值
                var logoInputs = document.querySelectorAll('input[type=hidden]');
                for (var i = 0; i < logoInputs.length; i++) {
                    if (logoInputs[i].id.indexOf('setting_') === 0) {
                        logoInputs[i].value = result.data.url;
                        break;
                    }
                }
                document.getElementById('logo_status').textContent = '已上传: ' + file.name;
                showToast('Logo上传成功', 'success');
            } else {
                showToast(result.msg || '上传失败', 'error');
            }
        })
        .catch(function(err) {
            showToast(err.message || '上传失败', 'error');
        });
    };
    input.click();
}

function toggleMaintainReason() {
    var closedSelect = null;
    var closedId = '<?php echo isset($siteMap['site_closed']) ? $siteMap['site_closed']['id'] : ''; ?>';
    closedSelect = document.getElementById('setting_' + closedId);
    var reasonRow = document.getElementById('maintain_reason_row');
    if (reasonRow) {
        reasonRow.style.display = closedSelect.value === '1' ? '' : 'none';
    }
}

function saveSiteConfig() {
    var data = {};
    <?php foreach ($siteSettings as $s): ?>
    var el = document.getElementById('setting_<?php echo $s['id']; ?>');
    if (el) data['<?php echo $s['id']; ?>'] = el.value;
    <?php endforeach; ?>

    apiRequest('save_site_config', data, function(res) {
        if (res.code === 1) {
            showToast(res.msg, 'success');
        } else {
            showToast(res.msg, 'error');
        }
    });
}

function saveTeamConfig() {
    var data = {};
    <?php foreach ($teamSettings as $s): ?>
    data['<?php echo $s['id']; ?>'] = document.getElementById('setting_<?php echo $s['id']; ?>').value;
    <?php endforeach; ?>

    apiRequest('save_site_config', data, function(res) {
        if (res.code === 1) {
            showToast(res.msg, 'success');
        } else {
            showToast(res.msg, 'error');
        }
    });
}
</script>
