<?php

get_header();

if (!function_exists('get_trainings_for_current_language')) {
    function get_trainings_for_current_language()
    {
        $current_lang = pll_current_language();

        $args = array(
            'post_type' => 'training',
            'posts_per_page' => -1,
            'lang' => $current_lang,
            'post_status' => 'publish',
            'sort' => 'menu_order',
            'order' => 'ASC',
        );

        return get_posts($args);
    }
}

function get_training_taxonomies()
{
    $taxonomies = get_object_taxonomies('training', 'objects');
    $result = array();

    foreach ($taxonomies as $taxonomy) {
        if (!in_array($taxonomy->name, array('language', 'post_translations'))) {
            $terms = get_terms(array(
                'taxonomy' => $taxonomy->name,
                'hide_empty' => true,
            ));

            if (!is_wp_error($terms) && !empty($terms)) {
                $result[$taxonomy->name] = array(
                    'taxonomy' => $taxonomy,
                    'terms' => $terms
                );
            }
        }
    }

    return $result;
}

$trainings = get_trainings_for_current_language();
$taxonomies_data = get_training_taxonomies();

$trainings_data = array();
if ($trainings) {
    foreach ($trainings as $training) {
        $training_info = array(
            'post' => $training,
            'name' => '',
            'exp' => '',
            'short_desc' => '',
            'terms' => array()
        );

        if (have_rows('short_info', $training->ID)) {
            while (have_rows('short_info', $training->ID)) {
                the_row();
                $training_info['name'] = get_sub_field('name');
                $training_info['exp'] = get_sub_field('exp');
                $training_info['short_desc'] = get_sub_field('short_desc');
                $training_info['difficulty'] = get_sub_field('dificulty');
            }
        }

        foreach ($taxonomies_data as $taxonomy_name => $taxonomy_info) {
            $post_terms = wp_get_post_terms($training->ID, $taxonomy_name);
            if (!is_wp_error($post_terms)) {
                $training_info['terms'][$taxonomy_name] = $post_terms;
            }
        }

        $trainings_data[] = $training_info;
    }
}

function group_trainings_by_terms($trainings_data, $taxonomies_data)
{
    $grouped = array();

    foreach ($taxonomies_data as $taxonomy_name => $taxonomy_info) {
        $grouped[$taxonomy_name] = array();

        foreach ($taxonomy_info['terms'] as $term) {
            $grouped[$taxonomy_name][$term->slug] = array(
                'term' => $term,
                'trainings' => array()
            );

            foreach ($trainings_data as $training_data) {
                if (isset($training_data['terms'][$taxonomy_name])) {
                    foreach ($training_data['terms'][$taxonomy_name] as $training_term) {
                        if ($training_term->slug === $term->slug) {
                            $grouped[$taxonomy_name][$term->slug]['trainings'][] = $training_data;
                            break;
                        }
                    }
                }
            }
        }
    }

    return $grouped;
}

$grouped_trainings = group_trainings_by_terms($trainings_data, $taxonomies_data);


if (have_rows('short_info')) {
    while (have_rows('short_info')) {
        the_row();
        $training_name = get_sub_field('name');
        $training_short_desc = get_sub_field('short_desc');
        $training_difficulty = get_sub_field('dificulty');
    }
}

?>

    <section class="max-[768px]:py-[40px] py-[90px] container mx-auto">
        <div>

            <?php if (!empty($taxonomies_data)): ?>
                <div class="filter-navigation">
                    <?php foreach ($taxonomies_data as $taxonomy_name => $taxonomy_info): ?>
                        <div>
                            <div class="max-[768px]:gap-[4px] flex flex-wrap gap-[8px]">
                                <?php foreach ($taxonomy_info['terms'] as $term): ?>
                                    <button class="max-[768px]:!text-[15px] max-[768px]:!px-[14px]"
                                            onclick="scrollToSection('<?php echo esc_attr($taxonomy_name . '-' . $term->slug); ?>')">
                                        <?php echo esc_html($term->name); ?>
                                    </button>
                                <?php endforeach; ?>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            <?php endif; ?>

            <?php foreach ($grouped_trainings as $taxonomy_name => $terms_data): ?>
                <?php foreach ($terms_data as $term_slug => $term_data): ?>
                    <?php if (!empty($term_data['trainings'])): ?>
                        <div id="<?php echo esc_attr($taxonomy_name . '-' . $term_slug); ?>"
                             class="max-[768px]:mt-[40px] mt-[64px]">
                            <h2 class="max-[1050px]:text-[28px] max-[768px]:text-[24px] font-[700] text-[32px] leading-[115%]"><?php echo esc_html($term_data['term']->name); ?></h2>

                            <div class="max-[768px]:!px-[24px] max-[768px]:!mx-[-24px] trainings-container mt-[24px]"
                                 data-section="<?php echo esc_attr($taxonomy_name . '-' . $term_slug); ?>">
                                <div class="max-[1300px]:gap-0 trainings-wrapper flex flex-wrap gap-[24px]">
                                    <?php foreach ($term_data['trainings'] as $training_data): ?>
                                        <?php $training = $training_data['post']; ?>

                                        <a href="<?php echo get_permalink($training->ID); ?>"
                                           class="!no-underline training-item h-auto max-w-[312px] group block no-underline hover:no-underline transition-transform">
                                            <div class=" max-[768px]:shadow-[0_4px_48px_0_rgba(16,_15,_15,_0.1)] flex flex-col bg-[#f8f8f8] relative h-auto rounded-[20px] overflow-hidden shadow-[0_2px_32px_0_rgba(16,_15,_15,_0.03)] group-hover:shadow-[0_4px_48px_0_rgba(16,_15,_15,_0.1)] transition-shadow">
                                                <?php $photo_images = get_field('photo', $training->ID); ?>
                                                <?php if ($photo_images && !empty($photo_images[0])): ?>
                                                    <div class="overflow-hidden min-h-[260px]">
                                                        <img src="<?php echo esc_url($photo_images[0]['url']); ?>"
                                                             alt="<?php echo esc_attr($photo_images[0]['alt']); ?>"
                                                             loading="lazy"
                                                             class="w-full h-[260px] object-cover transition-transform"/>
                                                    </div>
                                                <?php endif; ?>
                                                <div class="max-[768px]:gap-[12px] max-[768px]:p-[12px] flex flex-col gap-[24px] h-full p-[24px]">
                                                    <?php $name = $training_data['name']; ?>
                                                    <?php if ($name): ?>
                                                        <div class="text-[24px] leading-[125%] font-[600] group-hover:text-[#e21e24] transition-colors">
                                                            <?php echo esc_html($name); ?>
                                                        </div>
                                                    <?php endif; ?>

                                                    <?php $short_desc = $training_data['short_desc']; ?>
                                                    <?php if ($short_desc): ?>
                                                        <div class="text-[16px] leading-[145%] font-[500] text-[#222]">
                                                            <?php echo wp_kses_post($short_desc); ?>
                                                        </div>
                                                    <?php endif; ?>

                                                    <?php $difficulty = $training_data['difficulty']; ?>
                                                    <?php if ($difficulty):
                                                        $difficulty_value = (int)$difficulty;

                                                        $difficulty_texts = [
                                                            1 => 'лёгкая', 2 => 'лёгкая',
                                                            3 => 'средняя', 4 => 'средняя',
                                                            5 => 'тяжелая'
                                                        ];

                                                        $red_color = '#E21E24';
                                                        $gray_color = '#E0E0E0';
                                                        ?>

                                                        <div class="pt-[14px] border-t border-dashed w-full justify-center gap-[12px] flex items-center mx-auto">
                                                            <span class="max-[768px]:text-[14px] font-[600] text-[16px] leading-[115%] text-[#2b2c35]">Сложность:</span>
                                                            <div class="flex items-center gap-2">
                                                                <svg width="28" height="17" viewBox="0 0 28 17"
                                                                     fill="none"
                                                                     xmlns="http://www.w3.org/2000/svg">
                                                                    <rect y="8" width="4" height="9" rx="1.33333"
                                                                          fill="<?php echo ($difficulty_value >= 1) ? $red_color : $gray_color; ?>"/>
                                                                    <rect x="6" y="5" width="4" height="12" rx="1.33333"
                                                                          fill="<?php echo ($difficulty_value >= 2) ? $red_color : $gray_color; ?>"/>
                                                                    <rect x="12" y="3" width="4" height="14"
                                                                          rx="1.33333"
                                                                          fill="<?php echo ($difficulty_value >= 3) ? $red_color : $gray_color; ?>"/>
                                                                    <rect x="18" y="2" width="4" height="15"
                                                                          rx="1.33333"
                                                                          fill="<?php echo ($difficulty_value >= 4) ? $red_color : $gray_color; ?>"/>
                                                                    <rect x="24" width="4" height="17" rx="1.33333"
                                                                          fill="<?php echo ($difficulty_value >= 5) ? $red_color : $gray_color; ?>"/>
                                                                </svg>
                                                                <span class="font-[500] text-[16px] max-[768px]:text-[14px] leading-[140%]">
        <?php echo esc_html($difficulty_texts[$difficulty_value] ?? 'неизвестная'); ?>
    </span>
                                                            </div>
                                                        </div>
                                                    <?php endif; ?>
                                                    <div class="!hidden mt-auto h-[59px] flex grey-gradient-hover w-full rounded-[90px] px-[12px] text-[18px] font-[600] leading-[195%] text-[#f8f8f8] bg-[0_2px_32px_0_rgba(16,_15,_15,_0.03)] items-center justify-center group-hover:opacity-90 transition-opacity pointer-events-none">
                                                        Перейти
                                                    </div>
                                                </div>
                                            </div>
                                        </a>
                                    <?php endforeach; ?>
                                </div>
                            </div>
                        </div>
                    <?php endif; ?>
                <?php endforeach; ?>
            <?php endforeach; ?>
        </div>
    </section>

    <script>
        function scrollToSection(sectionId) {
            document.getElementById(sectionId).scrollIntoView({
                behavior: 'smooth',
                block: 'start'
            });
        }

        document.addEventListener('DOMContentLoaded', function () {
            let swiperInstances = [];

            function initSwiper() {
                if (window.innerWidth < 1330) {
                    document.querySelectorAll('.trainings-container').forEach((container, index) => {
                        const wrapper = container.querySelector('.trainings-wrapper');
                        const items = container.querySelectorAll('.training-item');

                        if (items.length <= 1) return;

                        container.classList.add('swiper');
                        wrapper.classList.remove('flex', 'flex-wrap');
                        wrapper.classList.add('swiper-wrapper');

                        items.forEach(item => {
                            const slide = document.createElement('div');
                            slide.className = 'swiper-slide max-w-[312px]';
                            item.parentNode.insertBefore(slide, item);
                            slide.appendChild(item);
                        });

                        const scrollbar = document.createElement('div');
                        scrollbar.className = 'swiper-scrollbar !static !mx-auto !cursor-grab container mt-[44px] !w-full !p-0';
                        container.appendChild(scrollbar);

                        const swiper = new Swiper(container, {
                            slidesPerView: 'auto',
                            spaceBetween: 12,
                            grabCursor: true,
                            freeMode: true,
                            scrollbar: {
                                el: container.querySelector('.swiper-scrollbar'),
                                draggable: true,
                            },

                            keyboard: {
                                enabled: true,
                            },
                        });

                        swiperInstances.push(swiper);
                    });
                } else {
                    destroySwipers();
                }
            }

            function destroySwipers() {
                swiperInstances.forEach(swiper => {
                    if (swiper && swiper.destroy) {
                        swiper.destroy(true, true);
                    }
                });
                swiperInstances = [];

                document.querySelectorAll('.trainings-container').forEach(container => {
                    const wrapper = container.querySelector('.trainings-wrapper');
                    const slides = container.querySelectorAll('.swiper-slide');

                    container.classList.remove('swiper');
                    wrapper.classList.add('flex', 'flex-wrap');
                    wrapper.classList.remove('swiper-wrapper');

                    slides.forEach(slide => {
                        const item = slide.querySelector('.training-item');
                        if (item) {
                            wrapper.appendChild(item);
                            slide.remove();
                        }
                    });

                    container.querySelectorAll('.swiper-scrollbar').forEach(el => el.remove());
                });
            }

            initSwiper();

            let resizeTimeout;
            window.addEventListener('resize', function () {
                clearTimeout(resizeTimeout);
                resizeTimeout = setTimeout(initSwiper, 250);
            });
        });
    </script>

    <style>
        .filter-navigation button {
            box-shadow: 0 2px 32px 0 rgba(16, 15, 15, 0.03);
            background: #fff;
            font-weight: 500;
            font-size: 18px;
            line-height: 195%;
            color: #222;
            border-radius: 90px;
            padding: 8px 28px;
            border: none;
            cursor: pointer;
            transition: all 180ms ease-in-out;
        }

        .filter-navigation button:hover {
            font-size: 18px;
            line-height: 195%;
            color: #f8f8f8;
            box-shadow: none;
            background: linear-gradient(90deg, #9d9994 39.42%, #ccc9c4 92.9%);
        }

        .dark .filter-navigation button:hover {
            background: linear-gradient(90deg, #2b2c35 39.42%, #6e7996 92.9%);
            color: #f8f8f8;
        }
    </style>

<?php get_footer(); ?>