<?php 
/**
 * Build a mapping of handicapper names to local post URLs
 * Only if SH Handicappers plugin is active and the CPT exists
 */
$handicapper_local_urls = [];

// Check if SH Handicappers plugin is active and the handicapper CPT exists
if (function_exists('SHHANDICAP') && get_option('shh_status') == 1) {
    $shh = SHHANDICAP();
    $handicapper_post_type = $shh->get_slug(false);
    
    // Verify the post type exists
    if (post_type_exists($handicapper_post_type)) {
        // Query all handicapper posts
        $handicapper_posts = get_posts([
            'post_type' => $handicapper_post_type,
            'posts_per_page' => -1,
            'post_status' => 'publish',
        ]);
        
        // Build mapping: handicapper name (from ACF) => post URL
        foreach ($handicapper_posts as $hcp_post) {
            $acf_name = get_field('shh_handicappers_name', $hcp_post->ID);
            if (!empty($acf_name)) {
                $handicapper_local_urls[strtolower(trim($acf_name))] = get_permalink($hcp_post->ID);
            }
        }
    }
}
?>
<?php foreach ($handicappers as $handicapper): ?>
    <?php if (!$rdgb->helpers->validateFields($fields, $handicapper)) continue; ?>
    <?php 
        // Determine the profile URL - use local post URL if available
        $profile_url = $handicapper['profile_url'];
        $handicapper_name_key = strtolower(trim($handicapper['name']));
        if (!empty($handicapper_local_urls[$handicapper_name_key])) {
            $profile_url = $handicapper_local_urls[$handicapper_name_key];
        }
    ?>
    <div class="handicapper">
        <div class="handicapper-header">
            <div class="header-image">
                <?php
                    $image = $block_handicappers_hub->getImage($handicapper['image'], [
                        'image_type' => 'handicappers_hub',
                        'image_alt' => $handicapper['name'],
                        'logo_label' => true
                    ]);
                ?>
                <img src="<?php echo $image['url']; ?>" alt="<?php echo $image['alt']; ?>">
            </div>
            <div class="header-content">
                <div class="header-name"><a href="<?php echo esc_url($profile_url); ?>"><?php echo $handicapper['name']; ?></a></div>
                <?php 
                    // Determinar la URL a usar para el paquete
                    $package_url = null;
                    $package_name = isset($handicapper['group'][0]['name']) ? $handicapper['group'][0]['name'] : '';
                    
                    // Buscar si hay una URL configurada para este paquete
                    if (!empty($package_name) && isset($packages_with_urls)) {
                        foreach ($packages_with_urls as $package_value => $package_data) {
                            if ($package_data['title'] === $package_name && !empty($package_data['url'])) {
                                $package_url = $package_data['url'];
                                break;
                            }
                        }
                    }
                    
                    // Si no hay URL configurada, usar la de la API
                    if (empty($package_url) && isset($handicapper['group_url']) && !empty($handicapper['group_url'])) {
                        $package_url = $handicapper['group_url'];
                    }
                    
                    // Mostrar el paquete si hay nombre (con o sin URL)
                    if (!empty($package_name)):
                ?>
                    <div class="header-package">
                        <?php if (!empty($package_url)): ?>
                            <a href="<?php echo esc_url($package_url); ?>"><?php echo esc_html($package_name); ?></a>
                        <?php else: ?>
                            <span><?php echo esc_html($package_name); ?></span>
                        <?php endif; ?>
                    </div>
                <?php endif; ?>
                <?php
                    $amount = '';
                    if (strpos($handicapper['last_days_amount'], '-') === 0) {
                        $stat_class = 'danger';
                        $tem_amount = str_replace('-', '', $handicapper['last_days_amount']);
                        $amount = '-$' . number_format($tem_amount, 0, '.', ',');
                    } else {
                        $stat_class = 'success';
                        $amount = '+$' . number_format($handicapper['last_days_amount'], 0, '.', ',');
                    }
                ?>
                <div class="header-stats">Won in Last <?php echo $handicapper['last_days']; ?> days <span class="<?php echo $stat_class; ?>"><?php echo $amount; ?></span></div>
            </div>
        </div>
        <div class="handicapper-body">
            <div class="body-content">
                <?php
                    $paragraphs = preg_split('/\n+/', trim(strip_tags($handicapper['bio'])));
                    $result = implode('. ', array_map('trim', $paragraphs));
                    echo $result;
                ?>
            </div>
        </div>
        <div class="handicapper-footer">
            <div class="footer-content">
                <a href="<?php echo esc_url($profile_url); ?>">
                    <div class="footer-button">
                        <span class="button-picks"><?php echo $handicapper['today_picks']; ?> Picks available</span>
                    </div>
                </a>
            </div>
        </div>
    </div>
<?php endforeach; ?>
