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

    $source = get_field('source');
    $sports = (!empty(get_field('sports'))) ? get_field('sports') : '';

    $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') : [];
  
    $position_block = $rdgb->helpers->getBlocksSpaces(get_fields());
    $date_request = $block_picks_vs_multi->get_date_filter($date_type, $since_date, $to_date);

    $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_multi->isCaching() && !empty($block_id)) {
        // Include date range in cache key to ensure unique cache entries for different date ranges
        // Incorporate date hash into block_id to maintain standard 5-part cache name structure
        $cache_block_id = $block_id;
        if (isset($date_request) && is_array($date_request) && (!empty($date_request['start']) || !empty($date_request['end']))) {
            // Generate date hash and append to block_id to keep standard cache name format
            $date_hash = md5(($date_request['start'] ?? '') . '|' . ($date_request['end'] ?? ''));
            $cache_block_id = $block_id . '-' . $date_hash;
        }
        $cache_name = $rdgb->helpers->getBlocksCacheName($block_name, $post_type, $post_id, $cache_block_id);
        $cache_block = $cache->getCacheBlock($cache_name);
        $cache_block_array = $rdgb->helpers->isJson($cache_block);

        // Backward compatibility: If cache not found with new format (date hash in block_id),
        // try old format (date suffix as 6th part) for existing caches
        if (!$cache_block && isset($date_request) && is_array($date_request) && (!empty($date_request['start']) || !empty($date_request['end']))) {
            $date_hash = md5(($date_request['start'] ?? '') . '|' . ($date_request['end'] ?? ''));
            $old_format_cache_name = $rdgb->helpers->getBlocksCacheName($block_name, $post_type, $post_id, $block_id) . ':' . $date_hash;
            $old_format_cache_block = $cache->getCacheBlock($old_format_cache_name);
            if ($old_format_cache_block) {
                $cache_block = $old_format_cache_block;
                $cache_name = $old_format_cache_name;
                $cache_block_array = $rdgb->helpers->isJson($cache_block);
                if (defined('WP_DEBUG') && WP_DEBUG) {
                    error_log('[RDG Picks VS Multi Debug] Using old format cache: ' . $old_format_cache_name);
                }
            }
        }
        
        // If still not found, try without date hash as fallback
        // This handles cases where cache was saved without date filtering
        if (!$cache_block) {
            $fallback_cache_name = $rdgb->helpers->getBlocksCacheName($block_name, $post_type, $post_id, $block_id);
            $fallback_cache_block = $cache->getCacheBlock($fallback_cache_name);
            if ($fallback_cache_block) {
                $cache_block = $fallback_cache_block;
                $cache_name = $fallback_cache_name;
                $cache_block_array = $rdgb->helpers->isJson($cache_block);
                if (defined('WP_DEBUG') && WP_DEBUG) {
                    error_log('[RDG Picks VS Multi Debug] Using fallback cache (no date): ' . $fallback_cache_name);
                }
            }
        }

        // Diagnostic logging to identify rendering issues
        if (defined('WP_DEBUG') && WP_DEBUG) {
            error_log(sprintf(
                '[RDG Picks VS Multi Debug] Block ID: %s | Cache Name: %s | Cache Found: %s | Date Request: %s | Cache Block ID: %s',
                $block_id,
                $cache_name,
                $cache_block ? 'YES' : 'NO',
                json_encode($date_request),
                $cache_block_id
            ));
            
            if ($cache_block_array) {
                $api_resp = $cache_block_array['api_response'] ?? null;
                error_log(sprintf(
                    '[RDG Picks VS Multi Debug] Cache Array Valid: YES | Has api_response: %s | api_response is array: %s | api_response count: %s | api_response keys: %s',
                    isset($api_resp) ? 'YES' : 'NO',
                    is_array($api_resp) ? 'YES' : 'NO',
                    is_array($api_resp) ? count($api_resp) : 'N/A',
                    is_array($api_resp) ? implode(', ', array_keys($api_resp)) : 'N/A'
                ));
            } else {
                error_log('[RDG Picks VS Multi Debug] Cache Array Valid: NO | Cache Block: ' . ($cache_block ? 'exists but invalid JSON' : 'not found'));
            }
        }

        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 structure for rdg-picks-vs-multi
            // Cache may have hierarchy structure: {hierarchy_id: [picks...]} or multiple hierarchies
            // Template expects: [[picks...], [picks...]] - array of groups
            if (is_array($picks_raw) && !empty($picks_raw)) {
                // Check if this is hierarchy format (keys are hierarchy IDs, not sequential 0,1,2...)
                $keys = array_keys($picks_raw);
                $expected_keys = range(0, count($picks_raw) - 1);
                $has_hierarchy_keys = ($keys !== $expected_keys);
                
                // Also check if first key is a large number (typical hierarchy ID) or non-numeric
                if (!$has_hierarchy_keys && count($keys) > 0) {
                    $first_key = $keys[0];
                    if (is_numeric($first_key) && $first_key > 100) {
                        // Hierarchy IDs are typically > 100, sequential group keys start at 0
                        $has_hierarchy_keys = true;
                    } elseif (!is_numeric($first_key)) {
                        $has_hierarchy_keys = true;
                    }
                }
                
                if ($has_hierarchy_keys) {
                    // Convert hierarchy structure to group structure
                    // {277: [picks...], 278: [picks...]} => [[picks...], [picks...]]
                    $picks = [];
                    foreach ($picks_raw as $hierarchy_id => $hierarchy_picks) {
                        if (is_array($hierarchy_picks) && !empty($hierarchy_picks)) {
                            // Each hierarchy becomes a group
                            $picks[] = $hierarchy_picks;
                        }
                    }
                } else {
                    // Already in correct format or empty
                    $picks = $picks_raw;
                }
                
                // Log normalization result
                if (defined('WP_DEBUG') && WP_DEBUG) {
                    $normalized_count = is_array($picks) ? count($picks) : 0;
                    $first_group_count = (is_array($picks) && isset($picks[0]) && is_array($picks[0])) ? count($picks[0]) : 0;
                    error_log(sprintf(
                        '[RDG Picks VS Multi Debug] Picks normalized | Original keys: [%s] | Original count: %s | Normalized count: %s | First group count: %s | Has hierarchy keys: %s | Picks empty check: %s | Picks structure: %s',
                        implode(', ', $keys),
                        count($picks_raw),
                        $normalized_count,
                        $first_group_count,
                        $has_hierarchy_keys ? 'YES' : 'NO',
                        empty($picks) ? 'YES (empty)' : 'NO (not empty)',
                        is_array($picks) ? 'array with ' . count($picks) . ' groups' : gettype($picks)
                    ));
                }
            } else {
                $picks = $picks_raw;
                if (defined('WP_DEBUG') && WP_DEBUG) {
                    error_log('[RDG Picks VS Multi Debug] Picks not normalized - picks_raw is not array or empty');
                }
            }
        } else {
            // Log why picks is not being set
            if (defined('WP_DEBUG') && WP_DEBUG) {
                if (!$cache_block_array) {
                    error_log('[RDG Picks VS Multi Debug] Picks not set: cache_block_array is null or invalid JSON');
                } elseif (!is_array($cache_block_array['api_response'])) {
                    error_log('[RDG Picks VS Multi Debug] Picks not set: api_response is not an array. Type: ' . gettype($cache_block_array['api_response'] ?? 'not set'));
                }
            }
        }
    } else {
        // Log why cache lookup is skipped
        if (defined('WP_DEBUG') && WP_DEBUG) {
            $skip_reasons = [];
            if ($source != 'api') $skip_reasons[] = 'source != api (source: ' . $source . ')';
            if (!$block_picks_vs_multi->isCaching()) $skip_reasons[] = 'caching disabled';
            if (empty($block_id)) $skip_reasons[] = 'block_id is empty';
            error_log('[RDG Picks VS Multi Debug] Cache lookup skipped: ' . implode(' | ', $skip_reasons));
        }
    }
    
?>
<?php 
    // Additional debug check
    $picks_empty = empty($picks);
    $picks_count = is_array($picks) ? count($picks) : 0;
    $should_render = !$picks_empty && $picks_count > 0;
    if(defined('RDGBLOCKS_DEBUG_BLOCK_INFO') && RDGBLOCKS_DEBUG_BLOCK_INFO) {
        $display_block_debug_info = RDGBLOCKS_DEBUG_BLOCK_INFO;
    } else {
        $display_block_debug_info = false;
    }
    
    
    if (defined('WP_DEBUG') && WP_DEBUG && !$should_render) {
        error_log(sprintf(
            '[RDG Picks VS Multi Debug] Render check failed | Picks empty: %s | Picks count: %s | Picks type: %s | Should render: %s',
            $picks_empty ? 'YES' : 'NO',
            $picks_count,
            gettype($picks),
            $should_render ? 'YES' : 'NO'
        ));
    }
?>
<?php if ($should_render): ?>
    <div class="rdg-blocks">
        <?php
            $params = ['cache_name' => $cache_name, 'api_request' => $api_attributes];
            $block_picks_vs_multi->getLogDebug($params);
        ?>
        <div class="<?php echo esc_attr(join(' ', $block_classes)); ?>" style="<?php echo $position_block . esc_attr(join(' ', $block_styles)); ?>">
            <?php require RDGBLOCKS_PLUGIN_BLOCKS_DIR.'partials/titles.php'; ?>
                <div class="pvm-container">
                    <?php
                        if ($source == 'api') {
                            // Pass picks to partial explicitly
                            if (defined('WP_DEBUG') && WP_DEBUG) {
                                error_log(sprintf(
                                    '[RDG Picks VS Multi Template] Before requiring api.php | Picks isset: %s | Picks count: %s',
                                    isset($picks) ? 'YES' : 'NO',
                                    (isset($picks) && is_array($picks)) ? count($picks) : 'N/A'
                                ));
                            }
                            require 'partials/api.php';
                        } else {
                            require 'partials/manual.php';
                        }
                    ?>
            </div>
        </div>
    </div>
<?php elseif ($display_block_debug_info): ?>
    <?php 
    // Temporary visible debug output
    if (current_user_can('administrator')): ?>
        <div style="border: 2px solid red; padding: 10px; margin: 10px; background: #fff; color: #000;">
            <strong>RDG Picks VS Multi Debug (Admin Only):</strong><br>
            Source: <?php echo $source ?? 'not set'; ?><br>
            Block ID: <?php echo $block_id ?? 'not set'; ?><br>
            Cache Name: <?php echo $cache_name ?? 'not set'; ?><br>
            Is Caching: <?php echo $block_picks_vs_multi->isCaching() ? 'YES' : 'NO'; ?><br>
            Cache Block Found: <?php echo isset($cache_block) && $cache_block ? 'YES' : 'NO'; ?><br>
            Cache Block Array: <?php echo isset($cache_block_array) && $cache_block_array ? 'YES' : 'NO'; ?><br>
            Picks: <?php 
                if (is_null($picks)) {
                    echo 'NULL';
                } elseif (empty($picks)) {
                    echo 'EMPTY';
                } else {
                    echo 'Count: ' . count($picks) . ' | Type: ' . gettype($picks);
                    if (is_array($picks) && count($picks) > 0) {
                        echo ' | First element type: ' . gettype($picks[0]);
                        if (is_array($picks[0])) {
                            echo ' | First group count: ' . count($picks[0]);
                        }
                    }
                }
            ?><br>
            Date Request: <?php echo json_encode($date_request); ?><br>
            Should Render: <?php echo $should_render ?? 'not calculated' ? 'YES' : 'NO'; ?>
        </div>
    <?php endif; ?>
    <?php if (defined('WP_DEBUG') && WP_DEBUG): ?>
        <!-- RDG Picks VS Multi Debug: Block not rendered -->
        <!-- Source: <?php echo $source; ?> -->
        <!-- Block ID: <?php echo $block_id; ?> -->
        <!-- Cache Name: <?php echo $cache_name ?? 'not set'; ?> -->
        <!-- Picks: <?php 
            if (is_null($picks)) {
                echo 'null';
            } elseif (empty($picks)) {
                echo 'empty';
            } else {
                echo 'count: ' . count($picks) . ' | type: ' . gettype($picks);
                if (is_array($picks) && count($picks) > 0) {
                    echo ' | first element type: ' . gettype($picks[0]) . ' | first element count: ' . (is_array($picks[0]) ? count($picks[0]) : 'N/A');
                }
            }
        ?> -->
        <!-- Date Request: <?php echo json_encode($date_request); ?> -->
        <!-- Cache Block Found: <?php echo isset($cache_block) && $cache_block ? 'YES' : 'NO'; ?> -->
        <!-- Cache Block Array: <?php echo isset($cache_block_array) && $cache_block_array ? 'YES' : 'NO'; ?> -->
        <!-- Is Caching: <?php echo $block_picks_vs_multi->isCaching() ? 'YES' : 'NO'; ?> -->
    <?php endif; ?>
<?php endif; ?>
