<?php
/*
Template Name: Main Page
*/

// Функция для добавления ID к тегам H2 в контенте
function add_ids_to_h2($content) {
    // Заменяем все H2 теги на теги с ID атрибутами в формате a1, a2, a3
    $content = preg_replace_callback('/<h2(?:\s+[^>]*)?>(.*?)<\/h2>/i', function($matches) {
        static $count = 0;
        $count++;
        return '<h2 id="a' . $count . '">' . $matches[1] . '</h2>';
    }, $content);
    
    return $content;
}

// Функция для извлечения H2 тегов и их текста
function extract_h2_tags($content) {
    $h2_tags = [];
    
    preg_match_all('/<h2\s+id="a(\d+)">(.*?)<\/h2>/i', $content, $matches, PREG_SET_ORDER);
    
    foreach($matches as $match) {
        $id = 'a' . $match[1]; // Используем ID из тега в формате a1, a2, a3
        $text = strip_tags($match[2]);
        $h2_tags[] = ['id' => $id, 'text' => $text];
    }
    
    return $h2_tags;
}

// Получение значений полей ACF для главного баннера
$main_rating = get_field('main_rating') ?: 'Overall Rating: 95 / 100';
$main_heading = get_field('main_heading') ?: 'Online Casino Website';
$main_subheading = get_field('main_subheading') ?: 'The first thing that catches players\'s attention is the incredible simplicity of this casino.';
$main_image_data = get_field('main_image');
$main_image_url = !empty($main_image_data['url']) ? $main_image_data['url'] : get_template_directory_uri() . '/assets/public/img/main-banner/image-1.png';
$main_image_alt = !empty($main_image_data['alt']) ? $main_image_data['alt'] : $main_heading;
$link_url = casino_get_global_button_url();

// Получение значений для вводного текста
$intro_content = get_field('intro_content');

// Получение значений для секции lorem
$lorem_blocks = get_field('lorem_blocks');

// Сбрасываем счетчик H2 тегов для каждой страницы
global $h2_counter;
$h2_counter = 0;

// Обработка контента с добавлением ID для H2 тегов
if ($intro_content) {
    $intro_content = add_ids_to_h2($intro_content);
}

// Получение значений для секции игр
$games_heading = get_field('games_heading') ?: 'Top Games';
$games_count = get_field('games_count') ?: '48 games';
$games_list = get_field('games_list');

// Получение значений для секции ключевых фактов
$key_facts_heading = get_field('key_facts_heading') ?: 'Key facts';
$key_facts_items = get_field('key_facts_items');
$advantages_heading = get_field('advantages_heading') ?: 'Advantages';
$advantages_items = get_field('advantages_items');

// Получение значений для секции бонусов
$bonus_hub_heading = get_field('bonus_hub_heading') ?: 'Bonus Hub';
$bonus_items = get_field('bonus_items');

// Получение значений для секции рейтингов
$ratings_heading = get_field('ratings_heading') ?: 'Ratings of 22Bet Services';
$ratings_items = get_field('ratings_items');
$ratings_button = get_field('ratings_button');

// Получение значений для секции FAQ
$faq_heading = get_field('faq_heading') ?: 'Frequently Asked Questions';
$faq_items = get_field('faq_items');

// Создаем массив для Table of Content
$toc_items = [];

// Top Games
if ($games_heading) {
    $toc_items[] = ['id' => 'topGames', 'text' => $games_heading];
}

// Bonus Hub
if ($bonus_hub_heading) {
    $toc_items[] = ['id' => 'bonusHub', 'text' => $bonus_hub_heading];
}

// Content headings (lorem blocks)
if (is_array($lorem_blocks) && !empty($lorem_blocks)) {
    // Счетчик для нумерации H2 тегов в сквозном порядке
    static $h2_index = 0;
    
    foreach ($lorem_blocks as $block) {
        $h2_index++;
        $block_id = 'a' . $h2_index; // Используем формат a1, a2, a3
        $title = isset($block['title']) ? $block['title'] : 'Lorem ipsum dolor sit amet';
        
        // Добавляем заголовок блока в TOC
        $toc_items[] = ['id' => $block_id, 'text' => $title];
        
        // Если есть контент, проверяем на наличие H2 внутри
        if (isset($block['content']) && !empty($block['content'])) {
            $content = add_ids_to_h2($block['content']);
            $h2_tags = extract_h2_tags($content);
            if (!empty($h2_tags)) {
                $toc_items = array_merge($toc_items, $h2_tags);
            }
            // Сохраняем обработанный контент
            $lorem_blocks[key($lorem_blocks)]['content'] = $content;
        }
        
        next($lorem_blocks); // Переходим к следующему элементу
    }
}

// Rating
if ($ratings_heading) {
    $toc_items[] = ['id' => 'rating', 'text' => $ratings_heading];
}

// FAQ
if ($faq_heading) {
    $toc_items[] = ['id' => 'questions', 'text' => $faq_heading];
}

// Стандартные ссылки не используем в TOC

get_header();
?>

<section class="main-banner">
    <div class="container">
        <div class="main-banner__main">
        <div class="main-banner__text_block">
            <div class="main-banner__rate"><span><?php echo esc_html($main_rating); ?></span></div>
            <div class="main-banner__heading"> 
            <h1><?php echo esc_html($main_heading); ?></h1>
            </div>
            <div class="main-banner__subheading">
            <p><?php echo esc_html($main_subheading); ?></p>
            </div>
            <div class="main-banner__button">
                <?php if($link_url): ?>
                    <a class="button button--mainbaner" href="<?php echo esc_url($link_url); ?>" target="_self">
                        <span><?php pll_e('sign_up'); ?></span>
                    </a>
                <?php endif; ?>
            </div>
        </div>
        <div class="main-banner__image"> 
            <img src="<?php echo esc_url($main_image_url); ?>" alt="<?php echo esc_attr($main_image_alt); ?>">
        </div>
        </div>
    </div>
</section>
<section class="page-content">
    <div class="container"> 
        <div class="page-content__main">
            <div class="page-content__info">
                <div class="page-content__info_item">
                    <?php if($intro_content): ?>
                        <?php echo $intro_content; ?>
                    <?php endif; ?>
                </div>
                <div class="page-content__info_item" id="topGames">
                    <div class="games">
                        <div class="games__heading_block">
                        <div class="games__heading">
                            <h2><?php echo esc_html($games_heading); ?></h2><span><?php echo esc_html($games_count); ?></span>
                        </div>
                        <button class="button button--sort games__sort">
                            <span>A-Z</span>
                        </button>
                        <div class="games__nav">
                            <div class="games__arrow arrow-prev"><img src="<?php echo get_template_directory_uri(); ?>/assets/public/img/icons/arrow-left-grey.svg" alt=""></div>
                            <div class="games__arrow arrow-next"><img src="<?php echo get_template_directory_uri(); ?>/assets/public/img/icons/arrow-right-grey.svg" alt=""></div>
                        </div>
                        </div>
                        <div class="games__slider" id="gamesSlider">
                        <div class="swiper-wrapper">
                            <?php if($games_list && is_array($games_list) && count($games_list) > 0): ?>
                                <?php foreach($games_list as $game): 
                                    $game_image_data = isset($game['game_image']) ? $game['game_image'] : null;
                                    $game_image_url = !empty($game_image_data['url']) ? $game_image_data['url'] : get_template_directory_uri() . '/assets/public/img/games/game-1.jpg';
                                    $game_image_alt = !empty($game_image_data['alt']) ? $game_image_data['alt'] : (isset($game['game_name']) ? $game['game_name'] : 'Game image');
                                    $game_name = isset($game['game_name']) ? $game['game_name'] : 'Game Name';
                                    $game_brand = isset($game['game_brand']) ? $game['game_brand'] : 'Game Provider';
                                    $game_color = isset($game['game_color']) ? $game['game_color'] : 'orange-item';
                                ?>
                                <div class="swiper-slide">
                                    <div class="games__slide_container">
                                        <div class="games__image <?php echo esc_attr($game_color); ?>"> 
                                            <img src="<?php echo esc_url($game_image_url); ?>" alt="<?php echo esc_attr($game_image_alt); ?>">
                                        </div>
                                        <a class="games__like" href="/">
                                            <svg width="18" height="16" viewBox="0 0 18 16" fill="none" xmlns="http://www.w3.org/2000/svg">
                                                <path d="M6.00214 4.27376C5.90338 4.18173 5.78733 4.11023 5.66073 4.06338C5.53413 4.01654 5.39948 3.99529 5.26461 4.00087C5.12973 4.00645 4.9973 4.03875 4.875 4.09589C4.7527 4.15304 4.64296 4.23389 4.55214 4.33376C4.1913 4.73313 3.9942 5.25381 4.00013 5.79202C4.00606 6.33023 4.21459 6.84644 4.58414 7.23776C5.07414 7.75076 5.70614 8.41576 6.27014 9.00176C7.11814 9.88443 7.63381 10.3568 7.81714 10.4188C7.92581 10.4541 8.03414 10.4718 8.14214 10.4718C8.57214 10.4718 8.97214 10.1978 9.11514 9.76276C9.18169 9.5612 9.18528 9.34416 9.12543 9.14052C9.06559 8.93687 8.94515 8.75627 8.78014 8.62276C8.65014 8.49776 8.10914 7.94876 6.06214 5.79876C6.05455 5.79062 6.05033 5.7799 6.05033 5.76876C6.05033 5.75763 6.05455 5.74691 6.06214 5.73876C6.24673 5.53552 6.34392 5.26779 6.33269 4.99346C6.32146 4.71913 6.20272 4.46024 6.00214 4.27276" />
                                                <path d="M17.9331 4.53208C17.8172 3.75405 17.5292 3.01166 17.0902 2.35897C16.6511 1.70628 16.072 1.15972 15.3951 0.759083C13.9991 -0.0719166 12.3491 -0.228917 10.8691 0.329083C10.3391 0.529083 10.0691 1.12708 10.2661 1.66308C10.4631 2.19908 11.0551 2.47308 11.5861 2.27308C12.4841 1.93408 13.4941 2.03308 14.3561 2.54608C14.7706 2.78741 15.1252 3.11939 15.3933 3.51718C15.6614 3.91497 15.836 4.36825 15.9041 4.84308C16.0741 5.97308 15.7601 6.92308 14.9471 7.75008C13.3731 9.35008 11.7651 10.9731 10.2101 12.5401L9.01908 13.7411C8.51241 13.2304 8.00475 12.7204 7.49608 12.2111C6.00708 10.7151 4.46808 9.17108 2.98608 7.62508C2.02808 6.62508 1.80708 5.45508 2.33008 4.14608C2.85008 2.84308 3.80008 2.17208 5.23108 2.09508C6.15308 2.04508 6.94908 2.36508 7.66408 3.07208C7.79208 3.19908 7.91708 3.33408 8.05008 3.47708L8.24008 3.68108C8.63208 4.09508 9.28108 4.11008 9.69108 3.71408C10.1011 3.31908 10.1151 2.66208 9.72408 2.24808C9.66408 2.18542 9.60441 2.12175 9.54508 2.05708C9.40508 1.90375 9.25608 1.74775 9.09808 1.58908C7.96608 0.470084 6.62808 -0.0569163 5.12208 0.0240837C2.91008 0.142084 1.24208 1.33108 0.428078 3.36908C-0.401922 5.44708 -0.0169216 7.47108 1.51308 9.06808C3.01053 10.62 4.52294 12.1574 6.05008 13.6801C6.63875 14.2708 7.22675 14.8624 7.81408 15.4551C8.17408 15.8171 8.59508 15.9991 9.01708 15.9991C9.44108 15.9991 9.86508 15.8161 10.2271 15.4501L11.6581 14.0071C13.2151 12.4371 14.8251 10.8151 16.4021 9.21008C17.6691 7.92208 18.1991 6.30408 17.9331 4.53008V4.53208Z"/>
                                            </svg>
                                        </a>
                                        <div class="games__name"> <span><?php echo esc_html($game_name); ?></span></div>
                                        <div class="games__braing"> <span><?php echo esc_html($game_brand); ?></span></div>
                                    </div>
                                </div>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
                <div class="page-content__info_item" id="keys">
                    <div class="keys">
                        <div class="keys__items">
                        <div class="keys__item_heading">
                            <h5><?php echo esc_html($key_facts_heading); ?></h5>
                        </div>
                        <?php if(is_array($key_facts_items) && !empty($key_facts_items)): ?>
                            <?php foreach($key_facts_items as $fact): ?>
                                <div class="keys__item">
                                    <span><?php echo esc_html($fact['fact_label']); ?></span>
                                    <span><?php echo esc_html($fact['fact_value']); ?></span>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                        </div>
                        <div class="keys__items">
                        <div class="keys__item_heading">
                            <h5><?php echo esc_html($advantages_heading); ?></h5>
                        </div>
                        <?php if(is_array($advantages_items) && !empty($advantages_items)): ?>
                            <?php foreach($advantages_items as $advantage): ?>
                                <div class="keys__item">
                                    <img src="<?php echo get_template_directory_uri(); ?>/assets/public/img/icons/arrow-in-circle-yellow.svg" alt="">
                                    <span><?php echo esc_html($advantage['advantage_text']); ?></span>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                        </div>
                    </div>
                </div>
                <div class="page-content__info_item" id="bonusHub">
                    <h2><?php echo esc_html($bonus_hub_heading); ?></h2>
                    <div class="bonus"> 
                        <?php if(is_array($bonus_items) && !empty($bonus_items)): ?>
                            <?php foreach($bonus_items as $bonus): 
                                $bonus_name = isset($bonus['bonus_name']) ? $bonus['bonus_name'] : '';
                                $bonus_cash = isset($bonus['bonus_cash']) ? $bonus['bonus_cash'] : '';
                                $bonus_spins = isset($bonus['bonus_spins']) ? $bonus['bonus_spins'] : '';
                                $bonus_button = isset($bonus['bonus_button']) ? $bonus['bonus_button'] : '';
                                $bonus_link = isset($bonus['bonus_link']) ? $bonus['bonus_link'] : '';
                                $bonus_image_data = isset($bonus['bonus_image']) ? $bonus['bonus_image'] : null;
                                $bonus_image_url = !empty($bonus_image_data['url']) ? $bonus_image_data['url'] : get_template_directory_uri() . '/assets/public/img/bonus/image-1.png';
                                $bonus_image_alt = !empty($bonus_image_data['alt']) ? $bonus_image_data['alt'] : $bonus_name;
                            ?>
                            <div class="bonus__item">
                                <div class="bonus__text_block">
                                    <div class="bonus__name"><span><?php echo esc_html($bonus_name); ?></span></div>
                                    <div class="bonus__cash">
                                        <h4><?php echo esc_html($bonus_cash); ?></h4>
                                    </div>
                                    <div class="bonus__spins"> 
                                        <h4><?php echo esc_html($bonus_spins); ?></h4>
                                    </div>
                                    <div class="bonus__btn"> 
                                        <a href="<?php echo esc_url($link_url); ?>" class="button button--register button--colored">
                                            <span><?php pll_e('sign_up_now'); ?></span>
                                        </a>
                                    </div>
                                </div>
                                <div class="bonus__image"> 
                                    <img src="<?php echo esc_url($bonus_image_url); ?>" alt="<?php echo esc_attr($bonus_image_alt); ?>">
                                </div>
                            </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                </div>

                <?php if(is_array($lorem_blocks) && !empty($lorem_blocks)): ?>
                    <?php $lorem_block_count = 0; ?>
                    <?php foreach($lorem_blocks as $block): 
                        $lorem_block_count++;
                        $block_id = 'a' . $lorem_block_count; // Используем формат a1, a2, a3
                        $title = isset($block['title']) ? $block['title'] : '';
                        $image_data = isset($block['image']) ? $block['image'] : null;
                        $image_url = !empty($image_data['url']) ? $image_data['url'] : '';
                        $image_alt = !empty($image_data['alt']) ? $image_data['alt'] : $title;
                        $content = isset($block['content']) ? $block['content'] : '';
                        $show_button = isset($block['show_button']) ? $block['show_button'] : false;
                    ?>
                    <div class="page-content__info_item" id="<?php echo esc_attr($block_id); ?>">
                        <!-- title -->
                        <h2><?php echo esc_html($title); ?></h2>  
                        <!-- title -->
                        
                        <?php if($image_url): ?>
                        <!-- image -->
                        <img class="simple" src="<?php echo esc_url($image_url); ?>" alt="<?php echo esc_attr($image_alt); ?>">
                        <!-- image -->
                        <?php endif; ?>

                        <?php if($content): ?>
                        <!-- Content editor -->
                        <?php echo $content; ?>
                        <!-- Content editor -->
                        <?php endif; ?>
                        
                        <?php if($show_button): ?>
                        <!-- button -->
                        <a class="button button--mainbaner" href="<?php echo esc_url($link_url); ?>" target='_self'>
                            <span><?php pll_e('get_a_bonus'); ?></span>
                        </a>
                        <!-- button -->
                        <?php endif; ?>
                    </div>
                    <?php endforeach; ?>
                <?php endif; ?>

                <div class="page-content__info_item" id="rating">
                    <h2><?php echo esc_html($ratings_heading); ?></h2>
                    <div class="ratings"> 
                        <?php if(is_array($ratings_items) && !empty($ratings_items)): ?>
                            <?php foreach($ratings_items as $rating): ?>
                                <div class="ratings__item">
                                    <span><?php echo esc_html($rating['rating_service']); ?></span>
                                    <span><?php echo esc_html($rating['rating_score']); ?></span>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                    <a class="button button--mainbaner" href="<?php echo esc_url($link_url); ?>">
                        <span><?php pll_e('get_a_bonus'); ?></span>
                    </a>
                </div>
                <div class="page-content__info_item" id="questions">
                    <h2><?php echo esc_html($faq_heading); ?></h2>
                    <div class="questions">
                        <?php if(is_array($faq_items) && !empty($faq_items)): ?>
                            <?php foreach($faq_items as $faq): ?>
                                <div class="questions__item show-item"> 
                                    <div class="questions__heading">
                                        <span><?php echo esc_html($faq['question'] ?? ''); ?></span>
                                    </div>
                                    <div class="questions__text show-text">
                                        <?php echo $faq['answer'] ?? ''; ?>
                                    </div>
                                    <div class="questions__arrow">
                                        <img src="<?php echo get_template_directory_uri(); ?>/assets/public/img/icons/arrow-down-grey.svg" alt="">
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        <?php endif; ?>
                    </div>
                    <a class="page-content__up_button" href="#backTop">
                        <img src="<?php echo get_template_directory_uri(); ?>/assets/public/img/icons/arrow-up.svg" alt="">
                    </a>
                </div>
            </div>
        </div>
        <div class="sidebar"> 
            <div class="sidebar__heading show-item-2 active">
                <h4><?php pll_e('table_of_contents'); ?></h4>
                <img src="<?php echo get_template_directory_uri(); ?>/assets/public/img/icons/arrow-down-white.svg" alt="">
            </div>
            <div class="sidebar__items show-text-2 active">
                <?php if(is_array($toc_items) && !empty($toc_items)): ?>
                    <!-- <a class="sidebar__item show-act-time" href="/"><span>22Bet - play and win</span></a> -->
                    <?php foreach($toc_items as $item): ?>
                        <?php 
                        // Используем ID в новом формате a1, a2, a3
                        $href = '#' . $item['id']; // Добавляем # к ID для ссылки
                        ?>
                        <a class="sidebar__item show-act-time" href="<?php echo esc_attr($href); ?>"><span><?php echo esc_html($item['text']); ?></span></a>
                    <?php endforeach; ?>
                <?php endif; ?>
            </div>
        </div>
    </div>
</section>

<?php
get_footer();
