<?php
/**
 * Plugin Name: Gutenify Post List
 * Plugin URI: https://gutenify.com
 * Description: Post List block.
 * Version: 1.0.0
 * Author: Gutenify
 *
 * @package gutenify
 */

defined( 'ABSPATH' ) || exit;

/**
 * Renders the block on server.
 *
 * @param array $attributes The block attributes.
 *
 * @return string Returns the block content.
 */
function gutenify_render_block_post_list( $attributes ) {
	global $post;
	$args = array(
		'posts_per_page'   => ! empty( $attributes['query']['numberOfItems'] ) ? $attributes['query']['numberOfItems'] : 10,
		'post_status'      => 'publish',
		'order'            => ! empty( $attributes['query']['order'] ) ? $attributes['query']['order'] : 'desc',
		'orderby'          => ! empty( $attributes['query']['orderBy'] ) ? $attributes['query']['orderBy'] : 'date',
		'suppress_filters' => false,
		'post_type'        => ! empty( $attributes['query']['postTypes'] ) ? (array) $attributes['query']['postTypes'] : 'post',
		'category__in'     => array(),
		'post__not_in'     => array( get_the_ID() ),
	);
	if ( ! empty( $attributes['query']['selectedCategories'] ) ) {

		$args['category__in'] = array_column( $attributes['query']['selectedCategories'], 'id' );

	}

	if ( ! empty( $attributes['query']['tax']['category'] ) ) {

		$args['category__in'] = array_merge( $attributes['query']['tax']['category'], $args['category__in'] );

	}

	if ( ! empty( $attributes['query']['tax']['tag'] ) ) {
		$args['tag__in'] = $attributes['query']['tax']['tag'];
	}

	if ( ! empty( $attributes['query']['authorIds'] ) ) {
		$args['author__in'] = $attributes['query']['authorIds'];
	}

	if ( ! empty( $attributes['query']['postTypes'] ) && in_array( 'attachment', $attributes['query']['postTypes'] ) ) {
		$args['post_status'] = 'inherit';

	}
	$recent_posts = get_posts( $args );

	$formatted_posts = gutenify_get_post_info( $recent_posts );

	$block_style = null;

	if ( isset( $attributes['className'] ) && strpos( $attributes['className'], 'is-style-horizontal' ) !== false ) {

		$block_style = 'horizontal';

	} elseif ( isset( $attributes['className'] ) && strpos( $attributes['className'], 'is-style-stacked' ) !== false ) {

		$block_style = 'stacked';

	}

	return gutenify_post_list( $formatted_posts, $attributes );
}


/**
 * Renders the list and grid styles.
 *
 * @param array $posts Current posts.
 * @param array $attributes The block attributes.
 *
 * @return string Returns the block content for the list and grid styles.
 */
function gutenify_post_list( $posts, $attributes ) {
	$client_id   = ! empty( $attributes['blockClientId'] ) ? $attributes['blockClientId'] : '';
	$list_layout = ! empty( $attributes['blockAdvanceOptions']['postListLayout'] ) ? $attributes['blockAdvanceOptions']['postListLayout'] : 'layout-1';
	$class_name  = array( 'wp-block-gutenify-post-list', 'gutenify-section-' . $attributes['blockClientId'], 'gutenify-post-list-' . $attributes['layout'], 'gutenify--post-list--post-list-' . $list_layout, 'gutenify-post-list-version-2' );
	$class       = array( 'gutenify-post-list' );
	$styles      = array();
	$block_style = ! empty( $attributes['className'] ) && strpos( $attributes['className'], 'is-style-stacked' ) !== false ? 'stacked' : 'horizontal';
	$columns     = ! empty( $attributes['columns'] ) ? $attributes['columns'] : 1;
	$constants   = \gutenify\Helpers::plugin_constants();

	if ( isset( $attributes['className'] ) ) {
		array_push( $class_name, $attributes['className'] );
	}

	if ( isset( $attributes['align'] ) ) {
		array_push( $class_name, 'align' . $attributes['align'] );
	}

	if ( isset( $attributes['columns'] ) ) {
		array_push( $class, 'has-columns has-' . $attributes['columns'] . '-columns has-responsive-columns' );
	}

	if ( isset( $attributes['listPosition'] ) && 'right' === $attributes['listPosition'] && 'horizontal' === $block_style ) {
		array_push( $class, 'has-image-right' );
	}

	if ( isset( $attributes['imageSize'] ) && 'horizontal' === $block_style ) {
		array_push( $class, 'has-' . $attributes['imageSize'] . '-image' );
	}

	if ( isset( $attributes['imageStyle'] ) ) {
		array_push( $class, 'has-' . $attributes['imageStyle'] . '-image' );
	}

	if ( isset( $columns ) ) {
		array_push( $class_name, 'gutenify-post-list-col-' . $columns );
	}

	$class_name = apply_filters( 'gutenify_block_wrapper_class', esc_attr( implode( ' ', $class_name ) ), $attributes );

	$block_content = sprintf(
		'<div class="%1$s">',
		$class_name,
	);

	$list_items_markup = '';

	$constants         = \Gutenify\Helpers::plugin_constants();
	$default_image_url = $constants['core_base_url'] . 'assets/images/placeholder-attachment.png';
	foreach ( $posts as $post ) {

		$list_class       = '';
		$align_self_class = '';

		$list_items_markup .= '<div class="gutenify-post-list-item gutenify-post-list-item-wrapper inner-block-shadow">';
		$list_items_markup .= '<div class="gutenify-post-list-item-inner-wrapper">';

		if ( ! empty( $attributes['displayFeaturedImage'] ) ) {
			$thumbnail_url = $default_image_url;
			if ( has_post_thumbnail( $post['ID'] ) ) {
				$thumbnail_url = get_the_post_thumbnail_url( $post['ID'] );
			}

			$list_items_markup .= sprintf(
				'<div class="gutenify-post-list-thumb">
					<a class="image-hover-zoom" href="%1$s">
						<img src="%2$s" />
					</a>
				</div>',
				esc_url( $post['postLink'] ),
				esc_url( $thumbnail_url ),
				esc_url( $thumbnail_url )
			);

			if ( 'horizontal' === $block_style && ( ! isset( $attributes['displayPostContent'] ) || ! $attributes['displayPostContent'] ) && ( isset( $attributes['columns'] ) && 2 >= $attributes['columns'] ) ) {
				$align_self_class = 'self-center';
			}
		} else {
			$align_self_class = isset( $align_self_class ) ? $align_self_class . ' flex-start' : 'flex-start';
		}

		$list_items_markup .= sprintf(
			'<div class="gutenify-post-list-text-content %s">',
			esc_attr( $align_self_class )
		);

		if ( isset( $attributes['displayPostDate'] ) && $attributes['displayPostDate'] && 'stacked' === $block_style ) {

			$list_items_markup .= sprintf(
				'<time datetime="%1$s" class="wp-block-gutenify-posts__date">%2$s</time>',
				esc_url( $post['date'] ),
				esc_html( $post['dateReadable'] )
			);

		}

		$title = $post['title'];

		if ( ! $title ) {

			$title = _x( '(no title)', 'placeholder when a post has no title', 'gutenify' );

		}

		$list_items_markup .= sprintf(
			'<h3 class="gutenify-post-list-title"><a href="%1$s" rel="bookmark">%2$s</a></h3> ',
			$post['postLink'],
			$title
		);
		$meta_data          = '';
		if ( isset( $attributes['displayPostDate'] ) && $attributes['displayPostDate'] && 'horizontal' === $block_style ) {
			$meta_data .= sprintf(
				'<span class="posted-on"><time datetime="%1$s" class="gutenify-posts-date">%2$s</time></span>',
				esc_html( $post['date'] ),
				esc_html( $post['dateReadable'] )
			);

		}
		if ( ! empty( $attributes['displayPostAuthor'] ) ) {
			if ( ! get_the_author_meta( 'description' ) && post_type_supports( get_post_type(), 'author' ) ) {
				$meta_data .= '<span class="byline">';
				$meta_data .= sprintf(
					'%s',
					'<a href="' . esc_url( get_author_posts_url( $post['author_id'] ) ) . '" rel="author">' . esc_html( get_the_author_meta( 'display_name', $post['author_id'] ) ) . '</a>'
				);
				$meta_data .= '</span>';
			}
		}

		if ( ! empty( $attributes['displayPostCategories'] ) ) {
			/* translators: used between list items, there is a space after the comma. */
			$categories_list = get_the_category_list( __( ', ' ), '', $post['ID'] );
			if ( $categories_list ) {
				$meta_data .= sprintf(
					'<span class="cat-links">%s </span>',
					$categories_list // phpcs:ignore WordPress.Security.EscapeOutput
				);
			}
		}

		if ( ! empty( $meta_data ) ) {
			$list_items_markup .= sprintf( '<div class="gutenify-post-list-meta">%1$s</div>', $meta_data );
		}

		if ( isset( $attributes['displayPostContent'] ) && $attributes['displayPostContent'] ) {

			$post_excerpt       = $post['postExcerpt'];
			$trimmed_excerpt    = esc_html( wp_trim_words( $post_excerpt, $attributes['excerptLength'], ' &hellip; ' ) );
			$list_items_markup .= '<div class="entry-summary">';
			$list_items_markup .= sprintf(
				'<p>%1$s</p>',
				esc_html( $trimmed_excerpt )
			);

			if ( isset( $attributes['displayPostLink'] ) && $attributes['displayPostLink'] ) {

				$list_items_markup .= sprintf(
					'<a href="%1$s" class="more-link"><span class="more-button">%2$s<span class="screen-reader-text">%3$s</span></span></a>',
					esc_url( $post['postLink'] ),
					esc_html( $attributes['postLink'] ),
					esc_html( $post['title'] )
				);

			}

			$list_items_markup .= '</div>';
		}

		$list_items_markup .= '</div></div></div>';

	}

	$block_content .= $list_items_markup;
	// $block_content .= '</div>';
	$block_content .= '</div>';
	ob_start();
	echo $block_content; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
	$output = ob_get_contents();
	ob_end_clean();
	return $output;
}

/**
 * Load all translations for our plugin from the MO file.
 */
function gutenify_load_textdomain_block_post_list() {
	load_plugin_textdomain( 'gutenify', false, basename( __DIR__ ) . '/languages' );
}
add_action( 'init', 'gutenify_load_textdomain_block_post_list' );

/**
 * Registers all block assets so that they can be enqueued through Gutenberg in
 * the corresponding context.
 *
 * Passes translations to JavaScript.
 */
function gutenify_register_block_post_list() {

	// Register the block by passing the location of block.json to register_block_type.
	register_block_type(
		__DIR__,
		array(
			'render_callback' => 'gutenify_render_block_post_list',
		)
	);

	if ( function_exists( 'wp_set_script_translations' ) ) {
		/**
		 * May be extended to wp_set_script_translations( 'my-handle', 'my-domain',
		 * plugin_dir_path( MY_PLUGIN ) . 'languages' ) ). For details see
		 * https://make.wordpress.org/core/2018/11/09/new-javascript-i18n-support-in-wordpress/
		 */
		wp_set_script_translations( 'gutenify-block-post-list', 'gutenify' );
	}
}
add_action( 'init', 'gutenify_register_block_post_list' );


function gutenify_post_list_render_block ($block_content, $block){
	if ((isset($block['blockName']) && 'gutenify/post-list' !== $block['blockName'])|| is_admin()) {
		return $block_content;
	}

	$block_id = wp_unique_id('gtfy-');
	$block_client_id = !empty($block['attrs']['blockClientId']) ? 'gutenify-section-' . esc_attr($block['attrs']['blockClientId']) : $block_id;

	$block_content = new WP_HTML_Tag_Processor($block_content);
	$block_content->next_tag();
	$block_content->add_class($block_client_id);

	//selector
	$root_selector = '.' . $block_client_id . '.wp-block-gutenify-post-list' ;
	$inner_block_selector = $root_selector . ' .gutenify-post-list-item-inner-wrapper';
	$css ='';
	// echo '<pre>';
	// var_dump($css);
	$css .= $inner_block_selector . '{';

	//color
	if(!empty($block['attrs']['blockAdvanceOptions']['innerBlock']['textColor'])){
		$css .= 'color: ' . $block['attrs']['blockAdvanceOptions']['innerBlock']['textColor'] . ';';
	}

	//background Color
	if(!empty($block['attrs']['backgroundGradient'])){
		$css .= 'background:' . $block['attrs']['backgroundGradient'] . ';';
	}elseif(!empty($block['attrs']['backgroundColor'])){
		$css .= 'background:' . $block['attrs']['backgroundColor'] . ';';
	}elseif(!empty($block['attrs']['blockAdvanceOptions']['innerBlock']['backgroundGradient'])){
		$css .= 'background: ' .$block['attrs']['blockAdvanceOptions']['innerBlock']['backgroundGradient'] . ';';
	}elseif(!empty($block['attrs']['blockAdvanceOptions']['innerBlock']['backgroundColor'])){
		$css .= 'background: ' . $block['attrs']['blockAdvanceOptions']['innerBlock']['backgroundColor'] . ';';
	}

	//border color
	if(!empty($block['attrs']['blockAdvanceOptions']['innerBlock']['borderColor'])){
		$css .= 'border-color: ' . $block['attrs']['blockAdvanceOptions']['innerBlock']['borderColor'] . ';';
		// var_dump($block['attrs']['blockAdvanceOptions']['innerBlock']['borderColor']);
	}

	if ( ! empty( $block['attrs']['blockAdvanceOptions']['innerBlock']['borderWidth'] )  ) {
		$css .= 'border-style:solid;';
		if ( ! is_array( $block['attrs']['blockAdvanceOptions']['innerBlock']['borderWidth'] ) ) {
			$css .= 'border-width: ' . $block['attrs']['blockAdvanceOptions']['innerBlock']['borderWidth'] . 'px;';
		} else {
			$css .= \gutenify\Style_Helpers::box_control( $block['attrs']['blockAdvanceOptions']['innerBlock']['borderWidth'], 'border-', '-width');
		}
	}

	if ( ! empty( $block['attrs']['blockAdvanceOptions']['innerBlock']['borderRadius'] ) ) {
		$css .= \gutenify\Style_Helpers::border_radius_control( $block['attrs']['blockAdvanceOptions']['innerBlock']['borderRadius'] );
	}

	if ( ! empty( $block['attrs']['blockAdvanceOptions']['innerBlock']['boxShadow'] ) ) {
		$css .= \gutenify\Style_Helpers::custom_box_shadow_control( $block['attrs']['blockAdvanceOptions']['innerBlock']['boxShadow'] );
	}
	$css .='}';


	//thumbnail
	if(!empty($block['attrs']['blockAdvanceOptions']['innerBlock']['thumbnailMinHeight'])){
		$css .= $root_selector . '.wp-block-gutenify-post-list .gutenify-post-list-item-inner-wrapper .gutenify-post-list-thumb img {';
		$css .= 'height:' . $block['attrs']['blockAdvanceOptions']['innerBlock']['thumbnailMinHeight'] . ';}';
	}
	//padding
	if(!empty($block['attrs']['blockAdvanceOptions']['innerBlock']['contentPadding'])){
		// echo '<pre>';
		// var_dump($block['attrs']);

		$css .= $inner_block_selector . ' .gutenify-post-list-text-content{';
		if(!empty($block['attrs']['blockAdvanceOptions']['innerBlock']['contentPadding']['desktop']['top'])){
			$css .= 'padding-top:' . $block['attrs']['blockAdvanceOptions']['innerBlock']['contentPadding']['desktop']['top'] . ';';
		}
		if(!empty($block['attrs']['blockAdvanceOptions']['innerBlock']['contentPadding']['desktop']['bottom'])){
			$css .= 'padding-bottom:' . $block['attrs']['blockAdvanceOptions']['innerBlock']['contentPadding']['desktop']['bottom'] . ';';
		}
		if(!empty($block['attrs']['blockAdvanceOptions']['innerBlock']['contentPadding']['desktop']['left'])){
			$css .= 'padding-left:' .  $block['attrs']['blockAdvanceOptions']['innerBlock']['contentPadding']['desktop']['left'] . ';';
		}
		if(!empty($block['attrs']['blockAdvanceOptions']['innerBlock']['contentPadding']['desktop']['right'])){
			$css .= 'padding-right:' . $block['attrs']['blockAdvanceOptions']['innerBlock']['contentPadding']['desktop']['right'] . ';';
		}
		$css .='}';

		$css .= '@media only screen and (max-width: 992px) {';
		$css .= $inner_block_selector . ' .gutenify-post-list-text-content{';
		if(!empty($block['attrs']['blockAdvanceOptions']['innerBlock']['contentPadding']['tablet']['top'])){
			$css .= 'padding-top:' . $block['attrs']['blockAdvanceOptions']['innerBlock']['contentPadding']['tablet']['top'] . ';';
		}
		if(!empty($block['attrs']['blockAdvanceOptions']['innerBlock']['contentPadding']['tablet']['bottom'])){
			$css .= 'padding-bottom:' . $block['attrs']['blockAdvanceOptions']['innerBlock']['contentPadding']['tablet']['bottom'] . ';';
		}
		if(!empty($block['attrs']['blockAdvanceOptions']['innerBlock']['contentPadding']['tablet']['left'])){
			$css .= 'padding-left:' .  $block['attrs']['blockAdvanceOptions']['innerBlock']['contentPadding']['tablet']['left'] . ';';
		}
		if(!empty($block['attrs']['blockAdvanceOptions']['innerBlock']['contentPadding']['tablet']['right'])){
			$css .= 'padding-right:' . $block['attrs']['blockAdvanceOptions']['innerBlock']['contentPadding']['tablet']['right'] . ';';
		}
		$css .='}';
		$css .='}';

		$css .= '@media only screen and (max-width: 768px) {';

		$css .= $inner_block_selector . ' .gutenify-post-list-text-content{';
		if(!empty($block['attrs']['blockAdvanceOptions']['innerBlock']['contentPadding']['mobile']['top'])){
			$css .= 'padding-top:' . $block['attrs']['blockAdvanceOptions']['innerBlock']['contentPadding']['mobile']['top'] . ';';
		}
		if(!empty($block['attrs']['blockAdvanceOptions']['innerBlock']['contentPadding']['mobile']['bottom'])){
			$css .= 'padding-bottom:' . $block['attrs']['blockAdvanceOptions']['innerBlock']['contentPadding']['mobile']['bottom'] . ';';
		}
		if(!empty($block['attrs']['blockAdvanceOptions']['innerBlock']['contentPadding']['mobile']['left'])){
			$css .= 'padding-left:' .  $block['attrs']['blockAdvanceOptions']['innerBlock']['contentPadding']['mobile']['left'] . ';';
		}
		if(!empty($block['attrs']['blockAdvanceOptions']['innerBlock']['contentPadding']['mobile']['right'])){
			$css .= 'padding-right:' . $block['attrs']['blockAdvanceOptions']['innerBlock']['contentPadding']['mobile']['right'] . ';';
		}
		$css .='}';
		$css .='}';



	}


	if (!empty($block['attrs']['blockAdvanceOptions']['innerBlock']['postTitleSize'])) {
		$css .= $inner_block_selector . ' .gutenify-post-carousel-title { font-size: ' . esc_attr($block['attrs']['blockAdvanceOptions']['innerBlock']['postTitleSize']) . '; }';
	}

	//hover style
	$css .= $inner_block_selector . ':hover {';

	//color
	if(!empty($block['attrs']['blockAdvanceOptions']['innerBlock']['hoverTextColor'])){
		$css .= ' color: ' .$block['attrs']['blockAdvanceOptions']['innerBlock']['hoverTextColor'] . ';';
	}

	//background
	if(!empty($block['attrs']['hoverBackgroundGradient'])){
		$css .= 'background:' . $block['attrs']['hoverBackgroundGradient'] . ';';
	}elseif(!empty($block['attrs']['blockAdvanceOptions']['innerBlock']['hoverBackgroundGradient'])){
		$css .= 'background: ' .$block['attrs']['blockAdvanceOptions']['innerBlock']['hoverBackgroundGradient'] . ';';
	}elseif(!empty($block['attrs']['hoverBackgroundColor'])){
		$css .= 'background:' . $block['attrs']['hoverBackgroundColor'] . ';';
	}elseif(!empty($block['attrs']['blockAdvanceOptions']['innerBlock']['hoverBackgroundColor'])){
		$css .= 'background: ' . $block['attrs']['blockAdvanceOptions']['innerBlock']['hoverBackgroundColor'] . ';';
	}


	//border color
	if(!empty($block['attrs']['blockAdvanceOptions']['innerBlock']['hoverBorderColor'])){
		$css .= 'border-color: ' . $block['attrs']['blockAdvanceOptions']['innerBlock']['hoverBorderColor'] . ';';
	}

	if ( ! empty( $block['attrs']['blockAdvanceOptions']['innerBlock']['hoverBoxShadow'] ) ) {
		$css .= \gutenify\Style_Helpers::custom_box_shadow_control( $block['attrs']['blockAdvanceOptions']['innerBlock']['hoverBoxShadow'] );
	}

	$css .= '}';


	//font size
	if(!empty($block['attrs']['blockAdvanceOptions']['innerBlock']['postTitleSize'])){
		$css .= $root_selector . ' .gutenify-post-list-title{ font-size:' . $block['attrs']['blockAdvanceOptions']['innerBlock']['postTitleSize']. ';}';
	}

	$handle = 'gutenify-block-inline-handle';
	wp_add_inline_style('wp-block-library', $css);
	return $block_content->get_updated_html();
}

add_filter('render_block', 'gutenify_post_list_render_block', 200, 2);
