<?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%; min-width:100%" alt="Preview" />';
        return;
    }

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

    $block_styles = [];
    $block_name = BLOCK_RDG_SPORTS_PICKS;
    $block_classes = [$block_name];
    $block_sports_picks = $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'].';';
    }

    $picks = get_field('picks');
    $links = get_field('links');
    $source = get_field('source');
    $titles = get_field('titles');
    $position_block = $rdgb->helpers->getBlocksSpaces(get_fields());
    $show = (!empty(get_field('show_in'))) ? get_field('show_in') : 'full';
    $link_options = (!empty(get_field('link_options'))) ? get_field('link_options') : 'none';
    $custom_link = (!empty(get_field('custom_link'))) ? get_field('custom_link') : null;
    
    // Define sports array for use in partials
    $sports = (function_exists('shMappingHierarchySports')) ? shMappingHierarchySports() : [];

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

    if ($source == 'api' && $block_sports_picks->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);

        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...]], "269": [[picks...]]}
            if (is_array($picks_raw) && !empty($picks_raw)) {
                $keys = array_keys($picks_raw);
                $first_key = $keys[0] ?? null;
                
                // Check if this looks like hierarchy-keyed data (numeric keys > 100 typically)
                if ($first_key && is_numeric($first_key) && $first_key > 100) {
                    // New format detected - flatten the structure
                    // Data structure: {277: [[pick1, pick2...]], 269: [[pick3...]]}
                    // We need: [pick1, pick2, pick3...]
                    $picks = [];
                    foreach ($picks_raw as $hierarchy_id => $hierarchy_picks) {
                        if (is_array($hierarchy_picks)) {
                            foreach ($hierarchy_picks as $pick_group) {
                                if (is_array($pick_group)) {
                                    // Check if it's a single pick or an array of picks
                                    if (isset($pick_group[0]) && is_array($pick_group[0])) {
                                        // It's an array of picks: [[pick1], [pick2]]
                                        foreach ($pick_group as $pick) {
                                            if (is_array($pick) && !empty($pick)) {
                                                $picks[] = $pick;
                                            }
                                        }
                                    } else {
                                        // It's a single pick: [pick1]
                                        if (!empty($pick_group)) {
                                            $picks[] = $pick_group;
                                        }
                                    }
                                }
                            }
                        }
                    }
                } else {
                    // Standard format - use as is
                    $picks = $picks_raw;
                }
            } else {
                $picks = $picks_raw;
            }
        }
    }
?>

<?php if (!empty($picks) && count($picks) > 0): ?>
    <div class="rdg-blocks">
        <?php
            $params = ['cache_name' => $cache_name, 'api_request' => $api_attributes];
            $block_sports_picks->getLogDebug($params);
        ?>
        <div class="<?php echo esc_attr(join(' ', $block_classes)); ?> <?php echo $show; ?>" style="<?php echo $position_block . esc_attr(join(' ', $block_styles)); ?>">
            <div class="container content grid-container">
                <?php require RDGBLOCKS_PLUGIN_BLOCKS_DIR.'partials/titles.php'; ?>
                <div class="picks">
                    <?php if (!empty($picks)): ?>
                        <?php
                            if ($source == 'api') {
                                require 'partials/api.php';
                            } else {
                                require 'partials/manual.php';
                            }
                        ?>
                    <?php else: ?>
                        <?php if (!empty($message)): ?>
                            <span class="message"><?php echo $message; ?></span>
                        <?php endif; ?>
                    <?php endif; ?>
                </div>
                <?php if (is_array($links) && count($links) > 0): ?>
                    <div class="buttons">
                        <?php foreach($links as $link): ?>
                            <?php
                                $link_class = '';
                                $link_style = '';
                                if ($link['default_styles'] != 'custom') {
                                    $link_class = 'class="'.$link['default_styles'].'"';
                                } else {
                                    $link_style = 'onMouseOut="this.style.backgroundColor=\''.$link['background_color'].'\'" onmouseover="this.style.backgroundColor=\''.$link['background_hover_color'].'\'" class="link-default" style="'.$block_sports_picks->get_style('buttons', $link).'"';
                                }
                            ?>
                            <?php if (!empty($link['link']['url']) && $link['link']['title']): ?>
                                <a href="<?php echo $link['link']['url']; ?>" <?php echo $link_class; ?> <?php echo $link_style; ?>><?php echo $link['link']['title']; ?></a>
                            <?php endif; ?>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
            </div>
        </div>
    </div>
<?php endif; ?>
