<?php
require_once __DIR__ . "/../config.php";
require_once __DIR__ . "/../includes/functions.php";

// Check admin login
if (!isset($_SESSION['admin_logged_in']) || !$_SESSION['admin_logged_in']) {
    header("Location: login.php");
    exit();
}

$pageTitle = "FAQ bearbeiten";
$message = "";
$messageType = "";
$settings = getSystemSettings();

if ($_SERVER['REQUEST_METHOD'] === "POST" && isset($_POST['save_faq'])) {
    // Validate CSRF token
    if (!validateCsrfToken($_POST['csrf_token'] ?? "")) {
        $message = "Ungültiges Token. Bitte versuchen Sie es erneut.";
        $messageType = "error";
    } else {
        $content = isset($_POST['content']) ? (string) $_POST['content'] : "";
        $settings["startpage_intro_text"] = isset($_POST['startpage_intro_text'])
            ? (string) $_POST['startpage_intro_text']
            : "";

        if (saveFaqContent($content) && saveSystemSettings($settings)) {
            logAccess("Admin updated FAQ content");
            $message = "FAQ-Inhalt und Startseitentext wurden gespeichert.";
            $messageType = "success";
        } else {
            $message = "FAQ-Inhalt und/oder Startseitentext konnten nicht gespeichert werden.";
            $messageType = "error";
        }
    }
}

$faqContent = getFaqContent();
$settings = getSystemSettings();
$startpageIntroText = (string) ($settings["startpage_intro_text"] ?? "");

$bodyClass = "admin-page";
include __DIR__ . "/../includes/header.php";
?>

<div class="admin-header">
    <h2>FAQ bearbeiten</h2>
    <div>
        <a href="index.php" class="btn btn-secondary">Zurück zum Dashboard</a>
    </div>
</div>

<?php if ($message): ?>
    <div class="alert alert-<?php echo $messageType; ?>">
        <?php echo htmlspecialchars($message); ?>
    </div>
<?php endif; ?>

<div class="panel panel-lg">
    <p class="mb-2">
        Unterstützte Markdown-Syntax: <code>#</code>, <code>##</code>, <code>###</code>, <code>**fett**</code>, <code>*kursiv*</code>, Listen mit <code>-</code> oder <code>1.</code>, Links mit <code>[Text](https://example.com)</code>
    </p>

    <form method="POST">
        <?php echo csrfField(); ?>
        <div class="form-group">
            <label for="content">FAQ-Inhalt (Markdown)</label>
            <textarea id="content" name="content" rows="18"><?php echo htmlspecialchars(
                $faqContent,
            ); ?></textarea>
        </div>
        <div class="form-group">
            <label for="startpage_intro_text">Startseitentext</label>
            <textarea id="startpage_intro_text" name="startpage_intro_text" rows="6"><?php echo htmlspecialchars(
                $startpageIntroText,
            ); ?></textarea>
        </div>
        <button type="submit" name="save_faq" class="btn">Speichern</button>
    </form>
</div>

<?php include __DIR__ . "/../includes/footer.php"; ?>
