<?php
get_header();
$post_id = get_the_ID();	
$tags = get_the_terms( $post_id, 'courses' );
$current_term = $tags[0];
?>
<main class="single-course">
	<section class="banner">
		<nav aria-label="Хлебные крошки">
			<ul itemscope itemtype="https://schema.org/BreadcrumbList" class="breadcrumbs container desktop">
				<li itemprop="itemListElement" itemscope itemtype="https://schema.org/ListItem">
					<a itemprop="item" href="<?php echo home_url(); ?>/" class="home fa-home" title="Главная страница">
						<span itemprop="name" style='display:none;'>Главная</span>
						<svg width="21" height="16" viewBox="0 0 21 16" fill="none">
							<path d="M11.6473 10.6896H12.1473V11.1896V15.4691H16.4353C16.5143 15.4691 16.5756 15.4462 16.6432 15.3788C16.7108 15.3113 16.7333 15.2505 16.7333 15.1725V9.36976L10.0513 3.8712L3.36922 9.36976V15.1725C3.36922 15.2505 3.39178 15.3113 3.45937 15.3788C3.52698 15.4462 3.5883 15.4691 3.66723 15.4691H7.95527V11.1896V10.6896H8.45527H11.6473ZM10.3711 1.74407L18.9226 8.86174L19.5643 8.09722L16.9141 5.8987L16.7333 5.74874V5.51388V0.537319H14.5413V2.86272V3.93127L13.7209 3.2466L10.6815 0.709949C10.5114 0.572829 10.3095 0.499981 10.0513 0.499981C9.79293 0.499981 9.59094 0.572914 9.42075 0.710194L0.538196 8.09712L1.17996 8.86174L9.73142 1.74407L10.0513 1.47783L10.3711 1.74407Z" fill="white" stroke="white"/>
						</svg>
					</a>
<meta itemprop="position" content="1">
<meta itemprop="position" content="2">
<meta itemprop="position" content="3">
<meta itemprop="position" content="4">
				</li>
			</ul>
		</nav>
		<div class="banner-wrapper">
				<?php $foto = carbon_get_post_meta( $post_id, 'banner_img_desktop' ); ?>
				<?php $foto_mobile = carbon_get_post_meta( $post_id, 'banner_img_mobile' ); ?>
				<?php if($foto != '' && $foto_mobile !='') { ?>
				<picture class="banner-fon">
					<source srcset="<?php echo wp_get_attachment_url($foto); ?>" media="(min-width: 780px)">
					<img src="<?php echo wp_get_attachment_url($foto_mobile); ?>" alt="<?php echo get_post_meta( $foto, '_wp_attachment_image_alt', true ); ?>">
				</picture>
				<?php } ?>
			<div class="container">
				<div class="vacancies__banner">
					<div class="vacancies__banner-left">
						<h1 class="banner_title"><?php the_title(); ?></h1>
						<p class="banner_text"><?php echo get_field('podzagolovok'); ?></p>
						<div class="title_form-bt24 mobile">Запишитесь на бесплатное пробное занятие и тестирование</div>
					</div>				
					<div class="vacancies__banner-right">
						<?php echo carbon_get_theme_option( 'site_bitrix_script' ); ?>
					</div>
				</div>
			</div>
		</div>
	</section>
	
	<?php get_template_part( 'template-parts/block-banner-info' ); ?>
	
	<section class="course-about">
		<div class="container">
			<div class="course-about-wrapper">
				<span class="about-circle"></span>
				<div class="about_title mobile"><?php the_title(); ?></div>
				<div class="about_img">
					<?php if ( has_post_thumbnail()) { ?>
						<?php the_post_thumbnail(); ?>
					<?php } ?>
				</div>
				<div class="about-col">
					<div class="about_title desktop"><?php the_title(); ?></div>
					<div class="about-col_item course_duration">Длительность <span><?php echo get_field('dlitelnost'); ?></span></div>
					<div class="about-col_item course_subject">Предмет <span><?php echo get_field('predmet'); ?></span></div>
					<div class="about-col_item course_price">Стоимость <span>от <?php echo carbon_get_theme_option( 'price_hour4' ); ?>  за ак. час</span></div>
					<div class="expander"></div>
					<button class="btn-write btn-lilac btn-separate">Записаться</button>
				</div>
		</div>
	</section>
	
	<div class="single-post-content">
		<div class="container">
			<div class="post-content-wrapper">
				<div class="content-left-part">
					<div class="section-wrap">
						<h2 class="main-title-page">
							<span class="color-lilac">О наших</span>
							<span class="color-black"> занятиях</span>
						</h2>
						<div class="text">
							<?php echo get_field('informaciya_o_kurse'); ?>
						</div>
					</div>	

					<?php $osobennosti_kursa = get_field('osobennosti_kursa'); ?>
					<?php if (!empty($osobennosti_kursa)) { ?>
					<div class="section-wrap">
						<h2 class="main-title-page">
							<span class="color-lilac">Особенности</span>
							<span class="color-black"> курса</span>
						</h2>
						<div class="text">
							<?php foreach ($osobennosti_kursa as $kurs) {?>
								<div class="os-item"><?php echo $kurs['tekst_osobennosti']; ?></div>
							<?php } ?>
						</div>
					</div>	
					<?php } ?>
				</div>		
				<div class="courses-block desktop">
					<div class="courses-block-wrapper">
						<h2 class="read-block_title">Популярные курсы<h2>
						<div class="read-blocks-wrapper">
							<?php 
							$select_popular_course = carbon_get_post_meta( $post_id, 'select_popular_course' );
							if (count($select_popular_course) > 0) {
								foreach( $select_popular_course as $item ) { 
								$post = get_post( $item['id'] ); 
								$gallery = get_field('gallery'); ?>
								
								<article class="block-new">
									<a href="<?php the_permalink(); ?>">
										<div class="block-new_img">
											<?php if ( isset($gallery[0]['url']) ) {?>
												<img loading="lazy" src="<?php echo $gallery[0]['url']; ?>">
											<?php } else { ?>
											<img src="<?php echo get_template_directory_uri(); ?>/assets/images/img-for-course.jpg">
											<?php } ?>
											
										</div> 
										<h3 class="block-new_title"><?php the_title(); ?></h3>
									</a>
								</article>
									
							<?php }
							} else echo "Популярные курсы не заданы !!!";
							wp_reset_postdata();?>
						</div>
					</div>
					<div class="courses-block-social">
						<h3 class="social_title">Мы в социальных сетях</h3>
						<div class="social">
							<?php get_template_part( 'template-parts/block-social' ); ?>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>

	<div class="container">
		<div class="section-wrap programm-course">
			<h2 class="main-title-page">
				<span class="color-lilac">Программа</span>
				<span class="color-black"> курса</span>
			</h2>
			<div class="text">
				<?php echo get_field('programma_kursa'); ?>
			</div>
			<?php $razdely_programmy = get_field('razdely_programmy'); ?>
			<?php if (!empty($razdely_programmy)) {?>
				<div class="accordion obrazovanie">
					
					<?php
					foreach($razdely_programmy as $razdel){ ?>
					
						<div class="box__accordion" id="accordion_programm">
							<div class="box__accordion_label"><?php echo $razdel['nazvanie_razdela']; ?></div>
							<div class="box__accordion_content">
								<?php if (!empty($razdel['punkty'])) {?>

									<?php foreach($razdel['punkty'] as $item) { ?>
										<div class="cell"><?php echo $item['nazvanie']; ?></div>
									<?php } ?>
								
								<?php } ?>
							</div>
						</div>
					<?php 
					} ?>
				</div>
				<button class="btn-lilac more-programm">ПОДРОБНЕЕ</button>	
			<?php } ?>
		</div>
	</div>

	<?php get_template_part( 'template-parts/promo-form' ); ?>
	
	<?php get_template_part( 'template-parts/block-price' ); ?>
	
	<section class="section our-teachers">
		<div class="container">
			<h2 class="main-title-page">
				<span class="color-black">Наши</span><br>
				<span class="color-lilac">преподаватели</span>
			</h2>
			<p class="our-teachers_text">
			<?php 
				$teacher_text = carbon_get_post_meta( $post_id, 'teacher_text' );
				if ($teacher_text != '') echo $teacher_text; else echo 'Наши преподаватели - профессионалы с большим опытом репетиторства! Более трети преподавателей имеют ученые степени или закончили аспирантуру. Обязательными требованиями при отборе кандидатов является опыт работы преподавателем от 4 лет и опыт подготовки к ЕГЭ и ОГЭ (ГИА). Конкурс на место более 5 человек.' 
			?>
			</p>
			<?php
			// Параметры запроса к базе данных

			$teachers_args = array(
				'posts_per_page' => -1,
				'orderby'        => 'date',
				'order'          => 'DESC',
				'post_type'      => 'teacher',
				'meta_query' => array(
					array(
						'key' => 'select_courses',
						'carbon_field_property' => 'id', //Ключевое в условии meta_query указать этот параметр
						'compare' => '==',
						'value' => $post_id,
					),
				),
			);
			// Получение списка преподавателей
			$teachers = get_posts( $teachers_args );
			?>
			<div class="swiper teachers-owl">
				<div class='swiper-wrapper'>
					<?php foreach( $teachers as $teacher ) : setup_postdata( $teacher ); 
					//var_dump(carbon_get_post_meta( $teacher->ID, 'select_courses' ));
					?>
						<div class="swiper-slide teachers-owl_item">
							<div class="ourteacher-avatar">
								<a href="<?= esc_url( get_permalink( $teacher->ID ) ); ?>" title="<?= esc_attr( get_the_title( $teacher->ID ) ); ?>">
									<?php
									$avatar = get_the_post_thumbnail_url( $teacher->ID );
									if ( ! empty( $avatar ) ) : ?>
										<img src="<?= esc_url( $avatar ); ?>" alt="<?= esc_attr( get_the_title( $teacher->ID ) ); ?>" title="<?= esc_attr( get_the_title( $teacher->ID ) ); ?>">
									<?php endif; ?>
								</a>
							</div>
						</div>
					<?php endforeach; ?>
				</div>
				<?php wp_reset_postdata(); ?>
			</div>
			<div class="custom-button-next teachers-owl-next"></div>
			<div class="custom-button-prev teachers-owl-prev"></div>

			<div class="buttons">
				<a href="/our-teachers/" class="btn-yellow-link">все преподаватели</a>
			</div>
	</div>
	</section>
	
	<section class="preparation">
		<div class="container">
			<?php
			//var_dump($current_term);
			//if ($current_term->name == )
				$name = $current_term->name;
				$name = preg_replace('~[^А-Я]~u', '', $name);
				$name = mb_substr($name , 1);
				$name = mb_substr($name, 0, -1);
			?>
			<h2 class="main-title-page">
				<span class="color-lilac">Предметы</span>
				<span class="color-black"> для подготовки к <?php echo $name?></span>
			</h2>

			<div class="tabs-container">
		
				<div class="tabs-content">
					<div class="page-tab active">
						<div class="disciplines">
							<?php $posts = get_posts( array(
							'numberposts' => 12,
							'category'    => 0,
							'orderby'     => 'date',
							'order'       => 'DESC',
							'include'     => array(),
							'exclude'     => array(),
							'meta_key'    => '',
							'meta_value'  => '',
							'post_type'   => 'course',
							'suppress_filters' => true,
							'tax_query' => array(
								array(
								  'taxonomy' => 'courses',
								  'field' => 'term_id', 
								  'terms' => $current_term->term_id, /// Where term_id of Term 1 is "1".
								  'include_children' => false
									)
								)	
							) ); 
							foreach( $posts as $post ){
								setup_postdata($post); 
								$kratkoe_naimenovanie = get_field('kratkoe_naimenovanie');
								$ikonka_svg = get_field('ikonka_svg'); ?>
								<a class="disciplines__item" href="<?php the_permalink(); ?>">
										<?php if (!empty($ikonka_svg)) {?>
											<img loading="lazy" class="disciplines__item_icon" src="<?php echo $ikonka_svg ?>" alt="<?php the_title(); ?>" title="<?php the_title(); ?>">
										<?php } ?>
										<p class="disciplines__item_name"><?php echo $kratkoe_naimenovanie; ?></p>
								</a>
							<?php } wp_reset_postdata(); ?>
						</div>
					</div>
				</div>
			</div>
			<div class="preparation_links">
				<a href="/courses/<?php echo $current_term->slug; ?>/">подробнее о курсах <span><?php echo $name?></span></a>
			</div>
		</div>
	</section>
	
	<?php get_template_part( 'template-parts/popular-subjects' ); ?>
	
	<?php get_template_part( 'template-parts/block-why-us' ); ?>
	
	<?php
	$questions = carbon_get_post_meta( $post_id, 'questions' );
	if ( count($questions) > 0) : ?>
	<section class="section questions">
		<div class="container">
			<h2 class="main-title-page">
				<span class="color-black">Вопрос - </span>
				<span class="color-lilac">Ответ</span>
			</h2>
			<div class="accordion obrazovanie">
				<?php
				foreach ($questions as $question) { ?>
				
					<div class="box__accordion">
						<h3 class="box__accordion_label"><?php echo $question['questions_question']; ?></h3>
						<div class="box__accordion_content">
							<p><?php echo $question['questions_answer']; ?></p>
						</div>
					</div>

				<?php 
				} ?>
			</div>
			<button class="btn-write btn-lilac btn-separate">Записаться</button>
		</div>
	</section>
	<?php endif; ?>
	
	<?php get_template_part( 'template-parts/map' ); ?>
		
</main>

<?php 
// Микроразметка для курсов
$name = replaceQuotes(get_the_title());
$site_name = replaceQuotes(carbon_get_theme_option( 'site_name' ));
$name_title = yoastVariableToTitle($post_id);

$schema_description = replaceQuotes(carbon_get_post_meta( $post_id, 'schema_description' ));

global $wp;
$current_url = home_url(add_query_arg(array(),$wp->request));
$home_url = get_site_url();

$social_media = carbon_get_theme_option( 'social_media' );
$schema_social = '';
foreach( $social_media as $item ) { 
	if ($item['social_media_link'] != '') {
		$schema_social .= '"' . $item['social_media_link'] . '",';
	}
}
if ( $schema_social != '' ) $schema_social = substr($schema_social, 0, -1); // Удаляем последний символ

$site_index = carbon_get_theme_option( 'site_index' );
$site_region = carbon_get_theme_option( 'site_region' );
$site_address = carbon_get_theme_option( 'site_address' );
$site_city = carbon_get_theme_option( 'site_city' );
$site_phone = carbon_get_theme_option( 'site_phone' );
$schema_certificate = replaceQuotes(carbon_get_post_meta( $post_id, 'schema_certificate' ));
$schema_age = replaceQuotes(carbon_get_post_meta( $post_id, 'schema_age' ));
$price_hour_discount4 = carbon_get_theme_option( 'price_hour_discount4' );
$schema_age = replaceQuotes(carbon_get_post_meta( $post_id, 'schema_age' ));
$schema_keywords = carbon_get_post_meta( $post_id, 'schema_keywords' );

$schema_sections = carbon_get_post_meta( $post_id, 'schema_section' );
$sectionsHTML = '';
foreach( $schema_sections as $item ) {
	$schema_section_name = $item['schema_section_name'];
	$schema_section_description = $item['schema_section_description'];
	$sectionsHTML .='
	{
      "@type": "DefinedTerm",
      "name": "' . $schema_section_name .'",
      "description": "' . $schema_section_description . '"
    },';
}
if ( $sectionsHTML != '' ) $sectionsHTML = substr($sectionsHTML, 0, -1); // Удаляем последний символ

?>

<script type="application/ld+json" class='asd'>
{
  "@context": "https://schema.org",
  "@type": "Course",  
  "@id": "<?php echo $current_url ?>/#course",
  "name": "<?php echo $name ?>",
  "about": {
    "@type": "Thing",
    "name": "<?php echo $name; ?>"
  },
  "description": "<?php echo $schema_description ?>",
    "potentialAction": {
    "@type": "RegisterAction",
    "target": "<?php echo $current_url ?>/",
    "name": "Записаться на курс"
  },
  "provider": {
    "@type": "EducationalOrganization",
    "name": "<?php echo $site_name; ?>",
    "url": "<?php echo $home_url ?>/",
    "logo": "<?php echo $home_url ?>/logo.png",
    "sameAs": [
		<?php echo $schema_social; ?>
    ],
    "address": {
      "@type": "PostalAddress",
      "streetAddress": "<?php echo $site_address; ?>",
      "addressLocality": "<?php echo $site_city; ?>",
      "addressRegion": "<?php echo $site_region; ?>",
      "postalCode": "<?php echo $site_index; ?>",
      "addressCountry": "RU"
    },
    "contactPoint": {
      "@type": "ContactPoint",
      "telephone": "<?php echo $site_phone; ?>",
      "contactType": "customer service",
      "areaServed": "RU",
      "availableLanguage": ["Russian"]
    }
  },
  "educationalCredentialAwarded": "<?php echo $schema_certificate; ?>",
  "courseMode": "http://schema.org/OfflineCourse",
  "audience": {
    "@type": "EducationalAudience",
    "educationalRole": "Student",
    "additionalProperty": [
      {
        "@type": "PropertyValue",
        "name": "Класс",
        "value": "<?php echo $schema_age; ?>"
      }
    ]
  },
  "offers": {
    "@type": "Offer",
    "price": "<?php echo $price_hour_discount4; ?>",
    "priceCurrency": "RUB",
    "availability": "http://schema.org/InStock",
    "url": "<?php echo $current_url; ?>/"
  },
  "keywords": [
  <?php echo $schema_keywords; ?>
  ],
  "teaches": [<?php echo $sectionsHTML; ?>
  ]
}
</script>

<script>
  document.addEventListener('click', (event) => {
		if (event.target.classList.contains('more-programm')) {
			const parent = event.target.parentNode.querySelector('.accordion');
			const element = event.target;
			parent.classList.toggle('show');
			if (parent.classList.contains('show')) element.textContent = 'Свернуть'; else element.textContent = 'ПОДРОБНЕЕ';
			return;
		}

		if (event.target.classList.contains("tab-clicked")) {
		const tabsBlock = event.target.parentNode.parentNode.parentNode;
		const tabNum = event.target.parentNode.getAttribute('data-tab-btn');

		tabsBlock.querySelector('.tabs-content').style = 'opacity:0; filter: blur(5px); left: -50%';

		tabsBlock.querySelectorAll('.tab').forEach((item) => {
		   item.classList.remove('active');
		});

		tabsBlock.querySelector(`[data-tab-btn='${tabNum}']`).classList.add('active');

		setTimeout(() => {
		   tabsBlock.querySelector('.tabs-content').style = '';

		   tabsBlock.querySelectorAll('.page-tab').forEach((item, index) => {
			  if (index != Number(tabNum - 1)) item.classList.remove('active'); else item.classList.add('active');
		   });
		}, 300)

		return;
	 }
  });
</script>

<?php
get_footer();
