<?php
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

class Builder_Mosaic_RSS extends Builder_Mosaic_Provider {

	/**
	 * @type float
	 */
	private static $cache_lifetime=0;

	public static function get_items(array &$settings,int $limit,int $paged ):array {
		$settings+=array(
			'rss_feeds' => array(),
			'rss_cache_lifetime' => 12,
		);
		$feeds = wp_list_pluck( $settings['rss_feeds'], 'feed_url' );
		if ( empty ( $feeds ) ) {
			return ['error'=>__('No feed has been specified.', 'builder-mosaic' )]; 
		}

		if ( ! empty( $settings['rss_cache_lifetime'] ) ) {
			self::$cache_lifetime = (float) $settings['rss_cache_lifetime'];
			add_filter( 'wp_feed_cache_transient_lifetime', array( __CLASS__, 'filter_cache_transient_lifetime' ), 999 );
		}

		$rss = fetch_feed( $feeds );
		if ( is_wp_error( $rss ) ) {
			$error=$rss->get_error_message();
			if(is_array($error)){
				$error=$error[0];
			}
			return ['error'=>$error]; 
		}
		if ( ! $rss->get_item_quantity() ) {
			$rss->__destruct();
			return ['error'=>__( 'An error has occurred, which probably means the feed is down. Try again later.', 'builder-mosaic' )]; 
		}

		$items = array();
		$query = $rss->get_items( ( $paged - 1 ) * $limit, $limit );
		foreach ( $query as $item ) {
			$_item = self::get_item( $item );
			if ( $_item ) {
				$items[] = $_item;
			}
		}

		remove_filter( 'wp_feed_cache_transient_lifetime', array( __CLASS__, 'filter_cache_transient_lifetime' ), 999 );
		self::$cache_lifetime=0;
		return array(
			'items' => $items,
			'total_items' => $rss->get_item_quantity()
		);
	}

	private static function get_item( $item ):array {
		return array(
			'css_classes' => '',
			'image' => self::get_first_image( $item->get_content() ),
			'link' => $item->get_permalink(),
			'title' => $item->get_title(),
			'text' => strip_tags( $item->get_description(), '<b>,<i>,<a>,<strong>,<em>,<small>,<big>,<abbr>,<acronym>,<cite>,<dfn>,<sub>,<sup>' ),
			'badge' => ( $category = $item->get_category() ) ? $category->get_label() : '',
		);
	}

	/**
	 * Returns the first <img> tag found within $content.
	 */
	private static function get_first_image(string $content ):string {
		$first_img = '';
		preg_match_all( '/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $content, $matches );
		if ( isset( $matches [1] [0] ) ) {
			$first_img = $matches [1] [0];
		}

		return $first_img;
	}

	/**
	 * Filters "wp_feed_cache_transient_lifetime" to change how long
	 * RSS feeds should be cached
	 */
	public static function filter_cache_transient_lifetime(float $time ):float {
		return self::$cache_lifetime * 60 * 60;
	}
}