<?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_CATEGORIES;
    $block_classes = [$block_name];
    $block_picks_vs_categories = $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'].';';
    }

    $titles = get_field('titles');
    $sports = (!empty(get_field('sports'))) ? get_field('sports') : null;
    $sports_array = $block_picks_vs_categories->get_categories_sports($sports);
    
    // Get sports titles for display (use same function as rdg-picks-vs)
    $titles_sports = $rdgb->helpers->getSporstCategoriesTitles(true);

    $link_options = (!empty(get_field('link_options'))) ? get_field('link_options') : 'none';
    $custom_link = (!empty(get_field('custom_link'))) ? get_field('custom_link') : null;
    $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;

    $position_block = $rdgb->helpers->getBlocksSpaces(get_fields());
    $date_request = $block_picks_vs_categories->get_date_filter($date_type, $since_date, $to_date);
    $show = (!empty(get_field('show_in'))) ? get_field('show_in') : 'column';
    $category_heading = (!empty(get_field('category_heading'))) ? get_field('category_heading') : 'h1';

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

    if (is_array($sports) && count($sports) > 0 && $block_picks_vs_categories->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) {
            $api_attributes = $cache_block_array['api_attributes'];
            $sports_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($sports_picks_raw) && !isset($sports_picks_raw[0])) {
                // Check if this looks like hierarchy-keyed data (numeric keys)
                $keys = array_keys($sports_picks_raw);
                $first_key = $keys[0] ?? null;
                
                if ($first_key && is_numeric($first_key)) {
                    // New format detected - data is already grouped by hierarchy
                    $sports_picks = $sports_picks_raw;
                } else {
                    // Unknown structure, try to group by id_sport
                    $sports_picks = [];
                    foreach ($sports_picks_raw as $picks_group) {
                        if (is_array($picks_group)) {
                            foreach ($picks_group as $pick) {
                                $sport_id = $pick['id_sport'] ?? 'unknown';
                                if (!isset($sports_picks[$sport_id])) {
                                    $sports_picks[$sport_id] = [];
                                }
                                $sports_picks[$sport_id][] = $pick;
                            }
                        }
                    }
                }
            } else {
                // Old format or flat array - group by id_sport
                $sports_picks = [];
                if (is_array($sports_picks_raw)) {
                    foreach ($sports_picks_raw as $pick) {
                        $sport_id = $pick['id_sport'] ?? 'unknown';
                        if (!isset($sports_picks[$sport_id])) {
                            $sports_picks[$sport_id] = [];
                        }
                        $sports_picks[$sport_id][] = $pick;
                    }
                }
            }
        } else {
            error_log('DEBUG: No cache data found');
        }
    }
?>

<?php if (is_array($sports_picks) && count($sports_picks) > 0): ?>
    <div class="rdg-blocks">
        <?php
            $params = ['cache_name' => $cache_name, 'api_request' => $api_attributes];
            $block_picks_vs_categories->getLogDebug($params);
        ?>
        <div <?php echo (!empty($block_id)) ? 'id="'.$block_id.'"' : ''; ?> 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="sports">
                    <?php foreach($sports_picks as $sport_pick_key => $sport_picks): ?>
                        <?php
                            if (is_array($sport_picks) && count($sport_picks) == 0) continue;
                                if (array_key_exists($sport_pick_key, $sports_array)) {
                                    $subcat = $sports_array[$sport_pick_key];
                                    $id_sport_category = ($subcat == 'NULL') ? $sport_pick_key : $sport_pick_key . '-' . $subcat;
                                } else {
                                    $id_sport_category = $sport_pick_key;
                                }

                            $custom_title = 1;
                            $api_title = (is_array($titles_sports) && isset($titles_sports[$id_sport_category])) ? $titles_sports[$id_sport_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, true, false);
                        ?>
                        <div class="title" style="<?php echo $styles; ?>" data-heading="<?php echo $heading; ?>" data-custom-title="<?php echo isset($custom_title) ? $custom_title : 0; ?>">
                            <<?php echo $category_heading; ?>><?php echo $block_picks_vs_categories->get_picks_vs_title_format(isset($api_title) ? $api_title : ''); ?></<?php echo $category_heading; ?>>
                        </div>

                        <div class="picks">
                            <?php if (!empty($sport_picks)): ?>
                                <?php
                                    require 'partials/api.php';
                                ?>
                            <?php else: ?>
                                <?php if (!empty($message)): ?>
                                    <span class="message"><?php echo $message; ?></span>
                                <?php endif; ?>
                            <?php endif; ?>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
        </div>
    </div>
<?php endif; ?>