<?php
if ( ! class_exists( 'NISHIKI_BLOCKS_PRO_RSS' ) ) {
	/**
	 * RSS ブロックの設定
	 */
	class NISHIKI_BLOCKS_PRO_RSS {
		/**
		 * Construct.
		 */
		public function __construct() {
			add_filter( 'register_block_type_args', array( $this, 'custom_modify_block_args' ), 10, 2 );
		}

		/**
		 * ダイナミックブロックうに関する設定を追加
		 */
		public function custom_modify_block_args( $args, $block_type ) {
			$attributes = array(
							'numberOfItems'        => array(
								'type'    => 'number',
								'default' => 4,
							),
							'columns'              => array(
								'type'    => 'number',
								'default' => 2,
							),
							'defaultImage'         => array(
								'type'    => 'string',
								'default' => '',
							),
							'displayThumbnail'     => array(
								'type'    => 'boolean',
								'default' => true,
							),
							'displayAuthor'        => array(
								'type'    => 'boolean',
								'default' => true,
							),
							'displayDate'          => array(
								'type'    => 'boolean',
								'default' => true,
							),
							'textColor'            => array(
								'type'    => 'string',
								'default' => '',
							),
							'linkTarget'           => array(
								'type'    => 'boolean',
								'default' => true,
							),
							'rssUrl'               => array(
								'type'    => 'string',
								'default' => '',
							),
							'rssBackgroundColor'   => array(
								'type'    => 'string',
								'default' => '#ffffff',
							),
							'rssTextMainColor'     => array(
								'type'    => 'string',
								'default' => '#cccccc',
							),
							'rssTextSubColor'      => array(
								'type'    => 'string',
								'default' => '#444444',
							),
							'titleElement'         => array(
								'type'    => 'string',
								'default' => 'h2',
							),
							'thumbnailAspectRatio' => array(
								'type'    => 'string',
								'default' => '16-9',
							),
							'articleDesign' => array(
								'type'    => 'string',
								'default' => '',
							),
						);

			if ( 'nishiki-blocks-pro/rss' === $block_type ) {
				$args['attributes'] = $attributes;
				$args['render_callback'] = array( $this, 'sc_render' );
			}

			return $args;
		}

		/**
		 * ショートコード作成
		 *
		 * @param array $attributes 属性
		 * @return $rss_data
		 */
		public function sc_render( $attributes ) {
			$atts = shortcode_atts(
				array(
					'rssUrl'     => '',
					'linkTarget' => false,
				),
				$attributes
			);

			$rss_data             = '';
			$classes			  = [];
			$styles			      = [];
			$css                  = '';
			$column               = 'column-' . absint( $attributes['columns'] );

			// var_dump($attributes);

			if ( ! empty( $attributes['className'] ) ) {
				$classes[] = ' ' . $attributes['className'];
			}

			if ( empty( $attributes['rssUrl'] ) ) {
				return false;
			}

			// タイトル属性
			if ( ! empty( $attributes['titleElement'] ) ) {
				$title_element = $attributes['titleElement'];
			}

			// 投稿デザイン
			if ( ! empty( $attributes['articleDesign'] ) ) {
				$classes[] = 'has-' . $attributes['articleDesign'];
			}

			// Align
			if ( ! empty( $attributes['align'] ) ) {
				$classes[] = 'align' . $attributes['align'];
			}

			// delete_transient( 'nishiki_pro_rss_feed_' . get_the_ID() . '_' . $attributes['rssUrl'] );

			// $excerpt = $attributes['displayExcerpt'];

			// アイテムデータをキャッシュして、なかったらループで取得して配列に入れる
			$items_data = get_transient( 'nishiki_pro_rss_feed_' . get_the_ID() . '_' . $attributes['rssUrl'] );

			if ( false === $items_data ) {
				// キャッシュがなかったら取りに行く
				$rss = fetch_feed( $attributes['rssUrl'] );

				if ( is_wp_error( $rss ) ) {
					return 'RSS フィードの URL が正しくありません。';
				}

				// 連想配列に入れる
				// $thumbnail,$author,$date,$title

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

				$items_data = array();

				foreach ( $rss_items as $item ) {
					// $output .= $item->get_description();

					$thumbnail = '';

					// rss のthumbnailから取得
					if ( '' === $thumbnail ) {
						$thumbnail_tags = $item->get_item_tags( '', 'thumbnail' );
						if ( ! empty( $thumbnail_tags ) ) {
							// $thumbnail_url = $thumbnail_tags[0]['child']['']['url'][0]['data'];
							$thumbnail_url = $thumbnail_tags[0]['data'];
							if ( ! empty( $thumbnail_url ) ) {
								$thumbnail = $thumbnail_url;
							}
						}
					}

					// rss のenclosureから取得
					if ( '' === $thumbnail ) {
						$enclosure = $item->get_enclosure();
						if ( $enclosure && ! empty( $enclosure->thumbnails[0] ) ) {
							$thumbnail = $enclosure->thumbnails[0];
						}
					}

					// OGPから取得
					if ( '' === $thumbnail ) {
						$request = wp_remote_get( $item->get_link() );

						if ( ! is_wp_error( $request ) ) {
							if ( isset( $request ) && ! empty( $request ) && 200 === $request['response']['code'] ) {
								if ( preg_match( '/<meta.+?(property|name)=["\'](og:image|twitter:image)["\'][^\/>]*?content=["\']([^"\']+?)["\'].*?\/?>/is', $request['body'], $matches ) ) {
									if ( $matches[3] ) {
										$thumbnail = $matches[3];
									} else {
										$thumbnail = $this->get_content_image( $request['body'] );
									}
								} else {
									$thumbnail = $this->get_content_image( $request['body'] );
								}
							} else {
								$thumbnail = $this->get_content_image( $request['body'] );
							}
						}
					}

					$items_data[] = array(
						'title'     => $item->get_title(),
						'link'      => $item->get_permalink(),
						'date'      => $item->get_date( get_option( 'date_format' ) ),
						'author'    => ( is_object( $item->get_author() ) ? wp_strip_all_tags( $item->get_author()->get_name() ) : '' ),
						'thumbnail' => $thumbnail,
					);

					// print_r($items_data);
					set_transient( 'nishiki_pro_rss_feed_' . get_the_ID() . '_' . $attributes['rssUrl'], $items_data, 60 * 60 * 12 );
				}
			}

			if( $attributes['textColor'] ){
				$styles[] = 'color:' . esc_attr( $attributes['textColor'] ) . ';';
			}

			// インライン CSS を追加		
			if ( ! empty( $attributes['style'] ) ){
				$style = wp_style_engine_get_styles( $attributes['style'] );

				$css = $style['css'];
			}
			
			if( ! empty( $styles ) ){
				$css .= ' ' . trim( implode( '', $styles ) );
			}

			$classes[] = 'wp-block-nishiki-blocks-pro-rss-items';
			$classes[] = 'articles';
			$classes[] = 'flex';
			$classes[] = 'is-card';
			$classes[] = $column;

			$attributes_array = array(
				'class' => trim( implode( ' ', $classes ) ),
				'style' => $css,
			);

			$wrapper_attributes = get_block_wrapper_attributes( $attributes_array );

			// var_dump($attributes['className']);
//			$rss_data .= '<div class="wp-block-nishiki-blocks-pro-rss-items articles flex is-card column-' . absint( $attributes['columns'] ) . esc_attr( $article_design_class ) . esc_attr( $class_name ) . '">';
			$rss_data .= '<div ' . wp_kses_post( $wrapper_attributes ) . '>';

			$i = 0;
			if ( $items_data ) {
				$item_count = $attributes['numberOfItems'];
				if ( $attributes['numberOfItems'] > count( $items_data ) ) {
					$item_count = count( $items_data );
				}

				$linktarget = $attributes['linkTarget'];

				if ( $linktarget ) {
					$target = ' target="_blank" rel="noopener noreferrer"';
				} else {
					$target = '';
				}

				while ( $i < $item_count ) {
					$rss_data .= '<article>';
					if ( $attributes['displayThumbnail'] ) {
						if ( ! empty( $items_data[ $i ]['thumbnail'] ) ) {
							$featured_image = $items_data[ $i ]['thumbnail'];
						} else {
							$featured_image = $this->get_default_image( $attributes['defaultImage'] );
						}

						$aspect_ratio = ' aspect-ratio-' . $attributes['thumbnailAspectRatio'];

						$rss_data .= '<div class="post-image' . esc_attr( $aspect_ratio ) . '">';
						$rss_data .= '<a' . wp_kses_post( $target ) . ' class="wp-block-nishiki-blocks-pro-rss-item" href="' . esc_url( $items_data[ $i ]['link'] ) . '">';
						$rss_data .= '<figure><img src="' . esc_url( $featured_image ) . '" alt=""></figure>';
						$rss_data .= '</a></div>';
					}
					$rss_data .= '<div class="post-detail">';
					$rss_data .= '<a class="post-link" href="' . esc_url( $items_data[ $i ]['link'] ) . '">';
					$rss_data .= '<header><' . wp_kses_post( $title_element ) . ' class="post-title">' . esc_html( $items_data[ $i ]['title'] ) . '</' . wp_kses_post( $title_element ) . '></header>';
					$rss_data .= '</a>';
					if ( $attributes['displayDate'] || $attributes['displayAuthor'] ) {
						$rss_data .= '<footer>';
						if ( $attributes['displayDate'] ) {
							$rss_data .= '<span class="date">' . esc_html( $items_data[ $i ]['date'] ) . '</span>';
						}
						if ( $attributes['displayAuthor'] ) {
							$rss_data .= '<span class="author">' . esc_html( $items_data[ $i ]['author'] ) . '</span>';
						}
						$rss_data .= '</footer>';
					}
					$rss_data .= '</div>';
					$rss_data .= '</article>';
					++$i;
				}
			}

			$rss_data .= '</div>';

			return $rss_data;
		}

		/**
		 * Get Contents First Image
		 *
		 * @param string $content 本文
		 * @return $thumbnail
		 */
		public function get_content_image( $content ) {
			ob_start();
			ob_end_clean();
			preg_match_all( '/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $content, $matches );

			if ( isset( $matches[1][0] ) && ! is_wp_error( $matches[1][0] ) ) {
				$thumbnail = $matches[1][0];
			} else {
				$thumbnail = '';
			}

			// print_r('コンテンツから取得');

			return $thumbnail;
		}

		/**
		 * Get Default Image
		 *
		 * @param string $default_image 画像 URL
		 * @return $thumbnail
		 */
		public function get_default_image( $default_image ) {
			$thumbnail = '';

			if ( $default_image ) {
				$thumbnail = $default_image;
			} elseif ( get_theme_mod( 'setting_archive_default_image', '' ) ) {
				$image      = get_theme_mod( 'setting_archive_default_image' );
				$image_id   = attachment_url_to_postid( $image );
				$image_data = wp_get_attachment_image_src( $image_id, 'thumbnail' );
				if ( true === $image_data[3] ) {
					$image_thumbnail = $image_data[0];
					$thumbnail       = $image_thumbnail;
				} else {
					$thumbnail = $image;
				}
			}

			// print_r('デフォルトから取得');
			return $thumbnail;
		}

	}

	$output = new NISHIKI_BLOCKS_PRO_RSS();
}


