<?php
// ─────────────────────────────────────────────
// api/content.php
// GET  → Inhalte für Landing Page liefern
// POST → Inhalte aus HQ-Editor speichern
// ─────────────────────────────────────────────

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

c2c_cors_headers();

$method = $_SERVER['REQUEST_METHOD'];

// ── GET: alle Inhalte als JSON ────────────────
if ($method === 'GET') {
    $section = $_GET['section'] ?? null;
    $db      = C2CDatabase::get();

    if ($section) {
        $stmt = $db->prepare(
            "SELECT `key`, `value` FROM site_content WHERE section = ?"
        );
        $stmt->execute([$section]);
    } else {
        $stmt = $db->query(
            "SELECT section, `key`, `value` FROM site_content ORDER BY section, id"
        );
    }

    $rows = $stmt->fetchAll();

    // Flaches Array: section.key => value  (oder key => value bei section-Filter)
    $out = [];
    foreach ($rows as $row) {
        if ($section) {
            $out[$row['key']] = $row['value'];
        } else {
            $out[$row['section']][$row['key']] = $row['value'];
        }
    }

    json_response(['success' => true, 'content' => $out]);
}

// ── POST: Inhalte speichern (nur mit Token) ───
if ($method === 'POST') {
    require_api_token();

    $input = json_decode(file_get_contents('php://input'), true);
    if (empty($input['content']) || !is_array($input['content'])) {
        json_response(['error' => 'Keine Inhalte übergeben'], 422);
    }

    $db      = C2CDatabase::get();
    $saved   = 0;

    // Format: [['section'=>'hero','key'=>'headline','value'=>'...'}, ...]
    // ODER:   {'hero.headline': '...', ...}
    foreach ($input['content'] as $item) {
        if (!isset($item['section'], $item['key'])) continue;

        $stmt = $db->prepare("
            INSERT INTO site_content (section, `key`, `value`)
            VALUES (?, ?, ?)
            ON DUPLICATE KEY UPDATE `value` = VALUES(`value`), updated_at = NOW()
        ");
        $stmt->execute([
            $item['section'],
            $item['key'],
            $item['value'] ?? '',
        ]);
        $saved++;
    }

    // Cache-Bust: Timestamp in DB speichern
    $db->prepare("
        INSERT INTO site_content (section, `key`, `value`, type, label)
        VALUES ('_meta', 'last_saved', NOW(), 'text', 'Zuletzt gespeichert')
        ON DUPLICATE KEY UPDATE `value` = NOW(), updated_at = NOW()
    ")->execute();

    json_response(['success' => true, 'saved' => $saved]);
}

json_response(['error' => 'Method not allowed'], 405);
