<?php if ( !defined( 'ABSPATH' ) ) exit;//PHPの宣言と直接アクセスの拒否

/*** REST APIを使って複数のサイトから新着情報を取得して並び替えて表示させる（アイキャッチ付） ***/
function haup_rest_api_multi_latest_posts_with_thumbnails( $atts ) {
//パラメーターの指定
	$atts = shortcode_atts( array(
		'sites' => '', // サイトのURLをカンマ区切りで指定
		'number' => 5, // 取得する投稿数
		'display_count' => 5, // 表示する投稿数
		'order_by' => 'modified', // 並び順（modifiedまたはdate）
		'cache_time' => 3600, // キャッシュの有効期限（秒）
		'datetext' => '0',//日付の接頭辞
		'des' => '',
		'offset' => 0, // オフセット
		'size' => 'small',
		'column' => 0,
	), $atts );

//パラメーターが空またはショートコード内にない場合の初期値設定（エラー回避）
	if( empty( $atts['sites'] ) ){ $atts['sites'] = get_home_url(); }//空の場合は自サイトのホームURLをセット
	if( empty( $atts['number'] ) ){ $atts['number'] = '5';}
	if( empty( $atts['display_count'] ) ){ $atts['display_count'] = '5';}
	if( empty( $atts['order_by'] ) ){ $atts['order_by'] = 'modified';}
	if( empty( $atts['cache_time'] ) ){ $atts['cache_time'] = 3600;}
	if( empty( $atts['datetext'] ) ){ $atts['datetext'] = '0';}
	if( empty( $atts['des'] ) ){ $atts['des'] = '';}
	if( empty( $atts['offset'] ) ){ $atts['offset'] = 0;}
	if( empty( $atts['size'] ) ){ $atts['size'] = 'small';}
	if( empty( $atts['column'] ) ){ $atts['column'] = 0;}

//キャッシュキーを生成
	$cache_key = 'ha_rest_latest_posts_' . md5( $atts['sites'] . $atts['number'] . $atts['display_count'] . $atts['order_by'] .$atts['des'] . $atts['offset'] . $atts['size'] .$atts['column']) ;

//cache_timeが0の場合、キャッシュを削除して再取得
	if ( intval( $atts['cache_time'] ) === 0 ) {
		delete_transient( $cache_key );
	}

// キャッシュを取得
	$cached_posts = get_transient( $cache_key );

	if ( false !== $cached_posts ) {
		$posts = $cached_posts;
	} else {
		$sites = explode( ',', $atts['sites'] );
		$posts = [];

	foreach ( $sites as $site ) {
	// REST APIから新着投稿を取得
		$response = wp_remote_get( esc_url( $site . '/wp-json/wp/v2/posts?per_page=' . $atts['number'] ) );

		if ( is_array( $response ) && ! is_wp_error( $response ) ) {
			$body = json_decode( wp_remote_retrieve_body( $response ), true );
				if ( is_array( $body ) ) {
					foreach ( $body as $post ) {
					// アイキャッチ画像のIDを取得
						$thumbnail_id = $post['featured_media'];
						$thumbnail = '';

					// アイキャッチ画像のURLを取得
						if ( $thumbnail_id ) {
							$media_response = wp_remote_get( esc_url( $site . '/wp-json/wp/v2/media/' . $thumbnail_id ) );
							if ( is_array( $media_response ) && ! is_wp_error( $media_response ) ) {
								$media_body = json_decode( wp_remote_retrieve_body( $media_response ), true );

							if( $atts['size'] == 'small'){
								$image_size_info = $media_body['media_details']['sizes']['medium'];
							}else if( $atts['size'] == 'large' ){
								//$image_size_info = $media_body['media_details']['sizes']['large'];
								if (isset($media_body['media_details']['sizes']['large'])) {
									$image_size_info = $media_body['media_details']['sizes']['large'];
									} else {
									$image_size_info = $media_body['media_details']['sizes']['medium'];
								}
							}else{
								$image_size_info = $media_body['media_details']['sizes']['medium'];
							}

								//"medium"サイズのURLと幅・高さを取得
									$image_size_url = $image_size_info['source_url'];
									$image_size_width = $image_size_info['width'];
									$image_size_height = $image_size_info['height'];
							}
						}

					// 投稿データを追加
						$posts[] = array(
							'title' => $post['title']['rendered'],
							'description' => $post['excerpt']['rendered'],
							'link' => $post['link'],
							'date' => $post['date_gmt'], // 公開日を追加
							'modified' => $post['modified_gmt'], // 更新日を追加
							'thumbnail' => $image_size_url,
							'width' => $image_size_width,
							'height' => $image_size_height,
						);
					}
				}
		}
	}

		// 並び替えの基準を決定
			usort( $posts, function( $a, $b ) use ( $atts ) {
				$key = $atts['order_by'] === 'date' ? 'date' : 'modified';
				return strtotime( $b[$key] ) - strtotime( $a[$key] );
			});

		// 表示する投稿数で制限
			$posts = array_slice( $posts, intval($atts['offset']), intval($atts['display_count']));

		// キャッシュに保存
			set_transient( $cache_key, $posts, intval( $atts['cache_time'] )); // cache_timeを整数に変換
	}

// 投稿を表示
	if( $atts['size'] == 'small' ){
		$output = '<ul class="haup-mapi-card-wrapper">';
	}else if( $atts['size'] == 'large' ){
		$output = '<ul class="haup-mapi-card-wrapper" style="display: flex;flex-wrap: wrap;align-items: stretch;justify-content: space-between;">';
	}else{
		$output = '<ul class="haup-mapi-card-wrapper">';
	}


	foreach ( $posts as $post ) {//リストの繰り返しここから
		//サイトの日付フォーマットを格納
			$format = get_option( 'date_format' );

		//アイキャッチ画像があるかによって$image_htmlへ格納
			if ( $post['thumbnail'] ) {
				$img_html = '<a href="' . esc_url( $post['link'] ) . '"><img src="' . esc_url( $post['thumbnail'] ) . '" alt="' . esc_attr( $post['title'] ) . '" width="'.esc_attr($post['width']).'" height="'.esc_attr($post['height']).'"></a>';
			} else {
				$nothumb_text = __('No Thumbnail','hima-art-utility');
				$img_html = '<span>'.$nothumb_text.'</span>'; // アイキャッチ画像がない場合
			}
		
		//タイトルを$title_htmlへ格納
			$title_html = '<a href="' . esc_url( $post['link'] ) . '">' . esc_html( $post['title'] ) . '</a>';

		//抜粋を$description_htmlへ格納
			$description_html = $post['description'];
		//抜粋を表示するかどうかをパラメーターから判断して$descriへ格納
		if( $atts['des'] == '0' || empty($atts['des'])){
			$descri = '';
		}else if( $atts['des'] == '1' ){
			$descri = '<a href="' . esc_url( $post['link'] ) . '">' .$description_html . '</a>';
		}else{
			$descri = '';
		}

		//公開日・更新日を$moddate_html $date_htmlへ格納
			$moddate_html = '<a href="' . esc_url( $post['link'] ) . '">' . esc_html( gmdate( $format, strtotime( $post['modified'] ) ) ) . '</a>';
			$date_html = '<a href="' . esc_url( $post['link'] ) . '">' .esc_html( gmdate( $format, strtotime( $post['date'] ) ) ) . '</a>';
		
		//日付の接頭辞を設定
			//文字列
				$pub_text = __('Publish Date:','hima-art-utility');
				$mod_text = __('Modified Date:','hima-art-utility');

			//文字かアイコンかの分岐
			if($atts['datetext'] == '1'){
				$pub_tag = '<span class="icon-hauicon-webmark03" style="margin-right:4px;"></span>';
				$mod_tag = '<span class="icon-hauicon-webmark02" style="margin-right:4px;"></span>'; 
			}else{
				$pub_tag = '<span>'.$pub_text.'</span>';
				$mod_tag = '<span>'.$mod_text.'</span>';
			}

		//列数によって子スタイルを指定
		$columns = $atts['column'];
		$column_style = '100%';//初期値を指定（カラムが1または5以上の場合）
		if( $columns == 2 ){
			$column_style = 'calc( 100% / 2 - 16px * 2 )';
		}else if( $columns == 3 ){
			$column_style = 'calc( 100% / 3 - 10px * 3 )';
		}else if( $columns == 4 ){
			$column_style = 'calc( 100% / 4 - 8px * 4 )';
		}

		//出力するhtmlをまとめる
		//カードサイズによってdiv classを分岐
		if( $atts['size'] == 'small'){
			$card_li_class = '<li>';
			$card_inner_div_class = '<div class="haup-mapi-card-inner">';
			$card_img_div_class = '<div class="haup-mapi-card-img">';
			$card_content_div_class = '<div class="haup-mapi-card-content">';
			$card_title_div_class = '<div class="haup-mapi-card-title">';
			$card_date_div_class = '<div class="haup-mapi-card-date">';
			$card_description_div_class = '<div class="haup-mapi-card-description">';
		}else if( $atts['size'] == 'large' ){//「large」指定時にモバイルかどうかで列分割するかを判定
			if(haup_is_mobile()){
				$card_li_class = '<li>';
			}else{
				$card_li_class = '<li style="width:'.esc_attr($column_style).'">';
			}
			$card_inner_div_class = '<div class="haup-mapi-card-inner-large">';
			$card_img_div_class = '<div class="haup-mapi-card-img-large">';
			$card_content_div_class = '<div class="haup-mapi-card-content-large">';
			$card_title_div_class = '<div class="haup-mapi-card-title-large">';
			$card_date_div_class = '<div class="haup-mapi-card-date-large">';
			$card_description_div_class = '<div class="haup-mapi-card-description-large">';
		}else{
			$card_li_class = '<li>';
			$card_inner_div_class = '<div class="haup-mapi-card-inner">';
			$card_img_div_class = '<div class="haup-mapi-card-img">';
			$card_content_div_class = '<div class="haup-mapi-card-content">';
			$card_title_div_class = '<div class="haup-mapi-card-title">';
			$card_date_div_class = '<div class="haup-mapi-card-date">';
			$card_description_div_class = '<div class="haup-mapi-card-description">';
		}

		//コンテンツの出力
		$output .= $card_li_class;
		$output .= $card_inner_div_class;
		$output .= $card_img_div_class;
		$output .= $img_html;
		$output .= '</div>';
		$output .= $card_content_div_class;
		$output .= $card_title_div_class;
		$output .= $title_html;
		$output .= '</div>';
		$output .= $card_date_div_class;
		$output .= $mod_tag. $moddate_html;
		$output .= ' / ';
		$output .= $pub_tag. $date_html;
		$output .= '</div>';
		$output .= $card_description_div_class;
		$output .= $descri;
		$output .= '</div>';
		$output .= '</div>';
		$output .= '</div>';
		$output .= '</li>';

	}//リストの繰り返しここまで

		$output .= '</ul>';

	return $output;
}
add_shortcode( 'ha-latest-posts-with-thumbnails', 'haup_rest_api_multi_latest_posts_with_thumbnails' );


function haup_rest_api_latest_posts_with_thumbnails_style_init(){
if(haup_is_mobile()){
$custom_css_pre = hau_sanitize_css('
/* HAUP REST API Post List With Thumbnail For Mobile */
ul.haup-mapi-card-wrapper {
	list-style: none;
	padding-left: 0;
}

ul.haup-mapi-card-wrapper li {
	padding: 12px;
	border: 1px solid #eee;
	border-radius: 4px;
	margin-bottom:12px;
}

.haup-mapi-card-inner,
.haup-mapi-card-inner-large
{
	width: 100%;
}

.haup-mapi-card-content,
.haup-mapi-card-content-large
{
	width: 100%;
}

.haup-mapi-card-img img,
.haup-mapi-card-img-large img
{
	width: 100%;
	height: auto;
	object-fit: cover;
}

.haup-mapi-card-title,
.haup-mapi-card-title-large
{
	font-size: var(--wp--preset--font-size--large);
	font-weight:600;
}

.haup-mapi-card-date,
.haup-mapi-card-date-large
{
	font-size: var(--wp--preset--font-size--small);
	text-align:right;
}

.haup-mapi-card-title a,
.haup-mapi-card-description a,
.haup-mapi-card-date a,
.haup-mapi-card-title-large a,
.haup-mapi-card-description-large a,
.haup-mapi-card-date-large a
{
	text-decoration:none;
}
');
}else{
$custom_css_pre = hau_sanitize_css('
/* HAUP REST API Post List With Thumbnail For PC */
ul.haup-mapi-card-wrapper {
	list-style: none;
	padding-left: 0;
}

ul.haup-mapi-card-wrapper li {
	padding: 12px;
	border: 1px solid #eee;
	border-radius: 4px;
	margin-bottom:12px;
}

.haup-mapi-card-inner {
	display: flex;
	gap: 12px;
}

.haup-mapi-card-content {
	width: 100%;
}

.haup-mapi-card-img img {
	width: 150px;
	height: auto;
	max-height: 150px;
	object-fit: cover;
}

.haup-mapi-card-title {
	font-size: var(--wp--preset--font-size--large);
	font-weight:600;
}

.haup-mapi-card-date {
	font-size: var(--wp--preset--font-size--small);
	text-align:right;
}

.haup-mapi-card-title a,
.haup-mapi-card-description a,
.haup-mapi-card-date a
{
	text-decoration:none;
}

.haup-mapi-card-title a:hover,
.haup-mapi-card-description a:hover,
.haup-mapi-card-date a:hover
{
	text-decoration:underline;
}

.haup-mapi-card-inner-large {
	display: block;
	width: 100%;
}

.haup-mapi-card-img-large img {
	width: 100%;
	height: auto;
}

.haup-mapi-card-title-large {
	font-size: var(--wp--preset--font-size--large);
	font-weight:600;
}

.haup-mapi-card-date-large {
	font-size: var(--wp--preset--font-size--small);
	text-align:right;
}

.haup-mapi-card-title-large a,
.haup-mapi-card-description-large a,
.haup-mapi-card-date-large a
{
	text-decoration:none;
}

.haup-mapi-card-title-large a:hover,
.haup-mapi-card-description-large a:hover,
.haup-mapi-card-date-large a:hover
{
	text-decoration:underline;
}
');
}

//タブを除去
$custom_css_deltab = preg_replace('/\t+/', '', $custom_css_pre);
//改行を除去
$custom_css = str_replace(PHP_EOL, '', $custom_css_deltab);

//インラインで出力
	wp_add_inline_style( 'haup-front-and-blocks-style', $custom_css );
}
add_action('wp_enqueue_scripts','haup_rest_api_latest_posts_with_thumbnails_style_init');