<?php

function artcloud_posts_render($attributes)
{
	$numberOfItems = isset($attributes['numberOfItems']) ? absint($attributes['numberOfItems']) : 3;
	$selected_post_ids = get_selected_post_ids($attributes);
	$args = build_query_args($attributes, $selected_post_ids);
	$query = new WP_Query($args);
	$recent_items = $query->get_posts();
	$row_id = ($attributes["selectedStyle"] == "style1") ? 'style1' : 'style2';
	$output = '<div ' . get_block_wrapper_attributes() . '">';
	$output .= '<div id="loadPost-' . $row_id . '">';
	if (!empty($recent_items)) {
		// Use different row IDs for style1 and style2
		$output .= '<h1 class="post-block-title" style="color:' . !empty($attributes['btnBackgroundColor']) . '">' . esc_html($attributes['title']) . '</h1>';
		$output .= '<div class="row">';

		foreach ($recent_items as $post) {
			$output .= '<div class="col-4">';
			$output .= render_post_item($post, $attributes);
			$output .= '</div>';
		}
		// Enable the button
		$output .= '</div>';
	} else {
		$output .= '<p>No item Selected</p>'; // Disable the button
	}
	$output .= '<div style="margin-top:40px !important;text-align: center;"><a href="#" id="load_more_posts-' . $row_id . '" class="wp-block-post-excerpt__more-link" data-attributes="' . esc_attr(json_encode($attributes)) . '" data-offset="' . $numberOfItems . '">Näytä lisää</a></div>';
	$output .= '</div>';
	$output .= '</div>';
	return $output;
}

function get_selected_post_ids($attributes)
{
	$selected_post_ids = [];

	if (isset($attributes['selectedTitles']) && !empty($attributes['selectedTitles'])) {
		foreach ($attributes['selectedTitles'] as $titleObj) {
			$post_id = $titleObj['id'];
			if (empty($post_id)) {
				$post = get_page_by_title($titleObj['title'], OBJECT, $attributes['postType']);
				$post_id = $post ? $post->ID : 0;
			}

			if ($post_id) {
				$selected_post_ids[] = $post_id;
			}
		}
	}

	return $selected_post_ids;
}

function build_query_args($attributes, $selected_post_ids)
{
	$args = [
		'post_type' => $attributes['postType'],
		'posts_per_page' => $attributes['numberOfItems'],
		'post_status' => 'publish',
		'orderby' => 'post__in',
		'order' => $attributes['order']
	];
	if (!empty($selected_post_ids)) {
		$args['post__in'] = $selected_post_ids;
	} elseif (!empty($attributes['categories'])) {
		$category_slugs = array();
		foreach ($attributes['categories'] as $category) {
			$category_slugs[] = $category['slug'] ? $category['slug'] : $category['value'];
		}
		$args['category_name'] = implode(',', $category_slugs);
		$args['orderby'] = $attributes['orderBy'];
	} else {
		$args['orderby'] = $attributes['orderBy'];
	}

	return $args;
}


function get_post_date_format($post, $attributes)
{
	return $attributes["selectedStyle"] == "style1" ? get_the_date('d.m.Y', $post) : get_the_date('d.m.Y H:i:s', $post);
}

function get_post_image_url($post_id, $attributes)
{
	return has_post_thumbnail($post_id) ? wp_get_attachment_image_src(get_post_thumbnail_id($post_id), 'medium') : plugin_dir_url(__FILE__) . 'assets/img/default-post.jpg';
}

function get_post_description($post_id, $attributes)
{
	$post_description = '';

	if ($attributes["displayDescription"]) {
		$post_description = get_the_excerpt($post_id);
		$word_count = str_word_count($post_description);
		$max_words = ($attributes["selectedStyle"] == "style1") ? 8 : 25;
		$post_description = implode(' ', array_slice(explode(' ', $post_description), 0, $max_words));
		if ($word_count > $max_words) {
			$post_description .= '...';
		}
	}

	return $post_description;
}


function render_post_item($post, $attributes)
{
	$post_id = $post->ID;
	$post_title = isset($post->post_title) ? $post->post_title : 'N/A';
	$post_readmore = get_permalink($post_id);
	$post_date = get_post_date_format($post, $attributes);
	if ($attributes['postType'] == 'event') {
		$speakers = get_the_terms($post->ID, 'campaign_speakers');
		foreach ($speakers as $speaker) {
			$author_name = $speaker->name;
		}
	} else {
		$author_name = get_the_author_meta('display_name', $post->post_author);
	}
	$defaultImage = site_url() . '/wp-content/plugins/artcloud-blocks/assets/img/default-image.jpg';
	$medium_image_url = get_post_image_url($post_id, $attributes);
	$post_image_url = $medium_image_url ? $medium_image_url[0] : $defaultImage;
	$allowed_extensions = array('jpg', 'jpeg', 'png', 'gif');
	if (empty($post_image_url) || !in_array(strtolower(pathinfo($post_image_url, PATHINFO_EXTENSION)), $allowed_extensions)) {
		$post_image_url = $defaultImage;
	}
	$post_description = get_post_description($post_id, $attributes);
	$backgroundColor = isset($attributes["backgroundColor"]) ? $attributes["backgroundColor"] : "";
	$textColor = isset($attributes["textColor"]) ? $attributes["textColor"] : "";
	$btnBackgroundColor = isset($attributes["btnBackgroundColor"]) ? $attributes["btnBackgroundColor"] : "";
	$btnTextColor = isset($attributes["btnTextColor"]) ? $attributes["btnTextColor"] : "";
	$selectedStyle = isset($attributes["selectedStyle"]) ? $attributes["selectedStyle"] : "style1";

	$commonParams = [
		'post_image_url' => $post_image_url,
		'post_date' => $post_date,
		'author_name' => $author_name,
		'textColor' => $textColor,
		'post_title' => $post_title,
		'post_description' => $post_description,
		'btnBackgroundColor' => $btnBackgroundColor,
		'btnTextColor' => $btnTextColor,
		'post_readmore' => $post_readmore,
		'backgroundColor' => $backgroundColor,
	];

	if ($selectedStyle == 'style1') {
		$output = render_style1($commonParams, $attributes);
	} else {
		$output = render_style2($commonParams, $attributes);
	}

	return $output;
}

function render_style1($params, $attributes)
{
	$output = '<div class="artcloud-item">';
	if ($attributes["displayFeaturedImage"]) {
		$output .= '<div class="artcloud-postImg">';
		$output .= '<a href="' . esc_url($params['post_readmore']) . '"><img src="' . esc_url($params['post_image_url']) . '" alt="' . esc_attr($params['post_title']) . '"></a>';
		$output .= '</div>';
	}
	$output .= render_common_structure($params, $attributes);
	$output .= '<a style="background-color:' . $params['btnBackgroundColor'] . ' ;color:' . $params['btnTextColor'] . '" href="' . esc_url($params['post_readmore']) . '" class="item-btns wp-block-post-excerpt__more-link">' . __('Lue lisää', 'artcloud-blocks') . '</a>';
	$output .= '</div>';
	$output .= '</div>';
	return $output;
}

function render_style2($params, $attributes)
{
	$output = '<div class="artcloud-item">';
	if ($attributes["displayFeaturedImage"]) {
		$output .= '<div class="artcloud-postImg">';
		$output .= '<a href="' . esc_url($params['post_readmore']) . '"><img src="' . esc_url($params['post_image_url']) . '" alt="' . esc_attr($params['post_title']) . '"></a>';
		$output .= '</div>';
	}
	$output .= render_common_structure($params, $attributes);
	$output .= '</div>';
	$output .= '</div>';
	return $output;
}

function render_common_structure($params, $attributes)
{
	$output = '<div class="artcloud-content">';
	if ($attributes["displayDateAuthor"]) {
		$output .= '<h6 style="color:' . $params['textColor'] . '">' . $params['post_date'] . ' | ' . $params['author_name'] . '</h6>';
	}
	$output .= '<a href="' . esc_url($params['post_readmore']) . '"><h3 style="color:' . $params['textColor'] . '">' . esc_html($params['post_title']) . '</h3></a>';
	$output .= '<p>' . wp_kses_post($params['post_description']) . '</p>';

	return $output;
}
