<?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_SPORT_BETTING_ODDS;
    $block_classes = [$block_name];
    $block_sport_betting_odds = $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');
    $position_block = $rdgb->helpers->getBlocksSpaces(get_fields());
    $category = (!empty(get_field('sport_betting_odds_category'))) ? get_field('sport_betting_odds_category') : '';
    $date_type = (!empty(get_field('sport_betting_odds_date_type'))) ? get_field('sport_betting_odds_date_type') : 'auto';

    if ($date_type == 'auto') {
        $date = date('Y-m-d');
    } else {
        $date = (!empty(get_field('sport_betting_odds_date'))) ? get_field('sport_betting_odds_date') : date('Y-m-d');
    }

    $sport_name = '';
    $sport_id = (!empty(get_field('sport_betting_odds_sports'))) ? get_field('sport_betting_odds_sports') : '';
    $sports = (function_exists('shMappingHierarchySports')) ? shMappingHierarchySports() : [];

    if (isset($sports[$sport_id]) && !empty($sports[$sport_id])) {
        $sport_name = ucfirst(strtolower(trim($sports[$sport_id]))).' ';
    }

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

    if ($block_sport_betting_odds->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'];
            $odds = $cache_block_array['api_response'];
            $items = $cache_block_array['items'];
        }
    }
?>

<?php if (is_array($odds) && count($odds) > 0): ?>
    <div class="rdg-blocks">
        <?php
            $params = ['cache_name' => $cache_name, 'api_request' => $api_attributes];
            $block_sport_betting_odds->getLogDebug($params);
        ?>
        <div class="<?php echo esc_attr(join(' ', $block_classes)); ?>" style="<?php echo $position_block . esc_attr(join(' ', $block_styles)); ?>">
            <div class="content">
                <input type="hidden" id="sports_hierarchy_category_data" value="<?php echo $category; ?>">
                <?php require RDGBLOCKS_PLUGIN_BLOCKS_DIR.'partials/titles.php'; ?>
                <?php
                    // Robust date parsing with multiple formats
                    $game_datetime = false;
                    $date_formats = [
                        'Y-m-d',            // 2025-11-03
                        'Y-m-d H:i:s',      // 2025-11-03 12:00:00
                        'Y-m-d H:i',        // 2025-11-03 12:00
                        'Y-m-d\TH:i:s',     // 2025-11-03T12:00:00 (ISO)
                        'Y-m-d\TH:i:sP',    // 2025-11-03T12:00:00+00:00 (ISO with timezone)
                    ];
                    
                    foreach ($date_formats as $format) {
                        $game_datetime = DateTime::createFromFormat($format, $date);
                        if ($game_datetime !== false) {
                            break;
                        }
                    }
                    
                    // If all formats fail, try strtotime as fallback
                    if ($game_datetime === false) {
                        $timestamp = strtotime($date);
                        if ($timestamp !== false) {
                            $game_datetime = new DateTime();
                            $game_datetime->setTimestamp($timestamp);
                        }
                    }
                    
                    // Display formatted date if valid
                    if ($game_datetime !== false) {
                        $date_title = $game_datetime->format('M d, Y');
                    }
                ?>

                <div class="odds">
                    <div class="title"><?php echo $sport_name; ?>Odds - <?php echo $date_title; ?></div>
                    <div class="bettings-odds">
                        <div class="odds-headers">
                            <div class="name-team">
                                <div class="odd-header odd-team"></div>
                            </div>
                            <div class="stats">
                                <div class="odd-header odd-spread">Spread</div>
                                <div class="odd-header odd-total">Total</div>
                                <div class="odd-header odd-money">Money</div>
                            </div>
                        </div>
                        <div class="odds-list">
                            <?php foreach($odds as $odd): ?>
                                <?php
                                    $data = $block_sport_betting_odds->getValidData($odd);
                                ?>
                                <div class="odd-item">
                                    <div class="team odd-team-home">
                                        <div class="name-team">
                                            <div class="odd-header odd-team"><?php echo ucwords(strtolower($odd['home_team'])); ?></div>
                                        </div>
                                        <div class="stats">
                                            <div class="odd-header odd-spread">
                                                <?php
                                                    $spread_home_points = $block_sport_betting_odds->setDataFormat($data['spread_home_points']);
                                                    $spread_home_odds = $block_sport_betting_odds->setDataFormat($data['spread_home_odds']);
                                                    if ($spread_home_points == null && $spread_home_odds == null) {
                                                        echo '-';
                                                    } else {
                                                        echo $spread_home_points.$spread_home_odds;
                                                    }
                                                ?>
                                            </div>
                                            <div class="odd-header odd-total">
                                                <?php 
                                                    $total_home_points = $block_sport_betting_odds->setDataFormat($data['total_over_points']);
                                                    $total_home_odds = $block_sport_betting_odds->setDataFormat($data['total_over_odds']);
                                                    if ($total_home_points == null && $total_home_odds == null) {
                                                        echo '-';
                                                    } else {
                                                        echo 'o'.$total_home_points.$total_home_odds;
                                                    }
                                                ?>
                                            </div>
                                            <div class="odd-header odd-money">
                                                <?php 
                                                    $money_home_points =  $block_sport_betting_odds->setDataFormat($data['money_line_home_odds']); 
                                                    if ($money_home_points == null) {
                                                        echo '-';
                                                    } else {
                                                        echo $money_home_points;
                                                    }
                                                ?>
                                            </div>
                                        </div>
                                    </div>
                                    <div class="team odd-team-visitor">
                                        <div class="name-team">
                                            <div class="odd-header odd-team"><?php echo ucwords(strtolower($odd['visitor_team'])); ?></div>
                                        </div>
                                        <div class="stats">
                                            <div class="odd-header odd-spread">
                                                <?php
                                                    $spread_visitor_points = $block_sport_betting_odds->setDataFormat($data['spread_visitor_points']);
                                                    $spread_visitor_odds = $block_sport_betting_odds->setDataFormat($data['spread_visitor_odds']);
                                                    if ($spread_visitor_points == null && $spread_visitor_odds == null) {
                                                        echo '-';
                                                    } else {
                                                        echo $spread_visitor_points.$spread_visitor_odds;
                                                    }
                                                ?>
                                            </div>
                                            <div class="odd-header odd-total">
                                                <?php 
                                                    $total_visitor_points = $block_sport_betting_odds->setDataFormat($data['total_under_points']);
                                                    $total_visitor_odds = $block_sport_betting_odds->setDataFormat($data['total_under_odds']);
                                                    if ($total_visitor_points == null && $total_visitor_odds == null) {
                                                        echo '-';
                                                    } else {
                                                        echo 'u'.$total_visitor_points.$total_visitor_odds;
                                                    }
                                                ?>
                                            </div>
                                            <div class="odd-header odd-money">
                                                <?php 
                                                    $money_visitor_points =  $block_sport_betting_odds->setDataFormat($data['money_line_visitor_odds']); 
                                                    if ($money_visitor_points == null) {
                                                        echo '-';
                                                    } else {
                                                        echo $money_visitor_points;
                                                    }
                                                ?>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
<?php endif; ?>
