<?php
namespace admin\Blocks\Render;

use WP_Query;

class Forum_Posts {
	/**
	 * Render the Forum Posts block.
	 *
	 * @param array  $attributes Block attributes.
	 * @param string $content    Block content.
	 * @return string Rendered block HTML.
	 */
	public function render_forum_posts($attributes, $content)
	{
		if (!wp_style_is('bbpc-el-widgets', 'registered')) {
			if (defined('FORUMAX_FRONT_ASS')) {
				wp_register_style('bbpc-el-widgets', FORUMAX_STYLES . 'frontend/el-widgets.css');
			}
		}
		if (!wp_style_is('elegant-icon', 'registered')) {
			wp_register_style('elegant-icon', FORUMAX_VEND . 'elegant-icon/style.css');
		}
		wp_enqueue_style('bbpc-el-widgets');
		wp_enqueue_style('elegant-icon');

		$ppp = isset($attributes['ppp']) ? $attributes['ppp'] : 5;
		$order = isset($attributes['order']) ? $attributes['order'] : 'ASC';
		$orderBy = isset($attributes['orderBy']) ? $attributes['orderBy'] : 'date';
		$selectedForums = isset($attributes['selectedForums']) ? $attributes['selectedForums'] : [];
		$layout = isset($attributes['layout']) ? $attributes['layout'] : 'list';
		$columns = isset($attributes['columns']) ? $attributes['columns'] : 3;
		
		$pagination_type = isset($attributes['pagination_type']) ? $attributes['pagination_type'] : 'none';

		$show_meta = isset($attributes['show_meta']) ? $attributes['show_meta'] : true;
		$showAvatar = isset($attributes['showAvatar']) ? $attributes['showAvatar'] : true;
		$showExcerpt = isset($attributes['showExcerpt']) ? $attributes['showExcerpt'] : false;
		$showForumLink = isset($attributes['showForumLink']) ? $attributes['showForumLink'] : false;

		// Enforce free defaults when Pro is not active.
		$is_pro_active = function_exists( 'forumax_is_premium' ) && forumax_is_premium();
		if ( ! $is_pro_active ) {
			$layout          = 'list';
			$pagination_type = 'none';
			$showExcerpt     = false;
			$showForumLink   = false;
			$selectedForums  = [];
		}

		$title_color = isset($attributes['title_color']) ? $attributes['title_color'] : '';
		$meta_color = isset($attributes['meta_color']) ? $attributes['meta_color'] : '';
		$bg_color = isset($attributes['bg_color']) ? $attributes['bg_color'] : '';
		
		// Typography
		$title_font_size = isset($attributes['title_font_size']) ? $attributes['title_font_size'] : '';
		$title_font_weight = isset($attributes['title_font_weight']) ? $attributes['title_font_weight'] : '600';
		$title_line_height = isset($attributes['title_line_height']) ? $attributes['title_line_height'] : '';
		$meta_font_size = isset($attributes['meta_font_size']) ? $attributes['meta_font_size'] : '';
		$meta_line_height = isset($attributes['meta_line_height']) ? $attributes['meta_line_height'] : '';
		
		// Card Styling
		$card_border = isset($attributes['card_border']) ? $attributes['card_border'] : array();
		$card_border_width = isset($card_border['width']) ? $card_border['width'] : '1px';
		$card_border_style = isset($card_border['style']) ? $card_border['style'] : 'solid';
		$card_border_color = isset($card_border['color']) ? $card_border['color'] : '#eee';
		$card_border_radius = isset($card_border['radius']) ? $card_border['radius'] : '8px';
		$card_shadow = isset($attributes['card_shadow']) ? $attributes['card_shadow'] : '';
		$card_padding = isset($attributes['card_padding']) ? $attributes['card_padding'] : array();
		$card_padding_top = isset($card_padding['top']) ? $card_padding['top'] : '20px';
		$card_padding_right = isset($card_padding['right']) ? $card_padding['right'] : '20px';
		$card_padding_bottom = isset($card_padding['bottom']) ? $card_padding['bottom'] : '20px';
		$card_padding_left = isset($card_padding['left']) ? $card_padding['left'] : '20px';
		$card_gap = isset($attributes['card_gap']) ? $attributes['card_gap'] : 20;
		$card_hover_bg = isset($attributes['card_hover_bg']) ? $attributes['card_hover_bg'] : '';
		$card_hover_border = isset($attributes['card_hover_border']) ? $attributes['card_hover_border'] : '';
		
		// Pagination Colors
		$pagination_text_color = isset($attributes['pagination_text_color']) ? $attributes['pagination_text_color'] : '';
		$pagination_active_bg = isset($attributes['pagination_active_bg']) ? $attributes['pagination_active_bg'] : '#2271b1';
		$pagination_active_text = isset($attributes['pagination_active_text']) ? $attributes['pagination_active_text'] : '#ffffff';

		$unique_id = uniqid('bbpc-forum-posts-');

		$paged = (get_query_var('paged')) ? get_query_var('paged') : ((get_query_var('page')) ? get_query_var('page') : 1);

		$query_args = array(
			'post_type' => 'topic',
			'posts_per_page' => $ppp,
			'order' => $order,
			'paged' => $paged,
		);

		// Handle Filtering by Forum
		if (!empty($selectedForums)) {
			$query_args['post_parent__in'] = $selectedForums;
		}

		// Handle Ordering
		if ($orderBy === 'meta_value') {
			$query_args['meta_key'] = '_bbp_last_active_time';
			$query_args['orderby'] = 'meta_value';
		} else {
			$query_args['orderby'] = $orderBy;
		}

		$forum_posts = new WP_Query($query_args);

		$wrapper_classes = [
			'community-posts-wrapper',
			'bbpc-layout-' . $layout
		];

		$wrapper_attributes = get_block_wrapper_attributes([
			'class' => implode(' ', $wrapper_classes),
			'id' => $unique_id,
		]);

		ob_start();
		?>
		<style>
			/* Layout Styles */
			<?php if ($layout === 'grid'): ?>
				#<?php echo esc_attr($unique_id); ?> .bbpc-posts-list {
					display: grid;
					grid-template-columns: repeat(<?php echo intval($columns); ?>, 1fr);
					gap: <?php echo intval($card_gap); ?>px;
				}
				#<?php echo esc_attr($unique_id); ?> .bbpc-posts-list .community-post {
					flex-direction: column;
					align-items: flex-start;
					border: <?php echo esc_attr($card_border_width); ?> <?php echo esc_attr($card_border_style); ?> <?php echo esc_attr($card_border_color); ?>;
					padding-top: <?php echo esc_attr($card_padding_top); ?>;
					padding-right: <?php echo esc_attr($card_padding_right); ?>;
					padding-bottom: <?php echo esc_attr($card_padding_bottom); ?>;
					padding-left: <?php echo esc_attr($card_padding_left); ?>;
					border-radius: <?php echo esc_attr($card_border_radius); ?>;
					background: <?php echo $bg_color ? esc_attr($bg_color) : '#fff'; ?>;
					transition: all 0.3s ease;
					<?php if ($card_shadow): ?>
						box-shadow: <?php echo esc_attr($card_shadow); ?>;
					<?php endif; ?>
				}
				#<?php echo esc_attr($unique_id); ?> .bbpc-posts-list .community-post:hover {
					<?php if ($card_hover_bg): ?>
						background-color: <?php echo esc_attr($card_hover_bg); ?>;
					<?php else: ?>
						box-shadow: 0 5px 15px rgba(0,0,0,0.05);
						transform: translateY(-2px);
					<?php endif; ?>
					<?php if ($card_hover_border): ?>
						border-color: <?php echo esc_attr($card_hover_border); ?>;
					<?php endif; ?>
				}
				#<?php echo esc_attr($unique_id); ?> .bbpc-posts-list .community-post .post-content {
					margin-bottom: 0;
					width: 100%;
					flex-direction: column;
					align-items: flex-start;
				}
				#<?php echo esc_attr($unique_id); ?> .bbpc-posts-list .community-post .author-avatar {
					margin-bottom: 12px;
					margin-right: 20px;
				}
				#<?php echo esc_attr($unique_id); ?> .bbpc-posts-list .community-post .post-meta-wrapper {
					margin-top: 15px;
					width: 100%;
					border-top: 1px solid #f5f5f5;
					padding-top: 15px;
				}
			<?php else: ?>
				/* List Layout */
				#<?php echo esc_attr($unique_id); ?> .bbpc-posts-list .community-post {
					margin-bottom: <?php echo intval($card_gap); ?>px;
					border: <?php echo esc_attr($card_border_width); ?> <?php echo esc_attr($card_border_style); ?> <?php echo esc_attr($card_border_color); ?>;
					padding-top: <?php echo esc_attr($card_padding_top); ?>;
					padding-right: <?php echo esc_attr($card_padding_right); ?>;
					padding-bottom: <?php echo esc_attr($card_padding_bottom); ?>;
					padding-left: <?php echo esc_attr($card_padding_left); ?>;
					border-radius: <?php echo esc_attr($card_border_radius); ?>;
					background: <?php echo $bg_color ? esc_attr($bg_color) : 'transparent'; ?>;
					transition: all 0.3s ease;
					<?php if ($card_shadow): ?>
						box-shadow: <?php echo esc_attr($card_shadow); ?>;
					<?php endif; ?>
				}
				#<?php echo esc_attr($unique_id); ?> .bbpc-posts-list .community-post:hover {
					<?php if ($card_hover_bg): ?>
						background-color: <?php echo esc_attr($card_hover_bg); ?>;
					<?php endif; ?>
					<?php if ($card_hover_border): ?>
						border-color: <?php echo esc_attr($card_hover_border); ?>;
					<?php endif; ?>
				}
			<?php endif; ?>

			/* Pagination Styles */
			#<?php echo esc_attr($unique_id); ?> .bbpc-pagination {
				margin-top: 40px;
				padding-top: 30px;
				border-top: 1px solid #f0f0f0;
				text-align: center;
			}
			#<?php echo esc_attr($unique_id); ?> .bbpc-pagination ul {
				display: inline-flex;
				gap: 6px;
				list-style: none;
				padding: 0;
				margin: 0;
				flex-wrap: wrap;
				justify-content: center;
			}
			#<?php echo esc_attr($unique_id); ?> .bbpc-pagination .page-numbers {
				display: flex;
				align-items: center;
				justify-content: center;
				min-width: 40px;
				height: 40px;
				padding: 0 12px;
				color: <?php echo $pagination_text_color ? esc_attr($pagination_text_color) : '#666'; ?>;
				text-decoration: none;
				font-weight: 500;
				font-size: 14px;
				transition: all 0.25s ease;
			}
			#<?php echo esc_attr($unique_id); ?> .bbpc-pagination .page-numbers:hover {
				
				color: #333;
				transform: translateY(-1px);
			}
			#<?php echo esc_attr($unique_id); ?> .bbpc-pagination .page-numbers li {
				border:1px solid #e0e0e0;
				border-radius: 6px;
			}
			#<?php echo esc_attr($unique_id); ?> .bbpc-pagination .page-numbers.current {
				background: <?php echo esc_attr($pagination_active_bg); ?>;
				color: <?php echo esc_attr($pagination_active_text); ?>;
				border-color: <?php echo esc_attr($pagination_active_bg); ?>;
				box-shadow: 0 2px 4px rgba(34,113,177,0.3);
				cursor: default;
				border-radius: 6px;
			}
			#<?php echo esc_attr($unique_id); ?> .bbpc-pagination .page-numbers.current:hover {
				transform: none;
			}
			#<?php echo esc_attr($unique_id); ?> .bbpc-pagination .page-numbers.dots {
				border: none;
				background: transparent;
				box-shadow: none;
				color: #999;
				cursor: default;
			}
			#<?php echo esc_attr($unique_id); ?> .bbpc-pagination .page-numbers.dots:hover {
				transform: none;
				background: transparent;
			}
			#<?php echo esc_attr($unique_id); ?> .bbpc-pagination .page-numbers.prev,
			#<?php echo esc_attr($unique_id); ?> .bbpc-pagination .page-numbers.next {
				font-weight: 600;
			}


			/* Typography Styles */
			<?php if ($title_font_size): ?>
				#<?php echo esc_attr($unique_id); ?> .community-post .post-content .post-title,
				#<?php echo esc_attr($unique_id); ?> .community-post .post-content .post-title a {
					font-size: <?php echo intval($title_font_size); ?>px;
				}
			<?php endif; ?>
			
			#<?php echo esc_attr($unique_id); ?> .community-post .post-content .post-title,
			#<?php echo esc_attr($unique_id); ?> .community-post .post-content .post-title a {
				font-weight: <?php echo esc_attr($title_font_weight); ?>;
				<?php if ($title_line_height): ?>
					line-height: <?php echo floatval($title_line_height); ?>;
				<?php endif; ?>
			}
			
			<?php if ($meta_font_size): ?>
				#<?php echo esc_attr($unique_id); ?> .community-post .post-content .entry-content,
				#<?php echo esc_attr($unique_id); ?> .community-post .post-meta-wrapper .post-meta-info li a,
				#<?php echo esc_attr($unique_id); ?> .community-post .post-date {
					font-size: <?php echo intval($meta_font_size); ?>px;
				}
			<?php endif; ?>
			
			<?php if ($meta_line_height): ?>
				#<?php echo esc_attr($unique_id); ?> .community-post .post-content .entry-content,
				#<?php echo esc_attr($unique_id); ?> .community-post .post-meta-wrapper .post-meta-info li a,
				#<?php echo esc_attr($unique_id); ?> .community-post .post-date {
					line-height: <?php echo floatval($meta_line_height); ?>;
				}
			<?php endif; ?>

			<?php if ($title_color): ?>
				#<?php echo esc_attr($unique_id); ?> .community-post .post-content .post-title a {
					color:
						<?php echo esc_attr($title_color); ?>
					;
				}

			<?php endif; ?>
			<?php if ($meta_color): ?>
				#<?php echo esc_attr($unique_id); ?> .community-post .post-content .entry-content,
				#<?php echo esc_attr($unique_id); ?> .community-post .post-meta-wrapper .post-meta-info li a {
					color:
						<?php echo esc_attr($meta_color); ?>
					;
				}

			<?php endif; ?>
		</style>
		<div <?php echo $wrapper_attributes; ?>>
			<div class="bbpc-posts-list">
			<?php
			$delay = 0.1;
			while ($forum_posts->have_posts()):
				$forum_posts->the_post();
				$favoriters = bbp_get_topic_favoriters();
				$favorite_count = !empty($favoriters) ? $favoriters[0] : '0';
				?>
				<div class="community-post wow fadeInUp" data-wow-delay="<?php echo esc_attr( $delay ); ?>s">
				<?php $delay += 0.1; ?>
					<div class="post-content">
						<?php if ($showAvatar): ?>
							<div class="author-avatar">
								<?php
								echo wp_kses_post(bbp_get_topic_author_link(
									array(
										'post_id' => get_the_ID(),
										'size' => 40,
										'type' => 'avatar'
									)
								));
								?>
							</div>
						<?php endif; ?>
						<div class="entry-content">
							<h3 class="post-title" style="margin-bottom: 5px;">
								<a href="<?php the_permalink(); ?>"> <?php the_title(); ?> </a>
							</h3>
							
							<?php if ($showForumLink): ?>
								<div class="post-parent-forum" style="font-size: 0.85em; margin-bottom: 5px; opacity: 0.8;">
									<?php 
										$forum_id = bbp_get_topic_forum_id();
										echo esc_html__('In: ', 'forumax') . '<a href="' . esc_url(get_permalink($forum_id)) . '">' . esc_html(get_the_title($forum_id)) . '</a>'; 
									?>
								</div>
							<?php endif; ?>

							<?php if ($showExcerpt): ?>
								<div class="post-excerpt" style="font-size: 0.9em; margin-bottom: 10px;">
									<?php bbp_topic_excerpt(); ?>
								</div>
							<?php endif; ?>

							<div class="post-date">
								<?php
								esc_html_e('Last active: ', 'forumax');
								echo esc_html(bbp_get_forum_last_active_time(get_the_ID()));
								?>
							</div>

						</div>
					</div>
					<?php if ($show_meta): ?>
						<div class="post-meta-wrapper">
							<ul class="post-meta-info">
								<li>
									<a href="<?php bbp_topic_permalink(); ?>">
										<i class="icon_chat_alt"></i>
										<?php bbp_show_lead_topic() ? bbp_topic_reply_count(get_the_ID()) : bbp_topic_post_count(get_the_ID()); ?>
									</a>
								</li>
								<li>
									<a href="<?php bbp_topic_permalink(); ?>">
										<i class="icon_star_alt"></i> <?php echo esc_html($favorite_count); ?>
									</a>
								</li>
							</ul>
						</div>
					<?php endif; ?>
				</div>
				<?php
			endwhile;
			?>
			</div>
			<?php
			
			// Pagination Logic
			if ($pagination_type === 'numbers') {
				$big = 999999999; 
				echo '<div class="bbpc-pagination">';
				echo paginate_links(array(
					'base' => str_replace($big, '%#%', esc_url(get_pagenum_link($big))),
					'format' => '?paged=%#%',
					'current' => max(1, $paged),
					'total' => $forum_posts->max_num_pages,
					'prev_text' => '&laquo;',
					'next_text' => '&raquo;',
					'type' => 'list',
				));
				echo '</div>';
			} elseif ($pagination_type === 'load_more' && $forum_posts->max_num_pages > $paged) {
				// Basic Load More Button (Link to next page as fallback)
				$next_page_link = get_next_posts_page_link($forum_posts->max_num_pages);
				if ($next_page_link) {
					echo '<div class="bbpc-load-more-wrapper" style="text-align: center; margin-top: 20px;">';
					echo '<a href="' . esc_url($next_page_link) . '" class="bbpc-load-more-btn button" data-paged="' . ($paged + 1) . '" data-max-pages="' . $forum_posts->max_num_pages . '">' . esc_html__('Load More', 'forumax') . '</a>';
					echo '</div>';
				}
			}

			wp_reset_postdata();
			?>
		</div>
		<?php
		return ob_get_clean();
	}
}