<?php

namespace ElementPack;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Class Admin Feeds
 */
class Admin_Feeds {

	private $settings;

	/**
	 * Static variable to track if the feed has been displayed
	 */
	private static $feed_displayed = false;

	/**
	 * Admin_Feeds constructor.
	 */
	public function __construct( $settings ) {
		$this->settings = $settings;
		add_action( 'wp_dashboard_setup', [ $this, 'register_rss_feeds' ] );
	}

	/**
	 * Register RSS Feeds for Element Pack
	 */
	public function register_rss_feeds() {
		if ( self::$feed_displayed ) {
			/**
			 * If the feed has already been displayed, do not add it again
			 */
			return;
		}

		wp_add_dashboard_widget(
			'bdt-dashboard-overview',
			esc_html( $this->settings['feed_title'] ),
			[ $this, 'display_rss_feeds_content' ],
			null,
			null,
			'column4',
			'core'
		);

		/**
		 * Mark the feed as displayed
		 */
		self::$feed_displayed = true;
	}

	/**
	 * Display RSS Feeds Content
	 */
	public function display_rss_feeds_content() {
		$feeds = $this->get_remote_feeds_data();
		if ( is_array( $feeds ) ) {
			foreach ( $feeds as $feed ) {
				?>
				<div class="activity-block">
					<a href="<?php echo esc_url( $feed->demo_link ); ?>" target="_blank" style="margin-bottom:10px; display: inline-block;">
						<img src="<?php echo esc_url( $feed->image ); ?>" style="width:100%;min-height:240px;">
					</a>
					<p>
						<?php echo wp_kses_post( wp_trim_words( wp_strip_all_tags( $feed->content ), 50 ) ); ?>
						<a href="<?php echo esc_url( $feed->demo_link ); ?>" target="_blank">
							<?php esc_html_e( 'Learn more...', 'bdthemes-element-pack' ); ?>
						</a>
					</p>
				</div>
				<?php
			}
		}
		echo wp_kses_post( $this->get_rss_posts_data() );
	}

	/**
	 * Get Remote Feeds Data
	 *
	 * @return array|mixed
	 */
	private function get_remote_feeds_data() {
		$transient_key = $this->settings['transient_key'];
		$cached_data   = get_transient( $transient_key );

		if ( ! empty( $cached_data ) ) {
			return json_decode( $cached_data );
		}

		$response = wp_remote_get( $this->settings['remote_feed_link'],
			array(
				'timeout' => 30,
				'headers' => array(
					'Accept' => 'application/json',
				),
			)
		);

		if ( is_wp_error( $response ) ) {
			return [];
		}

		$response_body = wp_remote_retrieve_body( $response );
		set_transient( $transient_key, $response_body, 6 * HOUR_IN_SECONDS );

		return json_decode( $response_body );
	}

	/**
	 * Get RSS Posts Data
	 *
	 * @return string
	 */
	private function get_rss_posts_data() {
		$transient_key = $this->get_rss_transient_key();
		$cached_data   = get_transient( $transient_key );

		if ( ! empty( $cached_data ) ) {
			$rss_items = json_decode( $cached_data, true );

			if ( ! empty( $rss_items ) ) {
				return $this->render_rss_posts_list( $rss_items );
			}

			delete_transient( $transient_key );
		}

		$rss_items = $this->fetch_rss_feed_items( $this->settings['feed_link'], 5 );

		if ( ! empty( $rss_items ) ) {
			set_transient( $transient_key, wp_json_encode( $rss_items ), 6 * HOUR_IN_SECONDS );
		}

		return $this->render_rss_posts_list( $rss_items );
	}

	/**
	 * Build a transient key that changes when the feed URL changes.
	 *
	 * @return string
	 */
	private function get_rss_transient_key() {
		return $this->settings['transient_key'] . '_rss_' . md5( $this->settings['feed_link'] );
	}

	/**
	 * Allow fetching RSS from private/local hosts configured in feed_link.
	 *
	 * WordPress blocks LAN IPs via reject_unsafe_urls; the browser can still open them.
	 *
	 * @param array  $args Request arguments.
	 * @param string $url  Request URL.
	 * @return array
	 */
	public function maybe_allow_feed_request( $args, $url ) {
		$feed_host = wp_parse_url( $this->settings['feed_link'], PHP_URL_HOST );
		$req_host  = wp_parse_url( $url, PHP_URL_HOST );

		if ( empty( $feed_host ) || empty( $req_host ) ) {
			return $args;
		}

		if ( strtolower( $feed_host ) === strtolower( $req_host ) ) {
			$args['reject_unsafe_urls'] = false;
		}

		return $args;
	}

	/**
	 * Fetch and normalize RSS feed items.
	 *
	 * @param string $feed_url Feed URL.
	 * @param int    $limit    Maximum number of items.
	 * @return array
	 */
	private function fetch_rss_feed_items( $feed_url, $limit = 5 ) {
		include_once ABSPATH . WPINC . '/feed.php';

		add_filter( 'http_request_args', array( $this, 'maybe_allow_feed_request' ), 10, 2 );

		$rss = fetch_feed( $feed_url );

		remove_filter( 'http_request_args', array( $this, 'maybe_allow_feed_request' ), 10 );

		if ( is_wp_error( $rss ) ) {
			return array();
		}

		$maxitems  = $rss->get_item_quantity( $limit );
		$rss_items = $rss->get_items( 0, $maxitems );

		if ( empty( $rss_items ) ) {
			return array();
		}

		return array_map(
			function ( $item ) {
				$timestamp = $item->get_date( 'U' );

				if ( empty( $timestamp ) ) {
					$timestamp = strtotime( (string) $item->get_date( 'Y-m-d H:i:s' ) );
				}

				$content = $item->get_content();

				if ( empty( $content ) ) {
					$content = $item->get_description();
				}

				return array(
					'title'   => $item->get_title(),
					'link'    => $item->get_permalink(),
					'date'    => $timestamp ? (int) $timestamp : 0,
					'content' => $content,
				);
			},
			$rss_items
		);
	}

	/**
	 * Render RSS posts list markup.
	 *
	 * @param array $rss_items Feed items.
	 * @return string
	 */
	private function render_rss_posts_list( $rss_items ) {
		ob_start();
		?>
		<div class="bdt-widget">
			<ul>
				<?php if ( empty( $rss_items ) ) : ?>
					<li><?php esc_html_e( 'Items Not Found', 'bdthemes-element-pack' ); ?>.</li>
				<?php else : ?>
					<?php foreach ( $rss_items as $item ) : ?>
						<li>
							<a target="_blank" href="<?php echo esc_url( $item['link'] ); ?>"
								title="<?php echo esc_attr( wp_date( get_option( 'date_format' ), $item['date'] ) ); ?>">
								<?php if ( $this->is_feed_item_new( $item['date'] ) ) : ?>
									<span class="bdt-feed-badge bdt-feed-badge--new"><?php esc_html_e( 'New', 'bdthemes-element-pack' ); ?></span>
								<?php endif; ?>
								<?php echo esc_html( $item['title'] ); ?>
							</a>
							<span class="bdt-date" style="display: block; margin: 0;">
								<?php echo esc_html( human_time_diff( $item['date'], time() ) . ' ' . __( 'ago', 'bdthemes-element-pack' ) ); ?>
							</span>
							<div class="bdt-summary">
								<?php echo esc_html( wp_html_excerpt( wp_strip_all_tags( $item['content'] ), 120 ) . ' [...]' ); ?>
							</div>
						</li>
					<?php endforeach; ?>
				<?php endif; ?>
			</ul>
		</div>
		<p class="community-events-footer" style="margin: 12px -12px 6px -12px; padding: 12px 12px 0px;">
			<?php
			$footer_links = $this->settings['footer_links'];
			$last_link    = end( $footer_links );

			foreach ( $footer_links as $link ) {
				printf(
					'<a href="%s" target="_blank">%s <span class="screen-reader-text"> (opens in a new tab)</span><span aria-hidden="true" class="dashicons dashicons-external"></span></a>',
					esc_url( $link['url'] ),
					esc_html( $link['title'] )
				);

				if ( $link !== $last_link ) {
					echo ' | ';
				}
			}
			?>
		</p>
		<?php
		return ob_get_clean();
	}

	/**
	 * Check if a feed item is "new" (published within the last 7 days).
	 *
	 * @param int|string $date Unix timestamp.
	 * @return bool
	 */
	private function is_feed_item_new( $date ) {
		$timestamp = is_numeric( $date ) ? (int) $date : strtotime( $date );
		if ( ! $timestamp ) {
			return false;
		}
		$cutoff = time() - ( 7 * DAY_IN_SECONDS );
		return $timestamp >= $cutoff;
	}
}

$settings = array(
	'feed_title'       => 'BdThemes News & Updates',
	'transient_key'    => 'bdthemes_product_feeds',
	'feed_link'        => 'https://bdthemes.com/feed',
	'remote_feed_link' => 'https://dashboard.bdthemes.io/wp-json/bdthemes/v1/product-feed/?product_category=element-pack',
	'text_domain'      => 'bdthemes',
	'footer_links'     => [ 
		[ 
			'url'   => 'https://bdthemes.com/blog/',
			'title' => 'Blog',
		],
		[ 
			'url'   => 'https://bdthemes.com/knowledge-base/',
			'title' => 'Docs',
		],
		[ 
			'url'   => 'https://store.bdthemes.com/',
			'title' => 'Get Pro',
		],
		[ 
			'url'   => 'https://feedback.elementpack.pro/announcements/',
			'title' => 'Changelog',
		],
	],
);

new Admin_Feeds( $settings );

