<?php
/**
 * Fetches and parses an RSS feed, using a local cache to improve performance.
 * @param string $feed_url The URL of the RSS feed.
 * @param int $limit The maximum number of items to return.
 * @return array An array of feed items.
 */
function fetch_rss_feed($feed_url, $limit = 5) {
    $cache_dir = $_SERVER['DOCUMENT_ROOT'] . '/cache/';
    $cache_file = $cache_dir . 'rss_' . md5($feed_url) . '.json';
    $cache_life = 3600; // Cache duration in seconds (1 hour)

    if (file_exists($cache_file) && (time() - filemtime($cache_file) < $cache_life)) {
        return json_decode(file_get_contents($cache_file), true);
    }

    // Use error suppression for file_get_contents in case the feed is down
    $xml_content = @file_get_contents($feed_url);
    if ($xml_content === FALSE) {
        // If fetching fails, return old cache if it exists, otherwise empty
        return file_exists($cache_file) ? json_decode(file_get_contents($cache_file), true) : [];
    }

    $xml = simplexml_load_string($xml_content);
    if ($xml === FALSE) {
        return [];
    }

    $items = [];
    $count = 0;
    foreach ($xml->channel->item as $item) {
        if ($count >= $limit) break;
        
        $items[] = [
            'title' => (string) $item->title,
            'link'  => (string) $item->link,
            'date'  => (string) $item->pubDate,
            'desc'  => (string) $item->description
        ];
        $count++;
    }

    if (!is_dir($cache_dir)) { @mkdir($cache_dir, 0755, true); }
    file_put_contents($cache_file, json_encode($items));

    return $items;
}
?>
