<?php
// ─────────────────────────────────────────────
// includes/content_loader.php
// Lädt site_content aus DB für Landing Page.
// Fallback auf Standardwerte wenn DB leer.
// ─────────────────────────────────────────────

require_once __DIR__ . '/config.php';
require_once __DIR__ . '/db.php';

function c2c_content(string $section, string $key, string $default = ''): string {
    static $cache = null;

    if ($cache === null) {
        try {
            $stmt = C2CDatabase::get()->query(
                "SELECT section, `key`, `value` FROM site_content WHERE section != '_meta'"
            );
            $cache = [];
            foreach ($stmt->fetchAll() as $row) {
                $cache[$row['section']][$row['key']] = $row['value'];
            }
        } catch (Exception $e) {
            $cache = [];
        }
    }

    return htmlspecialchars($cache[$section][$key] ?? $default, ENT_QUOTES, 'UTF-8');
}

// Rohwert ohne htmlspecialchars (für nl2br etc.)
function c2c_raw(string $section, string $key, string $default = ''): string {
    static $rawCache = null;

    if ($rawCache === null) {
        try {
            $stmt = C2CDatabase::get()->query(
                "SELECT section, `key`, `value` FROM site_content WHERE section != '_meta'"
            );
            $rawCache = [];
            foreach ($stmt->fetchAll() as $row) {
                $rawCache[$row['section']][$row['key']] = $row['value'];
            }
        } catch (Exception $e) {
            $rawCache = [];
        }
    }

    return $rawCache[$section][$key] ?? $default;
}

// Features-Liste: Zeilenumbrüche → Array
function c2c_features(string $section, string $key): array {
    $raw   = c2c_raw($section, $key, '');
    $lines = array_filter(array_map('trim', explode("\n", $raw)));
    return array_values($lines);
}

// Preis formatiert
function c2c_price(string $section, string $key, string $default = '0'): string {
    $val = c2c_raw($section, $key, $default);
    return number_format((float)$val, 0, '.', "'");
}
