<?php
require_once __DIR__ . '/header.php';
$pdo = db();

$group = $_GET['group'] ?? 'general';

// Handle Save
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    foreach ($_POST['settings'] as $key => $value) {
        $stmt = $pdo->prepare("UPDATE website_settings SET `value` = ? WHERE `key` = ?");
        $stmt->execute([$value, $key]);
    }
    header("Location: settings.php?group=$group&msg=saved");
    exit;
}

// Fetch settings
$stmt = $pdo->prepare("SELECT * FROM website_settings WHERE `group` = ?");
$stmt->execute([$group]);
$settings = $stmt->fetchAll();

$group_titles = [
    'general' => '基础设置',
    'contact' => '联系方式',
    'seo' => 'SEO设置'
];
?>

<div class="card">
    <div class="card-header"><?= $group_titles[$group] ?? '网站设置' ?></div>
    <div class="card-body">
        <form method="POST">
            <div class="row">
                <?php foreach ($settings as $s): ?>
                <div class="col-md-12 mb-4">
                    <label class="form-label fw-bold"><?= htmlspecialchars($s['label']) ?></label>
                    <div class="small text-muted mb-2">配置键: <code><?= htmlspecialchars($s['key']) ?></code></div>
                    
                    <?php if ($s['type'] === 'textarea'): ?>
                        <textarea name="settings[<?= $s['key'] ?>]" class="form-control" rows="4"><?= htmlspecialchars($s['value']) ?></textarea>
                    <?php elseif ($s['type'] === 'image'): ?>
                        <div class="input-group">
                            <input type="text" name="settings[<?= $s['key'] ?>]" id="input_<?= $s['key'] ?>" class="form-control" value="<?= htmlspecialchars($s['value']) ?>">
                            <button class="btn btn-outline-secondary" type="button" onclick="window.open('../<?= htmlspecialchars($s['value']) ?>')">查看预览</button>
                        </div>
                        <div class="mt-2">
                            <img src="../<?= htmlspecialchars($s['value']) ?>" style="max-height: 50px;" class="border rounded bg-light p-1">
                        </div>
                    <?php else: ?>
                        <input type="text" name="settings[<?= $s['key'] ?>]" class="form-control" value="<?= htmlspecialchars($s['value']) ?>">
                    <?php endif; ?>
                </div>
                <?php endforeach; ?>
            </div>
            
            <div class="mt-4 pt-4 border-top">
                <button type="submit" class="btn btn-primary px-5">保存所有更改</button>
            </div>
        </form>
    </div>
</div>

<?php require_once __DIR__ . '/footer.php'; ?>