<?php   
    if (isset($block['data']['isExample']) && $block['data']['isExample']) {
        echo '<img src="' . esc_url( $block['data']['preview_image'] ) . '"style="max-width:100%; min-width:100%" alt="Preview" />';
        return;
    }

    global $rdgb;
    $rdgb = (!empty($rdgb)) ? $rdgb : Rdg_Blocks::instance();

    $block_styles = [];
    $block_name = BLOCK_RDG_PICKS_VS;
    $block_classes = [$block_name];
    $block_picks_vs = $rdgb->settings->getBlock($block_name);
    $block_id = (isset($block['data']['custom_id']) && !empty($block['data']['custom_id'])) ? $block['data']['custom_id'] : $block['id'];

    $cache = new Rdg_Blocks_Cache();
    $connect = $cache->getRedisConnect();
    if (!$connect) {
        error_log(sprintf('%s / %s: Redis connection failed.', RDGBLOCKS_NAME, $block_name));
        return;
    }

    if (!empty($block['backgroundColor'])) {
        $block_classes[] = 'has-background';
        $block_classes[] = 'has-'.$block['backgroundColor'].'-background-color';
    }

    if (!empty($block['style']['color']['background'])) {
        $block_styles[] = 'background-color: '.$block['style']['color']['background'].';';
    }

    $items = (!empty(get_field('number_of_items'))) ? get_field('number_of_items') : 1;
    $picks = get_field('picks');
    $titles = get_field('titles');
    $source = get_field('source');
    $sport = (!empty(get_field('sport'))) ? get_field('sport') : '';
    $league = (!empty(get_field('league'))) ? get_field('league') : '';
    $category = (!empty(get_field('category'))) ? get_field('category') : $league; // Backward compatibility
    $link_options = (!empty(get_field('link_options'))) ? get_field('link_options') : 'none';
    $custom_link = (!empty(get_field('custom_link'))) ? get_field('custom_link') : null;
    $custom_link_rel = (!empty(get_field('custom_link_rel'))) ? get_field('custom_link_rel') : null;

    $game_part = (!empty(get_field('game_part'))) ? get_field('game_part') : 'none';
    $show_props = (!empty(get_field('show_props'))) ? get_field('show_props') : '0';
    $filter_category = (!empty(get_field('filter_category'))) ? get_field('filter_category') : 'hide';
    $filter_date = (!empty(get_field('filter_date'))) ? get_field('filter_date') : 'hide';
    $date_type = (!empty(get_field('date_type'))) ? get_field('date_type') : null;
    $since_date = (!empty(get_field('since_date'))) ? get_field('since_date') : null;
    $to_date = (!empty(get_field('to_date'))) ? get_field('to_date') : null;
    $date_ranges = (!empty(get_field('date_range'))) ? get_field('date_range') : [];
    $picks_titles = $rdgb->helpers->getSporstCategoriesOptions(true);
    $position_block = $rdgb->helpers->getBlocksSpaces(get_fields());
    $date_request = $block_picks_vs->get_date_filter($date_type, $since_date, $to_date);
    $show = (!empty(get_field('show_in'))) ? get_field('show_in') : 'column';
    $show_title = (!empty(get_field('show_title')) && get_field('show_title') != 'none') ? true : false;

    $picks = null;
    $cache_name = null;
    $api_attributes = null;
    $post_id = get_the_ID();
    $post_type = get_post_type($post_id);

    if ($source == 'api' && $block_picks_vs->isCaching() && !empty($block_id)) {
        $cache_name = $rdgb->helpers->getBlocksCacheName($block_name, $post_type, $post_id, $block_id);
        $cache_block = $cache->getCacheBlock($cache_name);
        $cache_block_array = $rdgb->helpers->isJson($cache_block);
        $titles_sports = $rdgb->helpers->getSporstCategoriesTitles(true);

        if ($cache_block_array && is_array($cache_block_array['api_response'])) {
            $api_attributes = $cache_block_array['api_attributes'];
            $picks_raw = $cache_block_array['api_response'];
            $items = $cache_block_array['items'];
            
            // Normalize picks if they have hierarchy structure (new API format)
            // Check if this is the new format: {"277": [...picks...]}
            if (is_array($picks_raw) && !isset($picks_raw[0])) {
                // New format detected - extract hierarchy
                $hierarchy_id = isset($api_attributes['hierarchy']) ? preg_replace('/\D/', '', $api_attributes['hierarchy']) : null;
                
                if ($hierarchy_id && isset($picks_raw[$hierarchy_id])) {
                    $picks = $picks_raw[$hierarchy_id];
                } else {
                    // Fallback: get first hierarchy
                    $first_key = array_key_first($picks_raw);
                    $picks = isset($picks_raw[$first_key]) ? $picks_raw[$first_key] : [];
                }
            } else {
                // Old format or already normalized
                $picks = $picks_raw;
            }
        }
    }
    
    if (strpos($category, '-')) {
        list($category_primary, $sub_category) = explode('-', $category);
    } else {
        $sub_category = null;
        $category_primary = $category;
    }

    $styles_filter_style = $block_picks_vs->get_width('style', $filter_category, $filter_date);
    $styles_filter_class_category = $block_picks_vs->get_width('class_category', $filter_category, $filter_date);
    $styles_filter_class_sub_category = $block_picks_vs->get_width('class_sub_category', $filter_category, $filter_date);

    $block_classes_tem = $block_classes;
    unset($block_classes_tem[0]);
    $color_style = esc_attr(join(' ', $block_styles));
    $color_class = esc_attr(join(' ', $block_classes_tem));
    $color_style_picks = '';
    $color_style_pick = '';
    $color_class_picks = '';
    $color_class_pick = '';
    if ($show_title) {
        $color_style_picks = $color_style;
        $color_class_picks = $color_class;
    } else {
        $color_style_pick = $color_style;
        $color_class_pick = $color_class;
    }
?>

<?php if (!empty($picks) && count($picks) > 0): ?>
    <div class="rdg-blocks">
        <?php
            $params = ['cache_name' => $cache_name, 'api_request' => $api_attributes];
            $block_picks_vs->getLogDebug($params);
        ?>
        <div <?php echo (!empty($block_id)) ? 'id="'.$block_id.'"' : ''; ?> class="<?php echo $block_classes[0] .' '. $color_class_picks; ?> <?php echo $show; ?>" style="<?php echo $position_block . $color_style_picks; ?>" data-date-type="<?php echo $date_type; ?>" data-since-date="<?php echo $since_date; ?>" data-to-date="<?php echo $to_date; ?>" data-sport="<?php echo $sport; ?>">
            <div class="container content grid-container">
                <div id="wait"></div>
                <?php if ($source == 'api'): ?>
                    <?php if ($filter_category == 'show' || ($filter_date == 'show' && is_array($date_ranges) && count($date_ranges) > 0)): ?>
                        <div class="filter" style="<?php echo $styles_filter_style; ?>">
                            <?php if ($filter_category == 'show'): ?>
                                <div class="categories <?php echo $styles_filter_class_category; ?>">
                                    <div class="select">
                                        <select id="rdg-picks-vs-category" data-items="<?php echo $items; ?>" data-block-id="<?php echo $block_id; ?>" data-custom-link-show="<?php echo $link_options; ?>" data-custom-link-url="<?php echo (!empty($custom_link) && isset($custom_link['url']) && !empty($custom_link['url'])) ? $custom_link['url'] : ''; ?>" data-custom-link-target="<?php echo (!empty($custom_link) && isset($custom_link['target']) && !empty($custom_link['target'])) ? $custom_link['target'] : ''; ?>">
                                            <?php foreach ($picks_titles as $pick_key => $pick_title): ?>
                                                <?php if (is_array($pick_title)): ?>
                                                    <optgroup label="<?php echo $pick_key; ?>">
                                                <?php endif; ?>

                                                <?php if (is_array($pick_title)): ?>
                                                    <?php foreach ($pick_title as $key => $sub_titles ): ?>
                                                        <?php $select = ''; ?>
                                                        <?php if ($key == $category_primary.'-'.$sub_category): ?>
                                                            <?php $select = 'selected'; ?>
                                                        <?php endif; ?>
                                                        
                                                        <option value="<?php echo $key; ?>" <?php echo $select; ?>><?php echo $sub_titles; ?></option>
                                                    <?php endforeach; ?>
                                                <?php else: ?>
                                                    <?php $select = ''; ?>
                                                    <?php if ($pick_key == $category_primary): ?>
                                                        <?php $select = 'selected'; ?>
                                                    <?php endif; ?>
                                                    <option value="<?php echo $pick_key; ?>" <?php echo $select; ?>><?php echo $pick_title; ?></option>
                                                <?php endif; ?>

                                                <?php if (is_array($pick_title)): ?>
                                                    </optgroup>
                                                <?php endif; ?>
                                            <?php endforeach; ?>
                                        </select>
                                    </div>
                                </div>
                            <?php endif; ?>

                            <?php if ($filter_date == 'show' && is_array($date_ranges) && count($date_ranges) > 0): ?>
                                <div class="sub-categories <?php echo $styles_filter_class_sub_category; ?>">
                                    <?php if (is_array($date_ranges) && count($date_ranges) > 0): ?>
                                        <div class="buttons">
                                            <?php $i = 1; $status = false; ?>
                                            <?php foreach($date_ranges as $date_range): ?>
                                                <?php
                                                    $icon = (!empty($date_range['icon'])) ? '<i class="fal '.$date_range['icon'].'"></i>' : '';
                                                ?>
                                                <?php if (!empty($date_range['title_date'])): ?>
                                                    <?php
                                                        if ($date_range['status'] == 'link-info') {
                                                            if ($status) {
                                                                $date_range['status'] = 'link-default';
                                                            } else {
                                                                $status = true;
                                                            }
                                                        } 
                                                    ?>
                                                    <a id="rdg_picks_vs_button_<?php echo $i; ?>" href="#" class="<?php echo $date_range['status']; ?>" data-items="<?php echo $items; ?>" data-date-type="<?php echo $date_range['date_type']; ?>" data-since-date="<?php echo (isset($date_range['since_date'])) ? $date_range['since_date'] : ''; ?>" data-to-date="<?php echo (isset($date_range['to_date'])) ? $date_range['to_date'] : ''; ?>" data-block-id="<?php echo $block_id; ?>" data-category="<?php echo $category; ?>" data-custom-link-show="<?php echo $link_options; ?>" data-custom-link-url="<?php echo (!empty($custom_link) && isset($custom_link['url']) && !empty($custom_link['url'])) ? $custom_link['url'] : ''; ?>" data-custom-link-target="<?php echo (!empty($custom_link) && isset($custom_link['target']) && !empty($custom_link['target'])) ? $custom_link['target'] : ''; ?>"><?php echo $date_range['title_date']; echo $icon;?></a>
                                                <?php endif; ?>
                                                <?php $i++; ?>
                                            <?php endforeach; ?>
                                        </div>
                                    <?php endif; ?>
                                </div>
                            <?php endif; ?>
                        </div>
                    <?php endif; ?>
                <?php endif; ?>

                <?php if ($show_title): ?>
                    <?php if ($source == 'api'): ?>
                        <?php
                            $custom_title = 1;
                            $api_title = (is_array($titles_sports) && isset($titles_sports[$category])) ? $titles_sports[$category] : '';
                            $format_title = (is_array($titles) && count($titles) > 0) ? $titles[0] : [];

                            if (!isset($format_title['title']) || $format_title['title'] == '') {
                                $format_title['title'] = $api_title;
                                $custom_title = 0;
                            }

                            list($heading, $title, $styles) = $rdgb->helpers->getTitle($format_title);
                        ?>
                        <div id="rdg-picks-vs-title" class="title" style="<?php echo $styles; ?>" data-heading="<?php echo $heading; ?>" data-custom-title="<?php echo $custom_title; ?>">
                            <<?php echo $heading; ?>><?php echo $block_picks_vs->get_picks_vs_title_format($title); ?></<?php echo $heading; ?>>
                        </div>
                    <?php else: ?>
                        <?php require RDGBLOCKS_PLUGIN_BLOCKS_DIR.'partials/titles.php'; ?>
                    <?php endif; ?>
                <?php endif; ?>

                <div class="picks">
                    <?php
                        if ($source == 'api') {
                            require 'partials/api.php';
                        } else {
                            require 'partials/manual.php';
                        }
                    ?>
                </div>
            </div>
        </div>
    </div>
<?php endif; ?>
