<?php
/*
Template Name: Шаблон страницы Лагерь
*/
$city       = get_field( 'camp_city', get_the_ID() ) ?: carbon_get_post_meta( get_the_ID(), 'camp_city' ) ?: carbon_get_theme_option( 'site_city' ) ?: 'в Щёлково';
$city_clean = preg_replace( '/^в\s+/u', '', $city );
add_action('wp_head', function() { echo '<style>.hidden{display:none}</style>'; }, 100);
get_header();
?>
<?php
$post_id = get_the_ID();
$theme_uri = get_template_directory_uri();

$priceMin = 1000000;
$programs = carbon_get_post_meta($post_id, 'programs' );

if (is_array($programs)) {
    foreach ($programs as $item) {
        $price = (int)$item['programs_price'];
        if ($price < $priceMin) $priceMin = $price;
    }
}

$jsonld_social = array();
$jsonld_social_raw = carbon_get_post_meta( $post_id, 'social_media' );
if ( is_array( $jsonld_social_raw ) ) {
	foreach ( $jsonld_social_raw as $s ) {
		if ( ! empty( $s['social_media_link'] ) ) {
			$jsonld_social[] = esc_url( $s['social_media_link'] );
		}
	}
}

$jsonld_phone = carbon_get_theme_option( 'site_phone' ) ?: carbon_get_post_meta( $post_id, 'contact_tel' );
$jsonld_addr = carbon_get_theme_option( 'site_address' ) ?: carbon_get_post_meta( $post_id, 'contact_address' );
$jsonld_city = $city_clean;
$jsonld_name = carbon_get_theme_option( 'site_name' ) ?: 'Декарт';
$jsonld_mail = carbon_get_theme_option( 'site_mail' ) ?: carbon_get_post_meta( $post_id, 'contact_mail' );
$jsonld_coords = carbon_get_post_meta( $post_id, 'contact_location' );
$jsonld_coord_arr = $jsonld_coords ? array_map( 'trim', explode( ',', $jsonld_coords ) ) : array( '55.9217', '37.9914' );
$jsonld_img_id = carbon_get_post_meta( $post_id, 'banner_img' );
$jsonld_img_url = $jsonld_img_id ? wp_get_attachment_url( $jsonld_img_id ) : '';

?>
<main class="camp container_camp">

<?php

/**
 * === Все данные из Carbon Fields собираем в одном месте ===
 */
$hero = [
    'h1'       => carbon_get_post_meta( $post_id, 'hero_title_h1' )   ?: 'Детский лагерь Декарт.',
    'span'     => carbon_get_post_meta( $post_id, 'hero_title_span' ) ?: 'Яркое лето без забот!',
    'btn_text' => carbon_get_post_meta( $post_id, 'hero_btn_primary' ) ?: 'Записаться на пробный день',
    'image_id' => carbon_get_post_meta( $post_id, 'banner_img' ),
];

$metrics = [
    [
        'img_id'       => carbon_get_post_meta( $post_id, 'hero_metric_1_img' ),
        'number'       => carbon_get_post_meta( $post_id, 'hero_metric_1_number' ) ?: '12',
        'label'        => carbon_get_post_meta( $post_id, 'hero_metric_1_label' )  ?: 'лет в городе',
        'default_icon' => $theme_uri . '/assets/images/doodles/icon-home.png',
    ],
    [
        'img_id'       => carbon_get_post_meta( $post_id, 'hero_metric_2_img' ),
        'number'       => carbon_get_post_meta( $post_id, 'hero_metric_2_number' ) ?: '2 500+',
        'label'        => carbon_get_post_meta( $post_id, 'hero_metric_2_label' )  ?: 'счастливых детей',
        'default_icon' => $theme_uri . '/assets/images/doodles/icon-bulb.png',
    ],
    [
        'img_id'       => carbon_get_post_meta( $post_id, 'hero_metric_3_img' ),
        'number'       => carbon_get_post_meta( $post_id, 'hero_metric_3_number' ) ?: '4.9 / 5',
        'label'        => carbon_get_post_meta( $post_id, 'hero_metric_3_label' )  ?: 'рейтинг от родителей',
        'default_icon' => $theme_uri . '/assets/images/doodles/icon-award.png',
    ],
];


?>
<section class="section-bg hero-media-search" data-bg="hero">
    <div class="container">
        <div class="hero-media-search__container">

            <!-- Левая колонка -->
            <div class="hero-media-search__content">
                <h1 class="heading-1"><?php echo wp_kses_post( $hero['h1'] ); ?></h1>
                <h2 id="camp-hero-subtitle" class="hero-subtitle-brand"><?php echo wp_kses_post( $hero['span'] ); ?></h2>

                <!-- Метрики (десктоп) -->
                <div class="hero-media-search__propositions on-desktop">
                    <?php foreach ( $metrics as $metric ) : ?>
                        <?php render_hero_metric( $metric ); ?>
                    <?php endforeach; ?>
                </div>

                <!-- CTA (десктоп) -->
                <div class="hero-cta on-desktop">
                        <a href="#0" class="btn-write-camp about-us__cta-link" aria-label="<?php echo esc_attr( $hero['btn_text'] ); ?>">
                            <?php echo esc_html( $hero['btn_text'] ); ?> →
                        </a>
                        <p class="hero-cta__note">Один пробный день — за наш счёт. Оцените качество сами, а решение примете после.</p>
                    </div>
                </div>

            <!-- Правая колонка (изображение + мобильные элементы) -->
            <div class="hero-media-search__media">
                <div class="hero-media-search__frame">
                    <?php if ( $hero['image_id'] ) : ?>
                        <?php echo wp_get_attachment_image( $hero['image_id'], 'full', false, [
                            'class'   => 'hero-media-search__image',
                            'fetchpriority' => 'high',
                            'loading' => 'eager',
                            'alt'     => esc_attr( wp_trim_words( $hero['h1'], 10 ) )
                        ] ); ?>
                    <?php else : ?>
                        <img class="hero-media-search__image"
                             fetchpriority="high" src="<?php echo $theme_uri; ?>/assets/images/camp-hero.jpg"
                             alt="Детский лагерь Декарт" loading="eager">
                    <?php endif; ?>

                    <!-- Декоративные элементы -->
                    <img src="<?php echo $theme_uri; ?>/assets/images/doodles/hero-doodle-gears.svg"
                         alt="" class="doodle doodle--top-left">
                    <img src="<?php echo $theme_uri; ?>/assets/images/doodles/hero-doodle-pencils.svg"
                         alt="" class="doodle doodle--bottom-right">
                </div>

                <!-- Метрики + CTA (мобильная версия) -->
                <div class="hero-media-search__wrapper">
                    <div class="hero-media-search__propositions on-mobile">
                    <?php foreach ( $metrics as $metric ) : ?>
                        <?php render_hero_metric( $metric ); ?>
                    <?php endforeach; ?>
                    </div>

                    <div class="hero-cta on-mobile">
                        <a href="#0" class="btn-write-camp about-us__cta-link" aria-label="<?php echo esc_attr( $hero['btn_text'] ); ?>">
                            <?php echo esc_html( $hero['btn_text'] ); ?> →
                        </a>
                        <p class="hero-cta__note">Один пробный день — за наш счёт. Оцените качество сами, а решение примете после.</p>
                    </div>
                </div>
            </div>

        </div>
    </div>
</section>
	<section class="section-reveal section-bg about-us" data-bg="white">
	<div class="container">
		<div class="about-us__wrapper">
			<div class="about-us__image-col">
				<div class="about-us__frame">
				<?php
					$about_img_id = carbon_get_post_meta( $post_id, 'about_us_img' );
					if ( $about_img_id ) :
						echo wp_get_attachment_image( $about_img_id, 'large', false, [
							'class'   => 'about-us__image',
							'loading' => 'lazy',
							'alt'     => 'Фото детского лагеря Декарт'
						] );
					else :
						echo '<div class="about-us__image-placeholder">
							<svg width="64" height="64" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
								<rect x="3" y="3" width="18" height="18" rx="2"></rect>
								<circle cx="8.5" cy="8.5" r="1.5"></circle>
								<path d="M21 15l-5-5L5 21"></path>
							</svg>
							<span>Добавьте фото</span>
						</div>';
					endif;
				?>
					<img src="<?php echo $theme_uri; ?>/assets/images/doodles/galileo/paperplane-galileo.svg"
					     alt="" class="about-us__doodle about-us__doodle--plane">
					<img src="<?php echo $theme_uri; ?>/assets/images/doodles/galileo/orangegear-white.svg"
					     alt="" class="about-us__doodle about-us__doodle--heart">
				</div>
			</div>
			<div class="about-us__content-col">
				<h2 id="camp-about" class="camp_title about-us__title">Лето, которое не хочется ставить на паузу</h2>
				<div class="about-us__text">
					<?php echo wp_kses_post( carbon_get_post_meta( $post_id, 'about_us_text' ) ?: 'Всю зиму ребёнок в телефоне? Бабушка устала? А ведь лето может быть другим — ярким, живым, полезным.
В Dekart дети не просто под присмотром. Они собирают роботов, ставят опыты, играют в театре, бегают на квестах и находят друзей.А главное — бегут в лагерь каждое утро без уговоров.' ); ?>
				</div>
				<div class="about-us__social-proof">
					<span class="about-us__badge">⭐ 2500+ мам доверили нам лето</span>
				</div>
				<div class="about-us__cta">
					<a href="#" class="btn-write-camp about-us__cta-link">Хочу на пробный день →</a>
				</div>
			</div>

		</div>
	</div>
</section>
<section class="section-reveal section-bg suggestions" data-bg="mint">
	<div class="container">
	<h2 id="camp-advantages" class="camp_title">Почему мамы выбирают Dekart: дети бегут сюда сами</h2>
	<p class="suggestions__subtitle">Никаких уговоров по утрам. Никаких «забери меня». Только горящие глаза и «а можно ещё?»</p>
	<div class="suggestions-wrapper">		<?php 			$suggestions = carbon_get_post_meta($post_id, 'suggestions' );			$icons = ['innovation-white.svg', 'steamprojects-35x35-1.svg', 'handson-35x35-1.svg', 'orangegear-white.svg', 'outdoor-white.svg', 'heart_sticker.svg'];
			if (is_array($suggestions)) {
				foreach ($suggestions as $index => $item) {
					$suggestions_title = $item['suggestions_title'];
					$suggestions_text = $item['suggestions_text'];
					$icon_file = $icons[$index % count($icons)];
				?>				<div class="suggestions__item">
						<div class="suggestions__icon-wrap">
							<img src="<?php echo $theme_uri; ?>/assets/images/doodles/galileo/<?php echo $icon_file; ?>"
						     alt="<?php echo esc_attr( $suggestions_title ); ?>" class="suggestions__icon" loading="lazy">
						</div>
						<h3 class="suggestions__item_title"><?php echo esc_html( $suggestions_title ); ?></h3>
						<p class="suggestions__item_text"><?php echo esc_html( $suggestions_text ); ?></p>
					</div>		<?php }
			} ?>	</div>
	</div>
</section>
	<section class="section-reveal section-bg infograph" data-bg="white">
		<div class="container">
			<div class="infograph__header">
				<h2 id="camp-infograph" class="camp_title">Цифры, которые говорят сами за себя</h2>
				<p class="infograph__lead">Мы создаём среду, где каждый ребёнок раскрывает свой потенциал</p>
			</div>
			<div class="infograph__grid">

				<div class="infograph__card">
					<div class="infograph__card-icon">
						<img loading="lazy" src="<?php echo $theme_uri; ?>/assets/images/age.svg" alt="Возраст детей — Образовательный центр Декарт <?php echo $city; ?>" width="40" height="40">
					</div>
					<div class="infograph__card-body">
						<p class="infograph__stat">6,5−11 лет</p>
						<p class="infograph__label">возраст</p>
					</div>
				</div>

				<div class="infograph__card">
					<div class="infograph__card-icon">
						<img loading="lazy" src="<?php echo $theme_uri; ?>/assets/images/group.svg" alt="Группы до 10 детей — Образовательный центр Декарт <?php echo $city; ?>" width="40" height="40">
					</div>
					<div class="infograph__card-body">
						<p class="infograph__stat">до 10 детей</p>
						<p class="infograph__label">каждая группа</p>
					</div>
				</div>

				<div class="infograph__card">
					<div class="infograph__card-icon">
						<img loading="lazy" src="<?php echo $theme_uri; ?>/assets/images/time.svg" alt="Время посещения на выбор — Образовательный центр Декарт <?php echo $city; ?>" width="40" height="40">
					</div>
					<div class="infograph__card-body">
						<p class="infograph__stat">на выбор</p>
						<p class="infograph__label">время посещения</p>
					</div>
				</div>

				<div class="infograph__card">
					<div class="infograph__card-icon">
						<img loading="lazy" src="<?php echo $theme_uri; ?>/assets/images/price.svg" alt="Стоимость недели — Образовательный центр Декарт <?php echo $city; ?>" width="40" height="40">
					</div>
					<div class="infograph__card-body">
						<p class="infograph__stat">от <?php echo esc_html( number_format($priceMin, 0, ',', ' ') ); ?> ₽</p>
						<p class="infograph__label">стоимость недели</p>
					</div>
				</div>

			</div>
		</div>
	</section>

	<section class="section-bg programs" data-bg="mint" itemscope itemtype="https://schema.org/ItemList">
		<div class="container">
			<h2 id="camp-programs" class="camp_title" itemprop="name">Летние программы</h2>
			<div class="programs__grid">
				<?php
				$programs = carbon_get_post_meta($post_id, 'programs');
				if (is_array($programs)) {
					foreach ($programs as $item) {
						$programs_img = $item['programs_img'];
						$programs_title = $item['programs_title'];
						$programs_date = $item['programs_date'];
						$programs_text = $item['programs_text'];
						$programs_price = $item['programs_price'];
						$programs_days = $item['programs_days'];
						$programs_content = $item['programs_content'];?>
				<article class="programs__card">
					<img class="programs__image" loading="lazy" width="360" height="225" src="<?php echo $programs_img ? wp_get_attachment_url($programs_img) : $theme_uri . '/assets/images/placeholder.svg'; ?>" alt="<?php echo $programs_img && get_post_meta($programs_img, '_wp_attachment_image_alt', true) ? esc_attr(get_post_meta($programs_img, '_wp_attachment_image_alt', true)) : esc_attr($programs_title) . ' — Образовательный центр Декарт ' . $city; ?>">
					<div class="programs__body">
						<h3 class="programs__name"><?php echo esc_html($programs_title); ?></h3>
						<p class="programs__date"><?php echo esc_html($programs_date); ?></p>
						<p class="programs__desc"><?php echo esc_html($programs_text); ?></p>
						<div class="programs__footer">
							<span class="programs__price"><?php echo number_format((int)$programs_price, 0, ',', ' '); ?> ₽</span>
							<span class="programs__duration"><?php echo esc_html($programs_days); ?></span>
						</div>
						<div class="programs_content hidden"><?php echo wp_kses_post($programs_content); ?></div>
						<button class="programs__btn btn-program" aria-label="Подробнее о программе <?php echo esc_attr($programs_title); ?>">Подробнее</button>
					</div>
				</article>
				<?php
					}
				} ?>
			</div>
		</div>
	</section>

	<section class="section-reveal section-bg bring-child" data-bg="white" itemscope itemtype="https://schema.org/Product">
    <meta itemprop="name" content="Городской лагерь Декарт">
    <meta itemprop="description" content="Стоимость пребывания в городском лагере Декарт">
	<?php 
		$price_half_day = carbon_get_post_meta($post_id, 'price_half_day' );
		$price_full_day = carbon_get_post_meta($post_id, 'price_full_day' );
	?>
	 <h2 id="camp-pricing" class="camp_title">Приводите ребёнка, когда вам удобно</h2>
	 <div class="bring-child-wrapper">

		<div class="pricing-card pricing-card--half">
			<div class="pricing-card__header">
				<div class="pricing-card__badge pricing-card__badge--half">
					<img loading="lazy" src="<?php echo $theme_uri; ?>/assets/images/green-star.svg" width="24" height="24" alt="">
				</div>
				<h3 class="pricing-card__title">Половина дня</h3>
				<p class="pricing-card__desc">Время пребывания — на выбор (до обеда или до вечера)</p>
			</div>
			<div class="pricing-card__price" itemprop="offers" itemscope itemtype="https://schema.org/Offer">
				<span class="pricing-card__amount" itemprop="price" content="<?php echo esc_attr($price_half_day); ?>"><?php echo number_format($price_half_day, 0, ',', ' '); ?> ₽</span>
				<span class="pricing-card__period">за 5 дней</span>
				<meta itemprop="priceCurrency" content="RUB">
			</div>
			<div class="pricing-card__slots">
				<div class="pricing-card__slot">
					<span class="pricing-card__slot-time">с 8:30 до 13:30</span>
					<span class="pricing-card__slot-label">утренняя смена</span>
				</div>
				<div class="pricing-card__slot">
					<span class="pricing-card__slot-time">с 13:30 до 18:30</span>
					<span class="pricing-card__slot-label">вечерняя смена</span>
				</div>
			</div>
			<ul class="pricing-card__features">
				<li><b>5 дней</b> пребывания в клубе</li>
				<li>творческие занятия и мастер-классы <b>1 раз в день</b></li>
				<li>умные прогулки <b>1 раз в день</b></li>
			</ul>
			<div class="pricing-card__extra">
				<img loading="lazy" src="<?php echo $theme_uri; ?>/assets/images/calendar.png" width="20" height="20" alt="Календарь — Образовательный центр Декарт <?php echo $city; ?>">
				<span>Тематическая неделя на выбор</span>
			</div>
			<button class="pricing-card__btn btn-write-camp">Занять место</button>
		</div>

		<div class="pricing-card pricing-card--full">
			<div class="pricing-card__header">
				<div class="pricing-card__badge pricing-card__badge--full">
					<img loading="lazy" src="<?php echo $theme_uri; ?>/assets/images/star-02.svg" width="24" height="24" alt="">
				</div>
				<h3 class="pricing-card__title">Полный день</h3>
				<p class="pricing-card__desc">Пребывание в клубе с утра до вечера, дополнительные активности</p>
			</div>
			<div class="pricing-card__price" itemprop="offers" itemscope itemtype="https://schema.org/Offer">
				<span class="pricing-card__amount" itemprop="price" content="<?php echo esc_attr($price_full_day); ?>"><?php echo number_format($price_full_day, 0, ',', ' '); ?> ₽</span>
				<span class="pricing-card__period">за 5 дней</span>
				<meta itemprop="priceCurrency" content="RUB">
			</div>
			<div class="pricing-card__slots">
				<div class="pricing-card__slot">
					<span class="pricing-card__slot-time">с 8:30 до 18:30</span>
					<span class="pricing-card__slot-label">полный день</span>
				</div>
			</div>
			<ul class="pricing-card__features">
				<li><b>5 дней</b> пребывания в клубе</li>
				<li>творческие занятия и мастер-классы <b>2 раза в день</b></li>
				<li>умные прогулки <b>2 раза в день</b></li>
				<li>тематические экскурсии каждую неделю</li>
			</ul>
			<div class="pricing-card__extra">
				<img loading="lazy" src="<?php echo $theme_uri; ?>/assets/images/calendar+.png" width="20" height="20" alt="Календарь — Образовательный центр Декарт <?php echo $city; ?>">
				<span>Тематическая неделя на выбор</span>
			</div>
			<button class="pricing-card__btn btn-write-camp">Занять место</button>
		</div>

	 </div>
	</section>

<section class="section-reveal section-bg mentors" data-bg="mint">
<h2 id="camp-mentors" class="camp_title">Наши наставники и ведущие мастер-классов</h2>
     <div class="mentors-wrapper">
        <?php 
        $mentors = carbon_get_post_meta($post_id, 'mentors' );
        if (is_array($mentors)) {
            foreach ($mentors as $item) { 
                $mentorName = $item['mentor_name'] ?? '';
                $mentor_job = $item['mentor_job'] ?? '';
                $mentor_foto = $item['mentor_foto'] ?? 0;
                $mentor_about = $item['mentor_about'] ?? '';
            ?>
                <div class="mentors__item">
                    <div class="mentors__card">
                        <div class="mentors__card-top">
                            <?php if ( !$mentor_foto ) { ?>
                                <img class="mentors__photo" loading="lazy" width="120" height="120" src="<?php echo $theme_uri; ?>/assets/images/no-photo.png" alt="<?php echo esc_attr( $mentorName ); ?> — Образовательный центр Декарт <?php echo $city; ?>">
                            <?php } else { ?>
                               <img class="mentors__photo" loading="lazy" width="120" height="120" src="<?php echo wp_get_attachment_url($mentor_foto); ?>" alt="<?php echo esc_attr( $mentorName ); ?> — Образовательный центр Декарт <?php echo $city; ?>">
                            <?php } ?>
                        </div>
                        <div class="mentors__card-body">
                            <h3 class="mentors__name"><?php echo esc_html($mentorName); ?></h3>
                            <p class="mentors__job"><?php echo esc_html($mentor_job); ?></p>
                            <?php if ($mentor_about) : ?>
                            <p class="mentors__about"><?php echo esc_html($mentor_about); ?></p>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            <?php }
        } ?>
     </div>

    </section>

	<section class="section-reveal section-bg routine" data-bg="white">
		<h2 id="camp-schedule" class="camp_title">Распорядок дня в клубе</h2>
		<div class="routine-wrapper">
	 	<?php 
			$routine = carbon_get_post_meta($post_id, 'routine' );
			if (is_array($routine)) {
				foreach ($routine as $item) { 
					$routine_time = $item['routine_time'];
					$routine_title = $item['routine_title'];
					$routine_text = $item['routine_text'];
				?>
				<div class="routine__item">
					<div class="routine__item_time"><?php echo esc_html($routine_time); ?></div>
					<div class="routine__item_circle"></div>
					<div class="routine__item_text">
					  <p class="routine__item_time-mobile"><?php echo esc_html($routine_time); ?></p>
					  <h3 class="routine__item_text-title"><?php echo esc_html($routine_title); ?></h3>
					  <p class="routine__item_text-text"><?php echo esc_html($routine_text); ?></p>
					</div>
				</div>
			<?php }
			} ?>
		</div>
	</section>

	<section class="section-reveal section-bg foto" data-bg="mint">
	 <h2 id="camp-gallery" class="camp_title">Наши фотографии</h2>
	 <?php
		$fotos = carbon_get_post_meta($post_id, 'fotos' );
		if (is_array($fotos) && !empty($fotos)) :
	 ?>
	 <div class="lw-gallery">
		<div class="lw-gallery__grid">
			<?php foreach ($fotos as $item) :
				$img_id = $item['foto'];
				$img_url = wp_get_attachment_url($img_id);
				$full_url = wp_get_attachment_image_url($img_id, 'full');
				$alt = esc_attr(get_post_meta($img_id, '_wp_attachment_image_alt', true));
				if ( ! $alt ) $alt = 'Фото лагеря — Образовательный центр Декарт ' . $city;
			?>
			<div class="lw-gallery__item">
				<img class="lw-gallery__thumb"
					 src="<?php echo esc_url($img_url); ?>"
					 alt="<?php echo $alt; ?>"
					 loading="lazy"
					 width="400" height="300"
					 data-full="<?php echo esc_url($full_url); ?>">
			</div>
			<?php endforeach; ?>
		</div>
	 </div>
	 <div class="lw-modal" id="lw-modal-gallery" role="dialog" aria-modal="true" aria-label="Просмотр фото">
		<div class="lw-modal__overlay"></div>
		<div class="lw-modal__content">
			<button class="lw-modal__close" aria-label="Закрыть">
				<svg width="24" height="24" viewBox="0 0 24 24" fill="none"><path d="M18 6L6 18M6 6l12 12" stroke="#fff" stroke-width="2" stroke-linecap="round"></path></svg>
			</button>
			<img class="lw-modal__img" src="https://dev.dekart.school/wp-content/uploads/2025/04/placeholder.jpg" alt="Форма записи">
		</div>
	 </div>
	 <?php endif; ?>
	</section>

	<section class="section-reveal section-bg camp-reviews" data-bg="white">
		<h2 id="camp-reviews" class="camp_title">Что говорят о нас родители</h2>
	<?php
		$key = array(
			array(
				'key' => 'review_type',
				'value' => 'camp',
				'compare' => '='
			)
		);
		$args = array(
			'posts_per_page' => -1,
			'post_type' => 'reviews',
			'orderby' => 'date',
			'order' => 'DESC',
			'suppress_filters' => true,
			'meta_query' => $key,
		);
		$the_query = new WP_Query($args);
		if ($the_query->have_posts()) :
	?>
		<div class="lw-scroll-x">
			<div class="lw-grid lw-grid--3 lw-gap-20">
				<?php while ($the_query->have_posts()) : $the_query->the_post();
					$review_id = get_the_ID();
					$avatar = carbon_get_post_meta($review_id, 'review_avatar');
					$stars = carbon_get_post_meta($review_id, 'review_star');
					$text = carbon_get_post_meta($review_id, 'review_text');
					$date = get_the_date('d.m.Y');
					$name = get_the_title();
					if (!$stars) $stars = 5;
					if (!$text) continue;
				?>
				<div class="lw-card">
					<div class="lw-flex lw-flex--row lw-gap-12 lw-items-center">
						<div class="lw-avatar lw-avatar--48">
							<?php if ($avatar) : ?>
								<img class="lw-avatar__img" src="<?php echo wp_get_attachment_url($avatar); ?>" alt="<?php echo esc_attr($name); ?>" loading="lazy">
							<?php endif; ?>
						</div>
						<div class="lw-flex lw-flex--col">
							<div class="lw-text-dark lw-font-semibold"><?php echo esc_html($name); ?></div>
							<div class="lw-text-xs lw-text-gray"><?php echo esc_html($date); ?></div>
						</div>
						<div class="lw-badge lw-badge--verified">Проверенный отзыв</div>
					</div>
					<div class="lw-stars lw-mt-8">
						<?php for ($i = 1; $i <= 5; $i++) : ?>
							<svg class="lw-star <?php echo $i <= $stars ? 'lw-star--filled' : ''; ?>" width="16" height="16" viewBox="0 0 21 19" fill="none">
								<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="currentColor"></path>
							</svg>
						<?php endfor; ?>
					</div>
					<div class="lw-card__text lw-mt-8"><?php echo wp_kses_post($text); ?></div>
				</div>
				<?php endwhile; ?>
			</div>
		</div>
	<?php endif; wp_reset_postdata(); ?>
	</section>

		<section class="section-reveal section-bg camp-faq" data-bg="mint">
			<h2 id="camp-faq" class="camp_title">Часто задаваемые вопросы</h2>
			<div class="faq-wrapper" itemscope itemtype="https://schema.org/FAQPage">

			<?php 
				$questions = carbon_get_post_meta($post_id, 'questions' );
				$HTMcol1 = '';
				$HTMcol2 = '';

				$count = 0;
				if (is_array($questions)) {
					foreach ($questions as $item) { 
						$questions_question = $item['questions_question'];
						$questions_answer = $item['questions_answer'];
						$accordion_item = "<div class='box__accordion'>
							  <div class='box__accordion_label' role='button' tabindex='0' itemscope itemprop='mainEntity' itemtype='https://schema.org/Question'>
								 <span itemprop='name'>" . esc_html($questions_question) . "</span>
								 <svg role='presentation' focusable='false' width='24px' height='24px' viewBox='0 0 24 24'>
									<g stroke='none' stroke-width='2px' fill='none' fill-rule='evenodd' stroke-linecap='square'>
									   <g transform='translate(1.000000, 1.000000)' stroke='#3bb273'>
										  <path d='M0,11 L22,11'></path>
										  <path d='M11,0 L11,22'></path>
									   </g>
									</g>
								 </svg>
							  </div>
							  <div class='box__accordion_content' itemscope itemprop='acceptedAnswer' itemtype='https://schema.org/Answer'>
								 <div class='box__accordion_content-text' itemprop='text'>" . wp_kses_post($questions_answer) . "</div>
							  </div>
						   </div>";
						if ($count % 2 === 0) {
							$HTMcol1 .= $accordion_item;
						} else {
							$HTMcol2 .= $accordion_item;
						}
						$count++;
					}
				}
				echo "<div class='accordion'>$HTMcol1</div>";
				echo "<div class='accordion accordion-last'>$HTMcol2</div>"; 
				?>
			</div>
		</section>

		<section class="section-reveal section-bg camp-contact" data-bg="white">
			<?php 
				$contact_tel = carbon_get_post_meta($post_id, 'contact_tel' );
				$contact_address = carbon_get_post_meta($post_id, 'contact_address' );
				$contact_location = carbon_get_post_meta($post_id, 'contact_location' );
				$contact_location_text = carbon_get_post_meta($post_id, 'contact_location_text' );
				$contact_mail = carbon_get_post_meta($post_id, 'contact_mail' );
			?>
			<h2 id="camp-contacts" class="camp_title">Контакты</h2>
			<div class="contact-wrapper">
				<div class="contact-content">
					<div class="contact_subtitle">Телефон:</div>
					<a class="contact_tel" href="tel:+<?php echo preg_replace('/[^0-9]/', '', $contact_tel); ?>" target="_blank"><?php echo esc_html($contact_tel); ?></a>
					<div class="contact_subtitle">Почта:</div>
					<a class="contact_tel" href="mailto:<?php echo esc_attr($contact_mail); ?>" target="_blank"><?php echo esc_html($contact_mail); ?></a>
					<div class="contact_subtitle">Адрес:</div>
					<div class="contact_tel"><?php echo esc_html($contact_address); ?></div>
					<div class="contact_subtitle">Наши соцсети:</div>
					<div class="contact_social">
						<?php 
						$social_media = carbon_get_post_meta( $post_id, 'social_media' );
						if (is_array($social_media)) {
							foreach( $social_media as $item ) { 
								$icon =  $item['social_media_img']; 
								if ($item['social_media_link'] != '') { ?>
								<a class="social_item" href="<?php echo esc_url($item['social_media_link']); ?>" target="_blank" rel="noopener noreferrer" title="<?php echo esc_attr($item['social_media_name']); ?>">
									<img loading="lazy" width="32" height="32" src="<?php echo wp_get_attachment_url($icon); ?>" alt="<?php echo esc_attr($item['social_media_name']); ?>">
								</a>
								<?php }
							}
						} ?>
					</div>
				</div>
			<div class="contact-map">
				<div id="ya-map" style="width: 100%; height: 625px;"></div>
			</div>
			</div>
		</section>

</main>

<div class="modal-programs" role="dialog" aria-modal="true" aria-label="Программа лагеря">
	<div class="modal-programs__card">
		<button class="modal-programs__close btn-close-programs" aria-label="Закрыть">
			<svg width="20" height="20" viewBox="0 0 24 24" fill="none"><path d="M18 6L6 18M6 6l12 12" stroke="#fff" stroke-width="2" stroke-linecap="round"></path></svg>
		</button>
		<div class="modal-programs__img">
			<img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='400' height='300'%3E%3C/svg%3E" alt="">
		</div>
		<div class="modal-programs__body">
			<?php if (!empty($programs_title)) : ?><h3 class="programs__item_title"><?php echo esc_html($programs_title); ?></h3><?php else : ?><p class="program-subtitle">Тема уточняется</p><?php endif; ?>
			<p class="programs__item_price"></p>
			<div class="programs__content"></div>
		</div>
	</div>
</div>

<div class="modal-mentors" role="dialog" aria-modal="true" aria-label="Информация о наставнике">
 <div class="modal-mentors-wrapper">
	<button class="btn-close-mentors" aria-label="Закрыть">
	   <svg role="presentation" class="t-popup__close-icon" width="23px" height="23px" viewBox="0 0 23 23">
		  <g stroke="none" stroke-width="1" fill="#3bb273" fill-rule="evenodd">
			 <rect
				transform="translate(11.313708, 11.313708) rotate(-45.000000) translate(-11.313708, -11.313708) "
				x="10.3137085" y="-3.6862915" width="2" height="30"></rect>
			 <rect
				transform="translate(11.313708, 11.313708) rotate(-315.000000) translate(-11.313708, -11.313708) "
				x="10.3137085" y="-3.6862915" width="2" height="30"></rect>
		  </g>
	   </svg>
	</button>
	<div class="modal-programs__img">
	   <img src="data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='400' height='300'%3E%3C/svg%3E" alt="">
	</div>
	<div class="modal-mentors__content">
	   <div class="modal-mentors_name"></div>
	   <div class="modal-mentors_job"></div>
	   <div class="modal-mentors__directions"></div>
	   <div class="modal-mentors__about">
		  <div class="about-item">
			 <img src="<?php echo $theme_uri; ?>/assets/images/icons/icon-education.svg" alt="" width="60" height="58" loading="lazy">
			 <div class="mentors__about-col">
				<p class="mentors__about-col_title">Образование:</p>
				<div class="mentors__about-col_text"></div>
			 </div>
		  </div>
		  <div class="about-item">
			 <img src="<?php echo $theme_uri; ?>/assets/images/icons/icon-experience.svg" alt="" width="59" height="58" loading="lazy">
			 <div class="mentors__about-col">
				<p class="mentors__about-col_title">Опыт работы в сфере образования:</p>
				<div class="mentors__experience-col_text"></div>
			 </div>
		  </div>
	   </div>
	   <div class="modal-additional__education">
		  <img src="<?php echo $theme_uri; ?>/assets/images/icons/icon-certificate.svg" alt="" width="58" height="60" loading="lazy">
		  <div class="mentors__about-col">
			 <p class="mentors__about-col_title">Дополнительное образование:</p>
			 <div class="modal-additional__education_list">
			 </div>
		  </div>
	   </div>
	</div>
 </div>
</div>

<?php
$_b24_raw = carbon_get_post_meta($post_id, 'camp_bitrix_script');
$_b24_form = '';
$_b24_url  = '';
if (preg_match('/data-b24-form="([^"]+)"/', $_b24_raw, $_m)) $_b24_form = $_m[1];
if (preg_match("/\\(window,document,'([^']+)'\\)/", $_b24_raw, $_m)) $_b24_url = $_m[1];
?>
<div class="modal-camp-request-form hidden"
     data-b24-form="<?php echo esc_attr($_b24_form); ?>"
     data-b24-loader="<?php echo esc_attr($_b24_url); ?>">
	<div class="form-wrapper">
		<button class="btn-close-request-form">
			<img class="btn-close-request-form-camp" src="<?php echo $theme_uri; ?>/assets/images/btn-close-modal.svg" alt="кнопка закрыть окно">
		</button>
		<div class="b24-form-container"></div>
	</div>
</div>

<script>
(function() {
    var mapLoaded = false;
    var mapContainer = document.getElementById("ya-map");
    if (!mapContainer) return;

    var observer = new IntersectionObserver(function(entries) {
        if (entries[0].isIntersecting && !mapLoaded) {
            mapLoaded = true;
            observer.disconnect();

            var script = document.createElement("script");
            script.src = "https://api-maps.yandex.ru/2.1/?lang=ru_RU";
            script.onerror = function() { console.warn("Yandex Maps API failed to load"); };
            script.onload = function() {
                ymaps.ready(function() {
                    var coords = <?php echo $contact_location ? '[' . esc_js($contact_location) . ']' : '[55.76, 37.64]'; ?>;
                    var map = new ymaps.Map("ya-map", {
                        center: coords,
                        zoom: 16
                    }, {
                        searchControlProvider: "yandex#search"
                    });

                    var placemark = new ymaps.Placemark(
                        coords,
                        { iconContent: "<?php echo esc_js($contact_location_text); ?>" },
                        { preset: "islands#redStretchyIcon" }
                    );
                    map.geoObjects.add(placemark);
                });
            };
            document.body.appendChild(script);
        }
    }, { rootMargin: "200px" });

    observer.observe(mapContainer);
})();
</script>


<?php
// ─────────────────────────────────────────────────────────────
// JSON-LD: Event (смены) + FAQ + AggregateRating (отзывы)
// ─────────────────────────────────────────────────────────────
$ld_events = array();
if ( is_array( $programs ) ) {
	foreach ( $programs as $item ) {
		$ev = array( '@type' => 'Event' );
		if ( ! empty( $item['programs_title'] ) ) {
			$ev['name'] = wp_strip_all_tags( $item['programs_title'] );
		}
		if ( ! empty( $item['programs_text'] ) ) {
			$ev['description'] = wp_strip_all_tags( $item['programs_text'] );
		}
		if ( ! empty( $item['programs_date'] ) ) {
			$raw = wp_strip_all_tags( $item['programs_date'] );
			if ( preg_match( '/\d{4}/', $raw, $y ) ) {
				$ev['startDate'] = $y[0];
			}
			$ev['description'] = ( isset( $ev['description'] ) ? $ev['description'] . ' — ' : '' ) . $raw;
		}
		if ( ! empty( $item['programs_img'] ) ) {
			$ev['image'] = esc_url( wp_get_attachment_url( $item['programs_img'] ) );
		}
		if ( ! empty( $item['programs_price'] ) ) {
			$ev['offers'] = array(
				'@type' => 'Offer',
				'price' => (int) $item['programs_price'],
				'priceCurrency' => 'RUB',
			);
		}
		if ( $jsonld_img_url && empty( $ev['image'] ) ) {
			$ev['image'] = esc_url( $jsonld_img_url );
		}
		$ld_events[] = $ev;
	}
}

$ld_questions = carbon_get_post_meta( $post_id, 'questions' );
$ld_faq      = array();
if ( is_array( $ld_questions ) ) {
	$faq_main_entity = array();
	foreach ( $ld_questions as $q ) {
		$name   = ! empty( $q['questions_question'] ) ? wp_strip_all_tags( $q['questions_question'] ) : '';
		$answer = ! empty( $q['questions_answer'] ) ? wp_strip_all_tags( $q['questions_answer'] ) : '';
		if ( $name && $answer ) {
			$faq_main_entity[] = array(
				'@type' => 'Question',
				'name'  => $name,
				'acceptedAnswer' => array(
					'@type' => 'Answer',
					'text'  => $answer,
				),
			);
		}
	}
	if ( ! empty( $faq_main_entity ) ) {
		$ld_faq[] = array(
			'@type'           => 'FAQPage',
			'mainEntity'      => $faq_main_entity,
		);
	}
}

$agg_rating  = null;
$agg_reviews = new WP_Query( array(
	'post_type'      => 'reviews',
	'posts_per_page' => -1,
	'fields'         => 'ids',
	'suppress_filters' => true,
	'meta_query'     => array( array(
		'key'   => 'review_type',
		'value' => 'camp',
		'compare' => '=',
	) ),
) );
if ( $agg_reviews->have_posts() ) {
	$total_stars = 0;
	$review_cnt  = 0;
	foreach ( $agg_reviews->posts as $rid ) {
		$star = (int) carbon_get_post_meta( $rid, 'review_star' );
		if ( $star > 0 ) {
			$total_stars += $star;
			$review_cnt++;
		}
	}
	if ( $review_cnt > 0 ) {
		$agg_rating = array(
			'@type'       => 'AggregateRating',
			'ratingValue' => round( $total_stars / $review_cnt, 1 ),
			'reviewCount' => $review_cnt,
			'bestRating'  => 5,
			'worstRating' => 1,
		);
	}
}
wp_reset_postdata();

$localbusiness = array(
	'@type' => 'LocalBusiness',
	'@id' => home_url('/') . '#localbusiness',
	'name' => $jsonld_name,
	'url' => get_permalink( $post_id ),
);
if ( $jsonld_phone ) $localbusiness['telephone'] = $jsonld_phone;
if ( $jsonld_mail ) $localbusiness['email'] = $jsonld_mail;
if ( $jsonld_img_url ) $localbusiness['image'] = $jsonld_img_url;

$localbusiness['address'] = array(
	'@type' => 'PostalAddress',
	'addressLocality' => $jsonld_city,
	'streetAddress' => $jsonld_addr,
	'addressCountry' => 'RU',
);

if ( ! empty( $jsonld_coord_arr[0] ) && ! empty( $jsonld_coord_arr[1] ) ) {
	$localbusiness['geo'] = array(
		'@type' => 'GeoCoordinates',
		'latitude' => $jsonld_coord_arr[0],
		'longitude' => $jsonld_coord_arr[1],
	);
}

$localbusiness['areaServed'] = $city_clean . ', Московская область';
$localbusiness['openingHours'] = 'Mo-Fr 08:30-18:30';

$organization = array(
	'@type' => 'Organization',
	'@id' => home_url('/') . '#organization',
	'name' => $jsonld_name,
	'url' => home_url('/'),
);
if ( ! empty( $jsonld_social ) ) {
	$organization['sameAs'] = $jsonld_social;
}

$ld_graph = array_merge( array( $localbusiness, $organization ), $ld_events, $ld_faq );
if ( $agg_rating ) $ld_graph[] = $agg_rating;

if ( ! empty( $ld_graph ) ) {
	echo '<script type="application/ld+json">' . "\n";
	echo json_encode( array(
		'@context' => 'https://schema.org',
		'@graph'   => $ld_graph,
	), JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT );
	echo "\n" . '</script>' . "\n";
}
?>
<?php
get_footer();
