<?php
/**
 * Cron: Refresh News RSS Cache
 * Run: php cron/cache-news.php (every 15 minutes via crontab)
 * Crontab: star/15 * * * * cd /path/to/cincinnatifire && php cron/cache-news.php >> /tmp/cfd-news-cache.log 2>&1
 * (Replace "star" with asterisk)
 */

// Run from CLI only
if (php_sapi_name() !== 'cli') {
    http_response_code(403);
    die('CLI only');
}

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

echo "[" . date('Y-m-d H:i:s') . "] Starting news cache refresh...\n";

$db = getDB();
$feeds = [
    ['url' => env('NEWS_RSS_WCPO', 'https://www.wcpo.com/news/local-news/?format=rss'), 'source' => 'WCPO'],
    ['url' => env('NEWS_RSS_WLWT', 'https://www.wlwt.com/rss.xml'), 'source' => 'WLWT'],
];

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

foreach ($feeds as $feed) {
    echo "  Fetching {$feed['source']}... ";
    $xml = @file_get_contents($feed['url'], false, $ctx);
    if ($xml === false) {
        echo "FAILED\n";
        continue;
    }

    libxml_use_internal_errors(true);
    $rss = @simplexml_load_string($xml);
    if (!$rss) {
        echo "PARSE ERROR\n";
        continue;
    }

    $items = $rss->channel->item ?? $rss->entry ?? [];
    $count = 0;

    $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 ($items as $item) {
        $title = (string)($item->title ?? '');
        $link = (string)($item->link ?? '');
        $pubDate = (string)($item->pubDate ?? $item->published ?? '');

        if ($title === '') continue;

        try {
            $stmt->execute([
                ':title'  => $title,
                ':link'   => $link,
                ':source' => $feed['source'],
                ':pub'    => $pubDate ? date('Y-m-d H:i:s', strtotime($pubDate)) : date('Y-m-d H:i:s'),
            ]);
            $count++;
        } catch (Exception $e) {
            // Skip duplicates
        }
    }

    echo "{$count} articles\n";
    $totalInserted += $count;
}

// Clean old entries
$db->exec("DELETE FROM news_cache WHERE cached_at < DATE_SUB(NOW(), INTERVAL 7 DAY)");

echo "[" . date('Y-m-d H:i:s') . "] Done. Total: {$totalInserted} articles cached.\n";
