<?php
/**
 * News Feed — WLWT RSS + NewsAPI.org
 * Caches headlines in DB for 15 minutes.
 */
require_once __DIR__ . '/../config/auth.php';
requireLogin();

$db = getDB();

// Check DB cache freshness
$cacheCheck = $db->query("SELECT cached_at FROM news_cache ORDER BY cached_at DESC LIMIT 1")->fetch();
$cacheAge = $cacheCheck ? (time() - strtotime($cacheCheck['cached_at'])) : PHP_INT_MAX;

if ($cacheAge < 900) {
    $articles = $db->query("SELECT title, link, source, published_at FROM news_cache ORDER BY published_at DESC LIMIT 30")->fetchAll();
    jsonResponse(['articles' => $articles, 'cached' => true]);
}

$allArticles = [];
$ctx = stream_context_create(['http' => ['timeout' => 10, 'ignore_errors' => true, 'user_agent' => 'CFDPortal/1.0']]);

// Source 1: WLWT RSS
$rssUrl = 'https://www.wlwt.com/topstories-rss';
$xml = @file_get_contents($rssUrl, false, $ctx);
if ($xml !== false) {
    libxml_use_internal_errors(true);
    $rss = @simplexml_load_string($xml);
    if ($rss) {
        $items = $rss->channel->item ?? [];
        foreach ($items as $item) {
            $title = (string)($item->title ?? '');
            $link = (string)($item->link ?? '');
            $pubDate = (string)($item->pubDate ?? '');
            if ($title === '') continue;
            $allArticles[] = [
                'title'        => $title,
                'link'         => $link,
                'source'       => 'WLWT',
                'published_at' => $pubDate ? date('Y-m-d H:i:s', strtotime($pubDate)) : date('Y-m-d H:i:s'),
            ];
        }
    }
}

// Source 2: NewsAPI.org — Cincinnati news
$newsApiKey = env('NEWSAPI_KEY', '8614f655ad5e435f9f4f26ea58b4b1cd');
if ($newsApiKey) {
    $apiUrl = "https://newsapi.org/v2/everything?q=Cincinnati&sortBy=publishedAt&pageSize=15&language=en&apiKey={$newsApiKey}";
    $apiResp = @file_get_contents($apiUrl, false, $ctx);
    if ($apiResp !== false) {
        $apiData = json_decode($apiResp, true);
        foreach (($apiData['articles'] ?? []) as $a) {
            $title = $a['title'] ?? '';
            if ($title === '' || $title === '[Removed]') continue;
            $allArticles[] = [
                'title'        => $title,
                'link'         => $a['url'] ?? '',
                'source'       => $a['source']['name'] ?? 'News',
                'published_at' => isset($a['publishedAt']) ? date('Y-m-d H:i:s', strtotime($a['publishedAt'])) : date('Y-m-d H:i:s'),
            ];
        }
    }
}

// Update DB cache
if (!empty($allArticles)) {
    $db->exec("DELETE FROM news_cache WHERE cached_at < DATE_SUB(NOW(), INTERVAL 24 HOUR)");

    $stmt = $db->prepare("INSERT INTO news_cache (title, link, source, published_at, cached_at) VALUES (:title, :link, :source, :pub, NOW()) ON DUPLICATE KEY UPDATE cached_at = NOW()");
    foreach (array_slice($allArticles, 0, 50) as $a) {
        try {
            $stmt->execute([
                ':title'  => $a['title'],
                ':link'   => $a['link'],
                ':source' => $a['source'],
                ':pub'    => $a['published_at'],
            ]);
        } catch (Exception $e) {
            // Skip duplicates
        }
    }
}

$articles = $db->query("SELECT title, link, source, published_at FROM news_cache ORDER BY published_at DESC LIMIT 30")->fetchAll();
jsonResponse(['articles' => $articles, 'cached' => false]);
