<?php
function artcloud_rss_feed_render($attributes)
{
	$rssAttr_json = json_encode($attributes);

	$output = '<script>';
	$output .= 'var rssFeedAttr = ' . $rssAttr_json . ';';
	$output .= '</script>';

	$numberOfItems = isset($attributes['numberOfItems']) ? absint($attributes['numberOfItems']) : 3;
	$backgroundColor = isset($attributes["backgroundColor"]) ? $attributes["backgroundColor"] : "";
	$textColor = isset($attributes["textColor"]) ? $attributes["textColor"] : "";
	$titleTextColor = isset($attributes["titleTextColor"]) ? $attributes["titleTextColor"] : "";

	$output .= '<div ' . get_block_wrapper_attributes() . '>';
	if (!empty($attributes['items'])) {
		$output .= '<h1 class="rss-block-title" style="color:' . $titleTextColor . '">' . esc_html($attributes['title']) . '</h1>';
		$output .= '<div class="container">';
		$output .= '<div class="row" id="artcloud-rss-feed">';
		foreach (array_slice($attributes['items'], 0, $numberOfItems) as $item) {
			$itemDate = $item['pubDate'];
			$gmt_datetime = new DateTime($itemDate, new DateTimeZone('GMT'));
			$eet_datetime = $gmt_datetime->setTimezone(new DateTimeZone('EET'));
			$eet_date_time = $eet_datetime->format('d.m.Y H:i:s e');

			$output .= '<div class="artcloud-item col-4" style="background-color:' . $backgroundColor . ';">';
			$output .= '<div class="artcloud-postImg">';
			$output .= '<a href="' . $item['link'] . '"></a><img decoding="async" src="' . $item['enclosure']['link'] . '" width="100%" height="252px" alt=""></a></div>';
			$output .= '<div class="artcloud-content">';
			$output .= '<h6 style="color:' . $textColor . '">' . $eet_date_time . '</h6>';
			$output .= '<a href="' . $item['link'] . ' ">';
			$output .= '<h3 style="color:' . $textColor . '">' . mb_substr($item['title'], 0, 75, 'UTF-8') . '</h3></a>';
			$output .= '<p>' . mb_substr($item['description'], 0, 175, 'UTF-8') . '</p>';
			$output .= '</div></div>';
		}
		$output .= '</div>';
		$output .= '</div>';
		$output .= '<div style="margin-top: 40px !important; text-align: center;"><a href="#" id="load_more_rss" class="wp-block-rss-excerpt__more-link" data-offset="' . $numberOfItems . '">Näytä lisää</a></div>';
	} else {
		$output .= __('Please Add/Check the RSS URL', 'artcloud-blocks');
	}
	$output .= '</div>';
	return $output;
}
//
add_action('wp_ajax_artcloud_load_more_rss', 'artcloud_load_more_rss_callback');
add_action('wp_ajax_nopriv_artcloud_load_more_rss', 'artcloud_load_more_rss_callback');

function artcloud_load_more_rss_callback()
{
	header('Content-Type: application/json');
	$offset = $_POST['offset'];
	$attributesItems = $_POST['attributes'];
	$numberOfItems = isset($_POST['numberOfItems']) ? absint($_POST['numberOfItems']) : 3;
	$items = array_slice($attributesItems['items'], $offset, $numberOfItems);
	$output = json_encode($items);
	print_r($output);
	wp_die();
}
