<?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);
}
?>

<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));
        $meta_package = get_post_meta(get_the_ID(), 'shh_package_ids', true);
        $package = (!empty($meta_package)) ? $meta_package : 0;

        $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));
            }
        
    ?>
            <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 $packages[$package]; ?></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 if (is_array($memberships) && count($memberships) > 0): ?>
                                <?php foreach ($memberships as $key => $membership): ?>
                                    <?php
                                        $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'] : '';
                                        $subscribers_plan = (isset($membership['subscribers_plan']) && is_array($membership['subscribers_plan'])) ? $membership['subscribers_plan'] : [];
                                    ?>
                                    <div class="package">
                                        <?php
                                            $class = '';
                                            $is_promo = false;
                                            if (is_array($subscribers_plan) && count($subscribers_plan) > 0) {
                                                foreach ($subscribers_plan 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-header <?php echo $class; ?>">
                                            <?php if ($is_promo): ?>
                                                <span class="package-title">Limited Time Offer !</span>
                                            <?php endif; ?>
                                        </div>
                                        <div class="package-body">
                                            <div class="package-description">
                                                <div class="name"><?php echo $package_name; ?></div>
                                                <div class="picks"><?php echo $num_picks; ?> Pick available</div>
                                                <div class="includes">
                                                    <span class="label">Includes:</span>
                                                    <span><?php echo $packages_label; ?></span>
                                                </div>
                                            </div>
                                            <div class="package-price">
                                                <?php if (is_array($subscribers_plan) && count($subscribers_plan) > 0): ?>
                                                    <div class="packages">
                                                        <?php
                                                            $i = 0;
                                                            $button_default = '';
                                                            $next = false;
                                                        ?>
                                                        <?php foreach ($subscribers_plan as $plan): ?>
                                                            <?php
                                                                if ($next) continue;

                                                                $checked = '';
                                                                $plan_name = (isset($plan['name']) && !empty($plan['name'])) ? $plan['name'] : '';
                                                                $price = (isset($plan['handicapper_amount']) && !empty($plan['handicapper_amount'])) ? $plan['handicapper_amount'] : 0;
                                                                $item_name = 'item-'.$membership['id'].'-'.$plan['id'];
                                                                $item_group = 'group-'.$membership['id'];

                                                                $button_label = $plan['label'];
                                                                if (isset($plan['first_month_discount']) && $plan['first_month_discount'] == 1) {
                                                                    $button_label = str_replace('.00', '', $plan['promo_label']);

                                                                    if (isset($plan['discount']) && !empty($plan['discount'])) {
                                                                        $price = $plan['discount'];
                                                                    }

                                                                    if (isset($plan['promo_label']) && !empty($plan['promo_label'])) {
                                                                        $plan_name = $plan['promo_label'];
                                                                    }
                                                                }
                                                                
                                                                if ($i === 0) {
                                                                    $checked = 'checked';
                                                                    $button_default = str_replace('.00', '', $button_label);
                                                                }

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

                                                                if (isset($plan['first_month_discount']) && $plan['first_month_discount'] == 1) {
                                                                    $checked = '';
                                                                    $button_label = $plan['label'];
                                                                    $plan_name = (isset($plan['name']) && !empty($plan['name'])) ? $plan['name'] : '';
                                                                    $price = (isset($plan['handicapper_amount']) && !empty($plan['handicapper_amount'])) ? $plan['handicapper_amount'] : 0;

                                                                    itemAdd($item_name, $item_group, $button_label, $checked, $price, $plan_name);
                                                                    
                                                                    $next_plan = next($subscribers_plan);
                                                                    if (is_array($next_plan) && count($next_plan) > 0) $next = true;
                                                                }

                                                                $i++;
                                                            ?>
                                                            
                                                        <?php endforeach; ?>
                                                    </div>
                                                <?php endif; ?>
                                                <div class="buttons">
                                                    <a href="<?php echo $membership['url']; ?>" target="_blank" class="primary" name="<?php echo $item_group; ?>"><?php echo $button_default; ?></a>
                                                </div>
                                            </div>
                                        </div>
                                        <div class="package-footer">*Payments will be recurring, but can be canceled at any time.</div>
                                    </div>
                                <?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 function itemAdd($item_name, $item_group, $button_label, $checked, $price, $plan_name){ ?>
    <div class="item-package">
        <div class="option">
            <input type="checkbox" class="memberships-package" id="<?php echo $item_name; ?>" name="<?php echo $item_group; ?>" data-button="<?php echo $button_label; ?>" <?php echo $checked; ?>>
        </div>
        <div class="price">
            <div class="amount">$<?php echo number_format($price, 0); ?></div>
            <div class="frequency"><?php echo str_replace('.00', '', $plan_name); ?></div>
        </div>
    </div>
<?php } ?>