<?php

// Формирование заголовка и параметров запроса в зависимости от переданных аргументов
$title = 'Отзывы';
$key = [];

if (isset($args['teacher'])) {
    $title = 'Отзывы о преподавателе';
    $teacher = $args['teacher'];
    $key = [
        'relation' => 'AND',
        [ 
            'key' => 'review_teacher', // Имя кастомного поля
            'value' => $teacher,
            'compare' => 'LIKE'
        ],
        [ 
            'key' => 'review_type',
            'value' => ['school', 'primary'],
            'compare' => 'IN'
        ]
    ];
} else {
    $type = get_query_var('type');

    if ($type !== '') {
        $title_map = [
            'camp' => 'Отзывы о лагере',
            'school' => 'Отзывы о школе',
            'primary' => 'Отзывы о начальной школе',
            'all' => 'Отзывы'
        ];
        $title = $title_map[$type] ?? $title;
        $key = ($type === 'all') ? [] : [
            [ 
                'key' => 'review_type',
                'value' => $type,
                'compare' => '='
            ]
        ];
    }
}

// Подготовка аргументов для запроса отзывов
$query_args = [
    'posts_per_page' => -1,
    'post_type'     => 'reviews',
    'orderby'       => 'date',
    'order'         => 'DESC',
    'suppress_filters' => true,
    'meta_query'    => $key
];

$the_query = new WP_Query($query_args);

if ($the_query->have_posts()) :
?>
<section class="reviews">
    <div class="container">
        <h2 class="page_h2"><?php echo esc_html($title); ?></h2>
        <div class="reviews-wrapper">
            <div class='swiper reviews-owl'>
                <div class='swiper-wrapper'> 
                    <?php while ($the_query->have_posts()) : $the_query->the_post(); ?>
                        <?php
                            $post_id = get_the_ID();
                            $review_date = get_the_date('d.m.Y');
                            $review_level = carbon_get_post_meta($post_id, 'review_level');
                            $avatar_id = carbon_get_post_meta($post_id, 'review_avatar');
                            $stars = carbon_get_post_meta($post_id, 'review_star') ?: 5; // По умолчанию 5 звезд
                            $tekst_otzyva = carbon_get_post_meta($post_id, 'review_text');
                            $prepodavatel = carbon_get_post_meta($post_id, 'review_teacher');

                            // Определяем класс для сокращенного текста
                            $add_class = (strlen($tekst_otzyva) >= 350) ? 'more' : '';
                        ?>

                        <?php if ($tekst_otzyva) : ?>
                            <div class="swiper-slide reviews__item">
                                <div class="reviews__item-wrapper">
                                    <div class="reviews__item-client">
                                        <div class="reviews__item-client_avatar" style="background-color: <?php echo rand_color(); ?>">
                                            <?php if ($avatar_id) : ?>
                                                <?php echo wp_get_attachment_image($avatar_id, [57, 57], false, [
                                                    'class' => 'reviews__item-client_avatar-img',
                                                    'loading' => 'lazy',
                                                    'alt'   => ''
                                                ]); ?>
                                            <?php else : ?>
                                                <?php echo esc_html(mb_substr(get_the_title(), 0, 1)); ?>
                                            <?php endif; ?>
                                        </div>
                                        <div class="reviews__item-client_data">
                                            <div class="reviews__item-client_name"><?php the_title(); ?></div>
                                            <?php if ($review_level) : ?>
                                                <div class="reviews__item-client_lavel"><?php echo esc_html($review_level); ?></div>
                                            <?php endif; ?>
                                        </div>
                                    </div>

                                    <div class="reviews__item-client_stars">
                                        <?php 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 endfor; ?>
                                        <span><?php echo esc_html($review_date); ?></span>
                                    </div>

                                    <?php if (!empty($prepodavatel[0]['id'])) : ?>
                                        <p class="reviews__kurs">
                                            <span>Преподаватель: </span>
                                            <a href="<?php echo esc_url(get_permalink($prepodavatel[0]['id'])); ?>">
                                                <?php echo esc_html(get_the_title($prepodavatel[0]['id'])); ?>
                                            </a>
                                        </p>
                                    <?php endif; ?>

                                    <div class="reviews__item-client_text <?php echo esc_attr($add_class); ?>">
                                        <?php echo wp_kses_post($tekst_otzyva); ?>
                                        <?php if ($add_class): ?>
                                            <button class="btn-more"><span onclick="this.parentNode.parentNode.classList.remove('more')">... Читать еще</span></button>
                                        <?php endif; ?>
                                    </div>
                                </div>
                            </div>
                        <?php endif; ?>
                    <?php endwhile; ?>
                </div>
            </div>
            <div class='custom-button-next reviews-owl-next'></div>
            <div class='custom-button-prev reviews-owl-prev'></div>
        </div>
        <div class="reviews-all-link" style="text-align:center; margin-top:24px;">
            <a href="/otzyvy/" class="btn-outline">Все отзывы →</a>
        </div>
    </div>
</section>
<?php
    wp_reset_postdata(); // Сброс глобального состояния WordPress
endif;