<?php
/**
 * Template Name: Handicapper
 * Post Type: Handicapper
 */

get_header();

$type = get_field('shh_memberships_type', 'option');
$separator = get_field('shh_memberships_separator', 'option');
$target = get_field('shh_memberships_target', 'option');

$attributes = [
    'type' => $type,
    'separator' => $separator,
    'target' => $target,
];

$packages = shMappingMembershipsHandicappers($attributes);
$memberships = (function_exists('shMappingMembershipsData')) ? shMappingMembershipsData() : [];

if (is_array($memberships)) {
    $memberships = array_reverse($memberships, true);
}

// Package del sitio según nombre en ACF (fallback: Sports Hub ID 8).
// packages_by_slug se construye desde $memberships (id real) para que el slug coincida con el card correcto.
$site_name = get_field('shh_site_name', 'option');
$packages_by_slug = [];
if (is_array($memberships)) {
    foreach ($memberships as $mid => $m) {
        $name = isset($m['name']) ? $m['name'] : '';
        $slug = strtolower(str_replace(' ', '', (string) $name));
        if ($slug !== '') {
            $packages_by_slug[$slug] = (int) $mid;
        }
    }
}
$site_name_normalized = is_string($site_name) ? strtolower(trim(str_replace(' ', '', $site_name))) : '';
$package_site_id = isset($packages_by_slug[$site_name_normalized]) ? $packages_by_slug[$site_name_normalized] : 8;
?>
<style>
.type-handicapper .handicapper-header-wrapper {
    align-items: stretch;
}
.type-handicapper .handicapper-header-wrapper .handicapper-card .handicapper-card-stats {
    margin-top: auto;
    height: auto;
}
/* Alinear contenido de .includes a la izquierda en todas las package cards */
.type-handicapper .package .package-body .package-description .includes {
    align-self: flex-start;
    width: 100%;
    text-align: left;
    padding-left: 0;
    margin-left: 0;
}
.type-handicapper .package .package-body .package-description .includes .label,
.type-handicapper .package .package-body .package-description .includes .includes-list {
    text-align: left;
    padding-left: 0;
    margin-left: 0;
}
</style>
<main id="site-content" role="main" class="handicapper-main">

    <?php
        $bets_stats = maybe_unserialize(get_post_meta(get_the_ID(), 'shh_bets_stats', true));
        $handicapper_basic_data = maybe_unserialize(get_post_meta(get_the_ID(), 'shh_handicapper_basic_data', true));
        $today_picks = maybe_unserialize(get_post_meta(get_the_ID(), 'shh_today_picks', true));

        $url_handicapper = get_field('shh_data_url', 'options'); 
        $base_url = explode('api', $url_handicapper)[0];
        $final_url_handicapper = $base_url . 'handicapper-summary/' .$handicapper_basic_data['slug'];

        if (have_posts()) {
            $lapse = [
                'yesterday' => 'Yesterday',
                'lastthreeDays' => 'Last 3 Days',
                'lastSevenDays' => 'Last 7 Days',
                'lastThirtyDays' => 'Last 30 Days',
            ];

        while (have_posts()) {
            the_post();

            $title = get_the_title();

            $profile_position = stripos($title, 'Profile');

            if ($profile_position !== false) {
                $title = trim(substr($title, 0, $profile_position));
            }

            // Paquetes a mostrar: Premium (3) + paquetes del handicapper; 4 y 7 sustituidos por paquete del sitio. Orden: sitio, handicapper, Premium.
            $handicapper_packages = get_post_meta(get_the_ID(), 'shh_package_ids', true);
            if (!is_array($handicapper_packages)) {
                if ($handicapper_packages === '' || $handicapper_packages === null) {
                    $handicapper_packages = [];
                } else {
                    $parts = array_map('trim', explode(',', (string) $handicapper_packages));
                    $handicapper_packages = array_map('intval', array_filter($parts, static function ($p) {
                        return $p !== '';
                    }));
                }
            } else {
                $handicapper_packages = array_map('intval', $handicapper_packages);
            }
            if (empty($handicapper_packages)) {
                $handicapper_packages = [7];
            }
            $resolved = [];
            foreach ($handicapper_packages as $pid) {
                $resolved[] = ($pid === 4 || $pid === 7) ? $package_site_id : $pid;
            }
            $resolved = array_unique($resolved);
            $packages_to_show = [];
            if (in_array($package_site_id, $resolved, true)) {
                $packages_to_show[] = $package_site_id;
            }
            foreach ($resolved as $id) {
                if ($id !== 3) {
                    $packages_to_show[] = $id;
                }
            }
            $packages_to_show[] = 3;
            $packages_to_show = array_values(array_unique($packages_to_show));

            $handicapper_package_names = [];
            foreach ($resolved as $pid) {
                if (isset($memberships[$pid]['name']) && $memberships[$pid]['name'] !== '') {
                    $handicapper_package_names[] = $memberships[$pid]['name'];
                }
            }
        ?>
            <article class="type-handicapper" id="post-<?php the_ID(); ?>" <?php post_class(); ?>>
                <h1 class="shh-title"><?php the_title();?></h1>
                <section class="handicapper-header grid-container container">
                    <div class="handicapper-wrapper handicapper-header-wrapper">
                        <div class="handicapper-card">
                            <div class="handicapper-card-header">
                                <div class="handicapper-card-info">
                                <?php $capper_image = (!empty(get_the_post_thumbnail_url())) ? get_the_post_thumbnail_url() : null; ?>
                                <?php if (!empty($capper_image)): ?>
                                    <img class="handicapper-img" src="<?php echo $capper_image; ?>" alt="handicapper_image">
                                <?php endif; ?>
                                    <p class="handicapper-name"><?php echo $title; ?></p>
                                </div>
                                <div class="handicapper-card-desc">
                                <?php
                                    echo get_post_meta(get_the_ID(), 'shh_handicapper_bio', true);
                                 ?>
                                </div>
                            </div>
                            <div class="handicapper-card-stats">
                                <div class="handicapper-card-stats-info">
                                    <div class="handicapper-card-stats-info-top">
                                        <p><span class="handicapper-bold">This handicapper is part of:</span> <?php echo esc_html(implode(', ', $handicapper_package_names)); ?></p>
                                    </div>
                                    <?php
                                        $shh_last_days_amount = get_post_meta(get_the_ID(), 'shh_last_days_amount', true);
                                    ?>
                                    <div class="handicapper-card-stats-info-bottom"><?php echo esc_html($shh_last_days_amount); ?></div>
                                </div>
                                <div class="handicapper-card-stats-cta">
                                        <a href="<?php echo $final_url_handicapper; ?>" target="_blank" rel="noreferrer">All Stats</a>
                                </div>
                            </div>
                        </div>
                        <div class="handicappers-day-wrapper">
                            <?php
                            $memberships_filtered = is_array($memberships) ? array_filter($memberships, function ($m) use ($packages_to_show) {
                                return isset($m['id']) && in_array((int) $m['id'], array_map('intval', $packages_to_show), true);
                            }) : [];
                            usort($memberships_filtered, function ($a, $b) use ($packages_to_show) {
                                $pos_a = array_search((int) $a['id'], array_map('intval', $packages_to_show), true);
                                $pos_b = array_search((int) $b['id'], array_map('intval', $packages_to_show), true);
                                return $pos_a <=> $pos_b;
                            });
                            ?>
                            <?php if (count($memberships_filtered) > 0): ?>
                                <?php foreach ($memberships_filtered as $key => $membership): ?>
                                    <?php
                                    $has_plans = isset($membership['subscribers_plan']) && is_array($membership['subscribers_plan']) && count($membership['subscribers_plan']) > 0;
                                    $is_site_package = isset($membership['id']) && ((int) $membership['id'] === 4 || (int) $membership['id'] === 7);
                                    if ($has_plans || $is_site_package) {
                                        shh_render_package_card($membership);
                                    }
                                    ?>
                                <?php endforeach; ?>
                            <?php endif; ?>
                        </div>
                    </div>
                </section>
                <?php 
                $day_results = maybe_unserialize(get_post_meta(get_the_ID(), 'shh_day_results', true));

                $show_section = false;

                if (isset($day_results['lastSevenDays']) && $day_results['lastSevenDays'] >= 0) {
                    $show_section = true;
                }

                if (isset($day_results['lastThirtyDays']) && $day_results['lastThirtyDays'] >= 0) {
                    $show_section = true;
                }

                if ($show_section): ?>
                    <section class="handicapper-profits grid-container container">
                        <div class="handicapper-wrapper handicapper-profit-wrapper">
                            <?php if (isset($day_results['lastSevenDays']) && $day_results['lastSevenDays'] >= 0): ?>
                                <div class="profit">
                                    <p>Last 7 days</p>
                                    <p class="profit--accent">$<?php echo esc_html($day_results['lastSevenDays']); ?></p>
                                </div>
                            <?php endif; ?>

                            <?php if (isset($day_results['lastThirtyDays']) && $day_results['lastThirtyDays'] >= 0): ?>
                                <div class="profit">
                                    <p>Last 30 days</p>
                                    <p class="profit--accent">$<?php echo esc_html($day_results['lastThirtyDays']); ?></p>
                                </div>
                            <?php endif; ?>
                        </div>
                    </section>
                <?php endif; ?>

                <?php if (is_array($today_picks) && count($today_picks) > 0): ?>
                <section class="handicapper-today-picks grid-container container">
                    <div class="handicapper-wrapper handicapper-today-picks-wrapper">
                        <p class="shh-entry-sub-title">Today's sports picks</p>
                        <div class="shh-card-container">
                            <?php foreach ($today_picks as $key => $today_pick): ?>
                                <div class="shh-card">
                                    <div class="shh-card-row">
                                        <div class="shh-align-left shh-item-text"><?php echo esc_html($today_pick['sport_name']); ?></div>
                                        <div class="shh-align-center shh-item-text"><?php echo esc_html($today_pick['game_date']); ?></div>
                                    </div>

                                    <?php
                                        if ($today_pick['home_id'] != $today_pick['visitor_id']) {
                                            include('parts/teams.php');
                                        } else {
                                            include('parts/tournaments.php');
                                        }
                                    ?>

                        <?php if (isset($today_pick['status']) && $today_pick['status'] != "PRIVATE PICK") { ?>
                            <div class="shh-card-footer">
                                <div class="shh-item-text shh-bordered">
                                    <b>Pending:</b> <?php echo esc_html($today_pick['description']); ?>
                                </div>
                                <div class="shh-item-text">
                                    Release date: <?php echo esc_html($today_pick['game_date']); ?>
                                </div>
                            </div>
                        <?php } else { ?>
                            <div class="shh-card-footer">
                                <div class="shh-item-text shh-item-text--no-free">
                                    Subscribe to our top handicapper today and gain access to all the insider details you can't miss.
                                </div>
                                <div class="shh-pick-btn-wrapper">
                                    <a href="https://members.sportshub.com/register" rel="noreferrer nofollow" target="_blank" class="shh-pick-btn">GET THIS PICK
                                    </a>
                                </div>
                                
                            </div>
                        <?php } ?>
                        </div>
                            <?php 
                        
                        endforeach; 
                        
                        ?>
                        </div>
                    </div>
                </section>
                <?php endif; ?> 
                <div class="shh-content"><?php the_content();?></div>
            </article><!-- .post -->
            <?php
        }
    } 
?>
<script>
    document.querySelectorAll(".memberships-package").forEach(checkbox => {
        checkbox.addEventListener("click", function() {
            let groupName = this.name;

            document.querySelectorAll(`.memberships-package[name='${groupName}']`).forEach(cb => { cb.checked = false; });
            this.checked = true;

            let button = document.querySelector(`.primary[name='${groupName}']`);
            if (button) { button.textContent = this.getAttribute("data-button"); }
        });
    });
</script>
</main>
<?php get_footer(); ?>

<?php
/**
 * Renderiza una tarjeta de paquete (misma estructura) para cada paquete del handicapper.
 *
 * @param array $membership Datos del membership/paquete (name, num_picks, packages_label, sub_groups, subscribers_plan, url, id).
 */
function shh_render_package_card($membership) {
    $package_name = (isset($membership['name']) && !empty($membership['name'])) ? $membership['name'] : '';
    $num_picks = (isset($membership['num_picks']) && !empty($membership['num_picks'])) ? $membership['num_picks'] : 0;
    $packages_label = (isset($membership['packages_label']) && !empty($membership['packages_label'])) ? $membership['packages_label'] : '';
    $sub_groups = (isset($membership['sub_groups']) && is_array($membership['sub_groups'])) ? $membership['sub_groups'] : [];
    $includes_text = $packages_label;
    if (!empty($sub_groups)) {
        $names = array_filter(array_map(function ($sg) {
            return isset($sg['name']) ? trim((string) $sg['name']) : '';
        }, $sub_groups));
        if (!empty($names)) {
            $includes_text = implode(' + ', $names);
        }
    }
    $subscribers_plan = (isset($membership['subscribers_plan']) && is_array($membership['subscribers_plan'])) ? $membership['subscribers_plan'] : [];
    $plans_sorted = $subscribers_plan;
    if (count($plans_sorted) > 0) {
        usort($plans_sorted, function ($a, $b) {
            $amt_a = isset($a['handicapper_amount']) ? (float) $a['handicapper_amount'] : 0.0;
            $amt_b = isset($b['handicapper_amount']) ? (float) $b['handicapper_amount'] : 0.0;
            return $amt_a <=> $amt_b;
        });
    }
    $plans_to_display = array_slice($plans_sorted, 0, 2);

    $class = '';
    $is_promo = false;
    if (is_array($plans_to_display) && count($plans_to_display) > 0) {
        foreach ($plans_to_display as $plan) {
            if (isset($plan['first_month_discount']) && $plan['first_month_discount'] == 1) {
                $is_promo = true;
                break;
            }
        }
        if ($is_promo) {
            $class = ' danger';
        }
    }
    ?>
    <div class="package">
        <div class="package-body">
            <div class="package-description">
                <div class="name"><?php echo esc_html($package_name); ?></div>
                <div class="picks"><?php echo esc_html($num_picks); ?> Pick available</div>
                <div class="includes">
                    <div class="label">Packages included:</div>
                    <div class="includes-list"><?php echo esc_html($includes_text); ?></div>
                </div>
            </div>
            <div class="package-price">
                <?php
                $button_default = '';
                $item_group = 'group-' . (isset($membership['id']) ? $membership['id'] : uniqid());
                if (is_array($plans_to_display) && count($plans_to_display) > 0):
                    $i = 0;
                    $next = false;
                    ?>
                    <div class="packages">
                        <?php foreach ($plans_to_display as $plan): ?>
                            <?php
                            if ($next) {
                                $next = false;
                                continue;
                            }

                            $checked = '';
                            $duration_name = (isset($plan['duration_name']) && $plan['duration_name'] !== '') ? $plan['duration_name'] : '';
                            $item_display_text = trim($duration_name);
                            if ($item_display_text === '') {
                                $item_display_text = (isset($plan['name']) && !empty($plan['name'])) ? $plan['name'] : '';
                            }
                            $price = (isset($plan['handicapper_amount']) && !empty($plan['handicapper_amount'])) ? $plan['handicapper_amount'] : 0;
                            $item_name = 'item-' . (isset($membership['id']) ? $membership['id'] : '') . '-' . (isset($plan['id']) ? $plan['id'] : $i);
                            $item_group = 'group-' . (isset($membership['id']) ? $membership['id'] : '');

                            $button_label = isset($plan['label']) ? $plan['label'] : '';
                            if (isset($plan['first_month_discount']) && $plan['first_month_discount'] == 1) {
                                $button_label = isset($plan['promo_label']) ? str_replace('.00', '', $plan['promo_label']) : $button_label;
                                if (isset($plan['discount']) && !empty($plan['discount'])) {
                                    $price = $plan['discount'];
                                }
                                if (isset($plan['promo_label']) && !empty($plan['promo_label'])) {
                                    $item_display_text = $plan['promo_label'];
                                }
                            }
                            if ((string) $button_label === '') {
                                $p = (float) $price;
                                $price_fmt = $p == (int) $p ? number_format($p, 0) : number_format($p, 2);
                                $button_label = 'Pay $' . $price_fmt . (strlen((string) $item_display_text) > 0 ? ' ' . $item_display_text : '');
                            }

                            if ($i === 0) {
                                $checked = 'checked';
                                $button_default = str_replace('.00', '', $button_label);
                            }

                            itemAdd($item_name, $item_group, $button_label, $checked, $price, $item_display_text);

                            if (isset($plan['first_month_discount']) && $plan['first_month_discount'] == 1) {
                                $checked = '';
                                $button_label = isset($plan['label']) ? $plan['label'] : '';
                                $duration_name = (isset($plan['duration_name']) && $plan['duration_name'] !== '') ? $plan['duration_name'] : '';
                                $item_display_text = trim($duration_name);
                                if ($item_display_text === '') {
                                    $item_display_text = (isset($plan['name']) && !empty($plan['name'])) ? $plan['name'] : '';
                                }
                                $price = (isset($plan['handicapper_amount']) && !empty($plan['handicapper_amount'])) ? $plan['handicapper_amount'] : 0;
                                if ((string) $button_label === '') {
                                    $p = (float) $price;
                                    $price_fmt = $p == (int) $p ? number_format($p, 0) : number_format($p, 2);
                                    $button_label = 'Pay $' . $price_fmt . (strlen((string) $item_display_text) > 0 ? ' ' . $item_display_text : '');
                                }
                                itemAdd($item_name, $item_group, $button_label, $checked, $price, $item_display_text);
                                $next_plan = next($plans_to_display);
                                $next = is_array($next_plan) && count($next_plan) > 0;
                            }

                            $i++;
                            ?>
                        <?php endforeach; ?>
                    </div>
                <?php endif; ?>
                <div class="buttons">
                    <a href="<?php echo esc_url(isset($membership['url']) ? $membership['url'] : '#'); ?>" target="_blank" class="primary" name="<?php echo esc_attr($item_group); ?>"><?php echo esc_html($button_default); ?></a>
                </div>
                <div class="package-footer">*Payments will be recurring. Cancel at any time.</div>
            </div>
        </div>
        
    </div>
    <?php
}
?>

<?php
/**
 * @param string $display_text Texto para .frequency: handicapper_amount ya se muestra en .amount; aquí va duration_name (o name si no hay).
 */
function itemAdd($item_name, $item_group, $button_label, $checked, $price, $display_text) {
    ?>
    <div class="item-package">
        <div class="option">
            <input type="checkbox" class="memberships-package" id="<?php echo esc_attr($item_name); ?>" name="<?php echo esc_attr($item_group); ?>" data-button="<?php echo esc_attr($button_label); ?>" <?php echo $checked; ?>>
        </div>
        <div class="price">
            <div class="amount">$<?php
                $p = (float) $price;
                echo esc_html($p == (int) $p ? number_format($p, 0) : number_format($p, 2));
                ?></div>
            <div class="frequency"><?php echo esc_html(str_replace('.00', '', $display_text)); ?></div>
        </div>
    </div>
    <?php
}
?>