<?php

/**
 * Checkout Subscription Summary
 *
 * @package ArraySubs\Features\SubscriptionCheckout
 */

defined('ABSPATH') || exit;

$arraysubs_cart = WC()->cart;
if (!$arraysubs_cart) {
    return;
}

$arraysubs_subscriptions = [];

foreach ($arraysubs_cart->get_cart() as $arraysubs_cart_item) {
    $arraysubs_product_id = $arraysubs_cart_item['product_id'];
    $arraysubs_variation_id = $arraysubs_cart_item['variation_id'] ?? 0;
    $arraysubs_check_id = $arraysubs_variation_id > 0 ? $arraysubs_variation_id : $arraysubs_product_id;

    if (!arraysubs_is_subscription_product($arraysubs_check_id)) {
        continue;
    }

    $arraysubs_product = $arraysubs_cart_item['data'];
    $arraysubs_subscription_data = arraysubs_get_product_subscription_data($arraysubs_check_id);

    if (!$arraysubs_subscription_data) {
        continue;
    }

    $arraysubs_subscriptions[] = [
        'product'    => $arraysubs_product,
        'data'       => $arraysubs_subscription_data,
        'quantity'   => $arraysubs_cart_item['quantity'],
        'product_id' => $arraysubs_check_id,
    ];
}

if (empty($arraysubs_subscriptions)) {
    return;
}
?>

<div class="arraysubs-checkout-summary">
    <h3><?php esc_html_e('Subscription Details', 'arraysubs'); ?></h3>

    <?php foreach ($arraysubs_subscriptions as $arraysubs_subscription_item) : ?>
        <?php
        $arraysubs_product = $arraysubs_subscription_item['product'];
        $arraysubs_data = $arraysubs_subscription_item['data'];
        $arraysubs_quantity = $arraysubs_subscription_item['quantity'];

        // Pricing variables
        $arraysubs_recurring_price = $arraysubs_data['price']; // Current price (sale or regular)
        $arraysubs_signup_fee = $arraysubs_data['signup_fee'];
        $arraysubs_enable_different_renewal = $arraysubs_data['enable_different_renewal_price'];
        $arraysubs_different_renewal_price = $arraysubs_data['different_renewal_price'];
        $arraysubs_different_renewal_after = $arraysubs_data['different_renewal_price_after'];
        $arraysubs_is_lifetime = ($arraysubs_data['period'] ?? '') === 'lifetime';
        $arraysubs_has_trial = !$arraysubs_is_lifetime && !empty($arraysubs_data['trial_length']) && $arraysubs_data['trial_length'] > 0;
        $arraysubs_gateway_context = function_exists('arraysubs_get_current_renewal_sync_gateway_context')
            ? arraysubs_get_current_renewal_sync_gateway_context()
            : ['id' => '', 'gateway' => null];
        $arraysubs_sync_context = function_exists('arraysubs_get_renewal_sync_context')
            ? arraysubs_get_renewal_sync_context($arraysubs_data, $arraysubs_quantity, '', (string) $arraysubs_gateway_context['id'], $arraysubs_gateway_context['gateway'])
            : ['applies' => false];

        $arraysubs_billing_schedule = arraysubs_get_billing_schedule_string(
            $arraysubs_data['interval'],
            $arraysubs_data['period']
        );
        $arraysubs_billing_schedule_phrase = arraysubs_get_billing_schedule_phrase(
            $arraysubs_data['interval'],
            $arraysubs_data['period']
        );

        // Calculate first payment total
        $arraysubs_first_payment_recurring = $arraysubs_has_trial ? 0 : (
            !empty($arraysubs_sync_context['applies'])
                ? (float) $arraysubs_sync_context['initial_line_amount']
                : ($arraysubs_recurring_price * $arraysubs_quantity)
        );
        $arraysubs_first_payment_total = $arraysubs_first_payment_recurring + $arraysubs_signup_fee;
        ?>

        <div class="subscription-item">
            <h4><?php echo esc_html(arraysubs_get_subscription_product_name($arraysubs_product)); ?>
                <?php if ($arraysubs_quantity > 1) : ?>
                    <small>(x<?php echo esc_html($arraysubs_quantity); ?>)</small>
                <?php endif; ?>
            </h4>

            <ul class="subscription-terms">
                <?php
                // Recurring price info 
                ?>
                <?php if ($arraysubs_is_lifetime) : ?>
                    <li>
                        <strong><?php esc_html_e('Subscription:', 'arraysubs'); ?></strong>
                        <?php esc_html_e('Lifetime Deal — No recurring charges', 'arraysubs'); ?>
                    </li>
                <?php else : ?>
                    <li>
                        <strong>
                            <?php if ($arraysubs_has_trial) : ?>
                                <?php esc_html_e('After Trial:', 'arraysubs'); ?>
                            <?php else : ?>
                                <?php esc_html_e('Recurring:', 'arraysubs'); ?>
                            <?php endif; ?>
                        </strong>
                        <?php
                        if ($arraysubs_enable_different_renewal && !empty($arraysubs_different_renewal_price)) {
                            if ($arraysubs_different_renewal_after > 1) {
                                printf(
                                    /* translators: %1$s: price, %2$s: billing schedule, %3$d: number of payments, %4$s: renewal price */
                                    esc_html__('%1$s %2$s for the first %3$d payments, then %4$s %2$s', 'arraysubs'),
                                    wp_kses_post(wc_price($arraysubs_recurring_price * $arraysubs_quantity)),
                                    esc_html($arraysubs_billing_schedule_phrase),
                                    (int) $arraysubs_different_renewal_after,
                                    wp_kses_post(wc_price($arraysubs_different_renewal_price * $arraysubs_quantity))
                                );
                            } else {
                                printf(
                                    /* translators: %1$s: first price, %2$s: renewal price, %3$s: billing schedule */
                                    esc_html__('%1$s first payment, then %2$s %3$s', 'arraysubs'),
                                    wp_kses_post(wc_price($arraysubs_recurring_price * $arraysubs_quantity)),
                                    wp_kses_post(wc_price($arraysubs_different_renewal_price * $arraysubs_quantity)),
                                    esc_html($arraysubs_billing_schedule_phrase)
                                );
                            }
                        } else {
                            printf(
                                /* translators: 1: subscription price amount, 2: billing cycle frequency */
                                esc_html__('%1$s %2$s', 'arraysubs'),
                                wp_kses_post(wc_price($arraysubs_recurring_price * $arraysubs_quantity)),
                                esc_html($arraysubs_billing_schedule_phrase)
                            );
                        }

                        if (!empty($arraysubs_sync_context['applies']) && !empty($arraysubs_sync_context['next_payment_date'])) {
                            echo '<br><small>';
                            printf(
                                /* translators: 1: renewal date, 2: recurring amount */
                                esc_html__('First full renewal: %1$s (%2$s)', 'arraysubs'),
                                esc_html(arraysubs_format_date_local((string) $arraysubs_sync_context['next_payment_date'], \get_option('date_format'))),
                                wp_kses_post(wc_price($arraysubs_recurring_price * $arraysubs_quantity))
                            );
                            echo '</small>';
                        }
                        ?>
                    </li>
                <?php endif; ?>

                <?php
                // Signup fee info 
                ?>
                <?php if ($arraysubs_signup_fee > 0) : ?>
                    <li>
                        <strong><?php esc_html_e('Signup Fee:', 'arraysubs'); ?></strong>
                        <?php echo wp_kses_post(wc_price($arraysubs_signup_fee)); ?>
                        <small>(<?php esc_html_e('one-time', 'arraysubs'); ?>)</small>
                    </li>
                <?php endif; ?>

                <?php
                // Trial info 
                ?>
                <?php if ($arraysubs_has_trial) : ?>
                    <li>
                        <strong><?php esc_html_e('Free Trial:', 'arraysubs'); ?></strong>
                        <?php
                        $arraysubs_trial_schedule = arraysubs_get_duration_string($arraysubs_data['trial_length'], $arraysubs_data['trial_period']);
                        echo esc_html($arraysubs_trial_schedule);
                        ?>
                    </li>
                <?php endif; ?>

                <?php
                // Duration 
                ?>
                <?php if (!$arraysubs_is_lifetime && $arraysubs_data['length'] > 0) : ?>
                    <li>
                        <strong><?php esc_html_e('Duration:', 'arraysubs'); ?></strong>
                        <?php
                        /* translators: %d: total number of billing cycles for subscription duration */
                        echo esc_html(
                            sprintf(
                                /* translators: %d: total number of billing cycles for subscription duration */
                                _n(
                                    '%d billing cycle',
                                    '%d billing cycles',
                                    (int) $arraysubs_data['length'],
                                    'arraysubs'
                                ),
                                (int) $arraysubs_data['length']
                            )
                        );
                        ?>
                    </li>
                <?php elseif (!$arraysubs_is_lifetime) : ?>
                    <li>
                        <strong><?php esc_html_e('Duration:', 'arraysubs'); ?></strong>
                        <?php esc_html_e('Continues until cancelled', 'arraysubs'); ?>
                    </li>
                <?php endif; ?>

                <?php
                // Today's charge 
                ?>
                <li>
                    <strong><?php esc_html_e('Today\'s Charge:', 'arraysubs'); ?></strong>
                    <?php
                    if ($arraysubs_has_trial && $arraysubs_signup_fee > 0) {
                        printf(
                            /* translators: %s: signup fee amount */
                            esc_html__('%s (signup fee only)', 'arraysubs'),
                            wp_kses_post(wc_price($arraysubs_signup_fee))
                        );
                    } elseif ($arraysubs_has_trial) {
                        esc_html_e('Free today', 'arraysubs');
                    } elseif ($arraysubs_signup_fee > 0) {
                        if (!empty($arraysubs_sync_context['applies']) && 'prorate' === ($arraysubs_sync_context['mode'] ?? '')) {
                            printf(
                                /* translators: %1$s: prorated first charge, %2$s: signup fee, %3$s: total charge */
                                esc_html__('%1$s prorated + %2$s signup = %3$s', 'arraysubs'),
                                wp_kses_post(wc_price($arraysubs_first_payment_recurring)),
                                wp_kses_post(wc_price($arraysubs_signup_fee)),
                                wp_kses_post(wc_price($arraysubs_first_payment_total))
                            );
                        } else {
                            printf(
                                /* translators: %1$s: first payment, %2$s: signup fee, %3$s: total charge */
                                esc_html__('%1$s + %2$s signup = %3$s', 'arraysubs'),
                                wp_kses_post(wc_price($arraysubs_first_payment_recurring)),
                                wp_kses_post(wc_price($arraysubs_signup_fee)),
                                wp_kses_post(wc_price($arraysubs_first_payment_total))
                            );
                        }
                    } elseif (!empty($arraysubs_sync_context['applies']) && 'prorate' === ($arraysubs_sync_context['mode'] ?? '')) {
                        printf(
                            /* translators: %s: prorated first charge amount */
                            esc_html__('%s prorated until the synced renewal date', 'arraysubs'),
                            wp_kses_post(wc_price($arraysubs_first_payment_recurring))
                        );
                    } elseif (!empty($arraysubs_sync_context['applies']) && 'full' === ($arraysubs_sync_context['mode'] ?? '')) {
                        printf(
                            /* translators: %s: full first charge amount */
                            esc_html__('%s full first charge', 'arraysubs'),
                            wp_kses_post(wc_price($arraysubs_first_payment_recurring))
                        );
                    } else {
                        echo wp_kses_post(wc_price($arraysubs_first_payment_recurring));
                    }
                    ?>
                </li>

                <?php
                // Next charge date 
                ?>
                <?php if (!$arraysubs_is_lifetime) : ?>
                    <li>
                        <strong>
                            <?php if ($arraysubs_has_trial) : ?>
                                <?php esc_html_e('First Charge:', 'arraysubs'); ?>
                            <?php else : ?>
                                <?php esc_html_e('Next Charge:', 'arraysubs'); ?>
                            <?php endif; ?>
                        </strong>
                        <?php
                        // Calculate next payment date correctly based on trial or regular billing
                        if (!empty($arraysubs_sync_context['applies']) && !empty($arraysubs_sync_context['next_payment_date'])) {
                            $arraysubs_next_date = (string) $arraysubs_sync_context['next_payment_date'];
                        } elseif ($arraysubs_has_trial) {
                            $arraysubs_next_date = arraysubs_calculate_next_payment_date(
                                current_time('mysql', true),
                                $arraysubs_data['trial_length'],
                                $arraysubs_data['trial_period']
                            );
                        } else {
                            $arraysubs_next_date = arraysubs_calculate_next_payment_date(
                                current_time('mysql', true),
                                $arraysubs_data['interval'],
                                $arraysubs_data['period']
                            );
                        }
                        echo esc_html(arraysubs_format_date_local($arraysubs_next_date, \get_option('date_format')));

                        // Show what will be charged next time
                        if ($arraysubs_has_trial || !empty($arraysubs_sync_context['applies'])) {
                            echo ' <small>(' . wp_kses_post(wc_price($arraysubs_recurring_price * $arraysubs_quantity)) . ')</small>';
                        }
                        ?>
                    </li>
                <?php endif; ?>
            </ul>
        </div>
    <?php endforeach; ?>

    <p class="subscription-notice">
        <?php esc_html_e('By completing this purchase, you authorize us to charge your payment method for the recurring subscription amounts on the scheduled dates.', 'arraysubs'); ?>
    </p>
</div>
