<?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_HANDICAPPERS_FILTER;
    $block_classes = [$block_name];
    $block_handicappers_filter = $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) {
        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());

    $block_data = isset($block['data']) ? $block['data'] : (isset($block['attrs']['data']) ? $block['attrs']['data'] : []);
    $items_val = $block_data['number_of_items'] ?? get_field('number_of_items');
    $number_of_items = (!empty($items_val) && is_numeric($items_val)) ? intval($items_val) : 8;
    $sport = isset($block_data['handicappers_filter_sport']) ? $block_data['handicappers_filter_sport'] : (get_field('handicappers_filter_sport') ?: null);
    $package = isset($block_data['handicappers_filter_package']) ? $block_data['handicappers_filter_package'] : (get_field('handicappers_filter_package') ?: 0);

    $cache_name = null;
    $handicappers = null;
    $api_attributes = null;
    $post_id = get_the_ID();
    $post_type = get_post_type($post_id);
    $duration = isset($block_data['handicappers_filter_duration']) ? $block_data['handicappers_filter_duration'] : (get_field('handicappers_filter_duration') ?: 365);
    $mode = isset($block_data['handicappers_filter_mode']) ? $block_data['handicappers_filter_mode'] : (get_field('handicappers_filter_mode') ?: 'exclude');
    $api_params_for_fetch = [
        'sport' => $block_handicappers_filter->getSportID($sport ?? '0'),
        'package' => ($package !== null && $package !== '') ? $package : '0',
        'duration' => $duration,
        'mode' => $mode,
        'capper_exclude' => $block_handicappers_filter->getHandicappersListFromField($block_data['handicappers_filter_handicappers'] ?? get_field('handicappers_filter_handicappers')),
    ];

    if ($block_handicappers_filter->isCaching() && !empty($block_id)) {
        $cache_name = $rdgb->helpers->getBlocksCacheName($block_name, $post_type, $post_id, $block_id);
        $cache_name .= ':' . $api_params_for_fetch['sport'] . ':' . $api_params_for_fetch['package'] . ':' . $api_params_for_fetch['duration'];
        $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'];
            $handicappers = isset($cache_block_array['api_response']['handicappers']) ? $cache_block_array['api_response']['handicappers'] : [];
        } elseif ($cache_block_array && isset($cache_block_array['api_attributes']['request']) && !empty($cache_block_array['api_attributes']['request'])) {
            $api_attributes = $cache_block_array['api_attributes'];
            $response = $rdgb->helpers->getApiRequest(
                $api_attributes['request'],
                $api_attributes['method'] ?? 'GET',
                $api_attributes['headers'] ?? []
            );
            if ($response['http_code'] == 200) {
                $response_json = $rdgb->helpers->isJson($response['data']);
                if ($response_json !== null && isset($response_json['handicappers'])) {
                    $cache->updateCacheBlock($cache_name, $cache_block_array, $response_json);
                    $handicappers = $response_json['handicappers'];
                }
            }
        } else {
            $api_attrs = $block_handicappers_filter->getApiAttributes($number_of_items, $api_params_for_fetch);
            if (!empty($api_attrs['request'])) {
                $response = $rdgb->helpers->getApiRequest(
                    $api_attrs['request'],
                    $api_attrs['method'] ?? 'GET',
                    $api_attrs['headers'] ?? []
                );
                if ($response['http_code'] == 200) {
                    $response_json = $rdgb->helpers->isJson($response['data']);
                    if ($response_json !== null && isset($response_json['handicappers'])) {
                        $handicappers = $response_json['handicappers'];
                        $api_attributes = $api_attrs;
                        $cache_data = ['api_attributes' => $api_attrs, 'api_response' => $response_json];
                        $cache->updateCacheBlock($cache_name, $cache_data, $response_json);
                    }
                }
            }
            if ($handicappers === null) {
                $handicappers = [];
            }
        }
    }

    $fields = $block_handicappers_filter->getFieldsValidate();
    $packages_with_urls = $block_handicappers_filter->getHandicappersHubPackagesWithUrls();

    $mode = isset($block_data['handicappers_filter_mode']) ? $block_data['handicappers_filter_mode'] : (get_field('handicappers_filter_mode') ?: 'exclude');
    $selected_handicappers = isset($block_data['handicappers_filter_handicappers']) ? $block_data['handicappers_filter_handicappers'] : (get_field('handicappers_filter_handicappers') ?: []);
    if (!is_array($selected_handicappers)) {
        $selected_handicappers = !empty($selected_handicappers) ? [$selected_handicappers] : [];
    }
    $include_ids = array_map('strval', array_filter($selected_handicappers));
    $include_ids_lower = array_map('strtolower', $include_ids);
?>

<?php if (is_array($handicappers) && count($handicappers) > 0): ?>
    <div class="rdg-blocks">
        <div class="<?php echo esc_attr(join(' ', $block_classes)); ?>" 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="handicappers-body">
                    <div class="handicappers">
                        <?php require RDGBLOCKS_PLUGIN_BLOCKS_DIR.'rdg-handicappers-filter/partials/api.php'; ?>
                    </div>
                </div>
            </div>
        </div>
    </div>
<?php elseif ($handicappers !== null): ?>
    <div class="rdg-blocks rdg-handicappers-filter">
        <div class="container content grid-container">
            <p class="rdg-no-data-message"><?php esc_html_e('No handicappers available for the selected filters.', 'rdg-blocks'); ?></p>
        </div>
    </div>
<?php endif; ?>
