<?php
/*
Template Name: Шаблон страницы Отзывы
*/
?>
<?php
get_header();
$post_id = get_the_ID();

$page_breadcrumbs = carbon_get_post_meta( $post_id, 'page_breadcrumbs' ); 

$filterID = '';

if ( isset($_GET['filter']) ) { 
	// получим ID курса по его назанию
	$filter = $_GET['filter'];
	$filterQuery = str_replace('—', '-', $filter);

	$query = new WP_Query(
	[
		'post_type'              => 'course',
		'title'                  => $filterQuery,
		'post_status'            => 'publish',
		'posts_per_page'         => 1,
		'update_post_term_cache' => false,
		'update_post_meta_cache' => false,
		'orderby'                => 'post_date ID',
		'order'                  => 'ASC',
		'no_found_rows'          => true,
		'ignore_sticky_posts'    => true,
	]
	);

	if ( $query->post ) {
		$page_got_by_title = $query->post;
		$compare = "LIKE";
	}
	else {
		$page_got_by_title = null;
		$compare = "!=";
	}
	$filterID = $page_got_by_title->ID;

	wp_reset_postdata(); // Сброс глобального состояния
} else {
	$filter = "Все отзывы";
	$page_got_by_title = null;
	$compare = "!=";
}

	// Повторная установка переменных, вероятно, ошибка логики, но оставлено как было в оригинале
	$filter = "Все отзывы";
	$page_got_by_title = null;
	$compare = "!=";

?>

<main class="page-rewiews">
	<?php get_template_part( 'template-parts/block-banner' ); ?>
	
	<section class="rewiews">
		<div class="container">
			<div class="container-wrapper">
				<div class="rewiews-wrapper">
					<?php

					$currentPage = get_query_var( 'paged' ) ? absint( get_query_var( 'paged' ) ) : 1;
					
					// получим отзывы
					$args = array(
						'post_type' 	=> 'reviews',
						'orderby'		=> 'date',
						'order'			=> 'DESC',
						'posts_per_page' => 10,
						'paged'          => $currentPage,
					);
					
					$query = new WP_Query($args);
					
					$schema_reviews = '';
					
					if ($query->have_posts()) { 
						$count = 0;
						while ($query->have_posts()) {
							$query->the_post(); 
						
							$post_id_review = get_the_ID(); 

							$review_date = get_the_date( 'd.m.Y');
							$review_level = carbon_get_post_meta( $post_id_review, 'review_level' );
							
							$avatar = carbon_get_post_meta( $post_id_review, 'review_avatar' );

							$stars = carbon_get_post_meta( $post_id_review, 'review_star' );
							$tekst_otzyva = carbon_get_post_meta( $post_id_review, 'review_text' );
							$prepodavatel = carbon_get_post_meta( $post_id_review, 'review_teacher' );

							$add_class= "more";
						
							if ( strlen($tekst_otzyva) < 350 ) $add_class= "";

							$count++; 
							
							$schema_reviews .='{
								"@type": "Review",
								"reviewBody": "' . replaceQuotes($tekst_otzyva) .'",
								"author": {
									"@type": "Person",
									"name": "' . get_the_title() .'"
								},
								"datePublished": "' . $review_date . '",
								"itemReviewed": {
									"@type": "Person",
									"name": "' . get_the_title($prepodavatel[0]['id']) . '",
									"url": "' . get_permalink( $prepodavatel[0]['id']) . '"}},';
							?>
								<div class="reviews__item">
										<div class="reviews__item-wrapper">
											 <div class="reviews__item-client">
												<div class="reviews__item-client_avatar" style="background: <?php echo rand_color(); ?>">
													<?php if ($avatar) { ?>
														<img loading="lazy" width="57" height="57" class="reviews__item-client_avatar-img" src="<?php echo wp_get_attachment_url($avatar); ?>" alt="<?php echo get_post_meta( $avatar, '_wp_attachment_image_alt', true ); ?>">
													<?php } else {
														echo mb_substr(get_the_title(), 0, 1);
													}?>
												</div>
												<div class="reviews__item-client_data">
												   <div class="reviews__item-client_name"><?php the_title(); ?></div>
												   <div class="reviews__item-client_lavel" ><?php echo $review_level; ?></div>
												</div>
											 </div>
											 <div class="reviews__item-client_stars">
												<?php 
													if (!$stars) $stars = 5;
													for ($i = 1; $i <= $stars; $i++) { ?>
														<svg width="20" height="20" viewBox="0 0 21 19" fill="none" xmlns="http://www.w3.org/2000/svg">
															 <path
																d="M9.58463 1.50884C9.89101 0.602477 11.1729 0.602476 11.4793 1.50884L13.1158 6.35007C13.2531 6.75637 13.6343 7.02985 14.0631 7.02985H19.2721C20.2504 7.02985 20.6467 8.28958 19.8447 8.84971L15.6995 11.7446C15.335 11.9991 15.1823 12.4636 15.3247 12.8847L16.9239 17.6158C17.233 18.5302 16.1954 19.3085 15.404 18.7559L11.1045 15.7533C10.7606 15.5131 10.3033 15.5131 9.95941 15.7533L5.65991 18.7559C4.86857 19.3085 3.83092 18.5302 4.14001 17.6158L5.73926 12.8847C5.8816 12.4636 5.72891 11.9991 5.36448 11.7446L1.21924 8.84971C0.417196 8.28958 0.813532 7.02985 1.79181 7.02985H7.00081C7.42969 7.02985 7.81081 6.75637 7.94815 6.35007L9.58463 1.50884Z"
																fill="#FFD43E" />
														</svg>
													<?php } ?>
													<span><?php echo $review_date; ?></span>
											 </div>
											 <?php if(isset($prepodavatel[0]['id'])) { ?>
												<p class="reviews__kurs"><span>Преподаватель: </span> <a href="<?php echo get_permalink( $prepodavatel[0]['id'] ); ?>"><?php echo get_the_title($prepodavatel[0]['id']);?></a></p>
											 <?php } ?>
											 <div class="reviews__item-client_text <?php echo $add_class; ?>">
												<?php echo $tekst_otzyva; ?>
												<button class="btn-more"><span onclick='this.parentNode.parentNode.classList.remove("more")'>... Читать еще</span></button>
											 </div>
										</div>
								</div>
							<?php			
						};
						wp_reset_postdata(); // Сброс глобального состояния
					}	else { ?>
						<p class="no-post filter_title">Отзывы по данному курсу отсутствуют.</p>
					<?php }?>
				</div>
			</div>
		</div>
		
		<div class="page-numbers-wrapper">
			<nav class="container">
				<?php 
				$pagination_base = str_replace(999999999, "%#%", get_pagenum_link(999999999));
				
				// Убеждаемся, что base для страниц 2+ оканчивается на слэш
				if (substr($pagination_base, -1) !== '/') {
					$pagination_base .= '/';
				}
				
				echo paginate_links([
					"base"      => $pagination_base,
					"format"    => "page/%#%/", // Корректный формат для ЧПУ
					"current"   => max(1, $currentPage),
					"total"     => $query->max_num_pages,
					"prev_text"          => '<svg style="transform: scale(-1, -1);" width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
												<rect width="40" height="40" rx="5" fill="#D9D9D9"/>
												<path d="M29.7071 20.7071C30.0976 20.3166 30.0976 19.6834 29.7071 19.2929L23.3431 12.9289C22.9526 12.5384 22.3195 12.5384 21.9289 12.9289C21.5384 13.3195 21.5384 13.9526 21.9289 14.3431L27.5858 20L21.9289 25.6569C21.5384 26.0474 21.5384 26.6805 21.9289 27.0711C22.3195 27.4616 22.9526 27.4616 23.3431 27.0711L29.7071 20.7071ZM12 21H29V19H12V21Z" fill="#1F1F1F"/>
											</svg>',  // анкор ссылки на предыдущую страницу
					"next_text"          => '<svg width="40" height="40" viewBox="0 0 40 40" fill="none" xmlns="http://www.w3.org/2000/svg">
												<rect width="40" height="40" rx="5" fill="#D9D9D9"/>
												<path d="M29.7071 20.7071C30.0976 20.3166 30.0976 19.6834 29.7071 19.2929L23.3431 12.9289C22.9526 12.5384 22.3195 12.5384 21.9289 12.9289C21.5384 13.3195 21.5384 13.9526 21.9289 14.3431L27.5858 20L21.9289 25.6569C21.5384 26.0474 21.5384 26.6805 21.9289 27.0711C22.3195 27.4616 22.9526 27.4616 23.3431 27.0711L29.7071 20.7071ZM12 21H29V19H12V21Z" fill="#1F1F1F"/>
											</svg>',  // анкор ссылки на следующую страницу
					"type"    => "list",
					"add_args" => (isset($_GET['filter']) ? ['filter' => esc_attr($_GET['filter'])] : false),
				]);?>
			</nav>
		</div>

		<div class="buttons">
			<a href="<?php echo carbon_get_theme_option( 'site_frame_reviews' ); ?>" onclick="document.querySelector('.frame__popup').style='display:flex;'" class="btn-yellow-link" target="myFrame">Оставить отзыв об учебном центре "Декарт"</a>
		</div>
		<div class="frame__popup">
			<div class="frame__popup-wrapper">
				<img class="btn-close-frame__popup" onclick="this.parentNode.parentNode.style='display:none;'" src="<?php echo get_template_directory_uri(); ?>/assets/images/btn-close-modal.svg" alt="кнопка закрыть окно">
				<iframe class="frame_reviews" src="" name="myFrame"></iframe>
			</div>
		</div>
	</section>

<?php 
// ИСПРАВЛЕНИЕ: Используем get_permalink($post_id) для надежного канонического URL в микроразметке
$schema_reviews = substr($schema_reviews, 0, -1); // Удаляем последний символ
?>

<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "WebPage",
  "name": "Отзывы о Учебном центре 'Декарт'",
  "url": "<?php echo esc_url( get_permalink($post_id) ); ?>",
  "review": [
	<?php echo $schema_reviews; ?>
  ]
}
</script>
	
	<?php get_template_part( 'template-parts/promo-form' ); ?>
	
	<?php get_template_part( 'template-parts/map' ); ?>

</main>


<script>
	const mobFilter = document.querySelector('.tiltle-mobile');

	mobFilter.addEventListener('click', (event) => {
		event.target.parentNode.classList.toggle('open');
	});
	
  document.addEventListener('click', (event) => {
	 if (event.target.classList.contains("filter_item")) {
		// Убедитесь, что здесь тоже есть слэш в конце, если 'all-reviews' является страницей
		document.location = "<?php echo get_home_url();?>/all-reviews/?filter=" + event.target.textContent;
		return;
	 }
  });
</script>

<?php
get_footer();