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

    $source = get_field('rdg_scores_and_odds_block_type');
    $date_type = (!empty(get_field('date_type'))) ? get_field('date_type') : 'latest';
    $game_part = (!empty(get_field('rdg_scores_and_odds_game_part'))) ? get_field('rdg_scores_and_odds_game_part') : 'none';
    $specific_date = (!empty(get_field('rdg_scores_and_odds_specific_date'))) ? get_field('rdg_scores_and_odds_specific_date') : date("Y-m-d");
    $from_day = (!empty(get_field('rdg_scores_and_odds_from_day'))) ? get_field('rdg_scores_and_odds_from_day') : date("Y-m-d");
    $to_day = (!empty(get_field('rdg_scores_and_odds_to_day'))) ? get_field('rdg_scores_and_odds_to_day') : date("Y-m-d");
    $sports = (!empty(get_field('rdg_scores_and_odds_sports'))) ? get_field('rdg_scores_and_odds_sports') : '';
    $league = (!empty(get_field('rdg_scores_and_odds_league'))) ? get_field('rdg_scores_and_odds_league') : null;

    $titles = get_field('titles');
    $position_block = $rdgb->helpers->getBlocksSpaces(get_fields());

    $picks = null;
    $cache_name = null;
    $api_attributes = null;
    $post_id = get_the_ID();
    $post_type = get_post_type($post_id);
    $data_state = 'loading'; // loading, success, no_data, error

    if ($source == 'api') {
        $items = get_field('number_of_items');
        $items = (!empty($items)) ? intval($items) : 10;
        
        $api_attributes = $block_scores_and_odds->getApiAttributes($items, [
            'sports' => $sports,
            'league' => $league,
            'game_part' => $game_part,
            'date_type' => $date_type,
            'specific' => $specific_date,
            'from_day' => $from_day,
            'to_day' => $to_day
        ]);
        
        if ($block_scores_and_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'])) {
                $picks = $cache_block_array['api_response'];
            } else {
                $response = $rdgb->helpers->getApiRequest(
                    $api_attributes['request'],
                    $api_attributes['method'],
                    $api_attributes['headers']
                );
                
                if ($response['http_code'] == 200) {
                    $picks = $rdgb->helpers->isJson($response['data']);
                    if ($picks && is_array($picks) && count($picks) > 0) {
                        $data_state = 'success';
                        error_log('[RDG-SCORES-ODDS] API Response: ' . count($picks) . ' items');
                    } else {
                        $data_state = 'no_data';
                        error_log('[RDG-SCORES-ODDS] API Response: No data available');
                    }
                } else {
                    $data_state = 'error';
                    error_log('[RDG-SCORES-ODDS] API Error: HTTP ' . $response['http_code']);
                }
            }
        } else {
            $response = $rdgb->helpers->getApiRequest(
                $api_attributes['request'],
                $api_attributes['method'],
                $api_attributes['headers']
            );
            
            if ($response['http_code'] == 200) {
                $picks = $rdgb->helpers->isJson($response['data']);
                if ($picks && is_array($picks) && count($picks) > 0) {
                    $data_state = 'success';
                    error_log('[RDG-SCORES-ODDS] API Response: ' . count($picks) . ' items');
                } else {
                    $data_state = 'no_data';
                    error_log('[RDG-SCORES-ODDS] API Response: No data available');
                }
            } else {
                $data_state = 'error';
                error_log('[RDG-SCORES-ODDS] API Error: HTTP ' . $response['http_code']);
            }
        }
    } else if ($source == 'manual') {
        if (have_rows('rdg_scores_and_odds_manual')) {
            $picks = ['manual' => true];
            $data_state = 'success';
        } else {
            $data_state = 'no_data';
        }
    }

    if (is_user_logged_in() && is_array($picks) && count($picks) > 0) {
        $games_previews = $block_scores_and_odds->getPreviews($picks);
    }
?>
<?php if ($data_state == 'success' && is_array($picks) && count($picks) > 0): ?>
    <div class="rdg-blocks">
        <?php
            $params = ['cache_name' => $cache_name, 'api_request' => $api_attributes];
            $block_scores_and_odds->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="sao-container">
                <?php
                    if ($source == 'api') {
                        require 'partials/api.php';
                    } else {
                        require 'partials/manual.php';
                    }
                ?>
            </div>
        </div>
    </div>
<?php elseif ($data_state == 'no_data'): ?>
    <div class="rdg-blocks">
        <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="sao-container">
                <div class="sao-no-data">
                    <p><?php echo __('No data available at this time.', BLOCK_RDG_SCORES_AND_ODDS); ?></p>
                </div>
            </div>
        </div>
    </div>
<?php elseif ($data_state == 'error'): ?>
    <div class="rdg-blocks">
        <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="sao-container">
                <div class="sao-error">
                    <p><?php echo __('Error loading data. Please try again later.', BLOCK_RDG_SCORES_AND_ODDS); ?></p>
                </div>
            </div>
        </div>
    </div>
<?php endif; ?>
