<?php
// ─────────────────────────────────────────────
// api/news_public.php
// Öffentlicher News-Endpunkt für die Landing Page
// Gibt IRCC-News aus der DB als JSON zurück
// CORS: come2canada.life darf abrufen
// ─────────────────────────────────────────────

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

c2c_cors_headers();

$limit = min((int)($_GET['limit'] ?? 5), 10);

try {
    $db   = C2CDatabase::get();
    $stmt = $db->prepare(
        "SELECT title, summary, published, link, category
         FROM ircc_news
         ORDER BY published DESC
         LIMIT ?"
    );
    $stmt->execute([$limit]);
    $news = $stmt->fetchAll();

    // Summary kürzen auf max 300 Zeichen
    foreach ($news as &$n) {
        if (!empty($n['summary']) && mb_strlen($n['summary']) > 300) {
            $n['summary'] = mb_substr($n['summary'], 0, 300);
        }
    }
    unset($n);

    json_response(['success' => true, 'news' => $news, 'count' => count($news)]);

} catch (Exception $e) {
    // Leere Liste zurückgeben — Frontend zeigt statischen Fallback
    json_response(['success' => true, 'news' => [], 'count' => 0]);
}
