<?php

/**
 * Checkout Display Trait
 *
 * Renders subscription summaries at checkout and within order details.
 *
 * @package ArraySubs\Features\SubscriptionCheckout\Services\Traits
 */

namespace ArraySubs\Features\SubscriptionCheckout\Services\Traits;

defined('ABSPATH') || exit;

/**
 * Checkout display methods
 */
trait CheckoutDisplayTrait
{
    /**
     * Display subscription summary in checkout order review table.
     *
     * @return void
     */
    public function displaySubscriptionSummaryInTable(): void
    {
        $cart = WC()->cart;

        if (!$cart) {
            return;
        }

        $subscriptions = [];

        foreach ($cart->get_cart() as $cart_item) {
            $product_id = $cart_item['product_id'];
            $variation_id = $cart_item['variation_id'] ?? 0;
            $check_id = $variation_id > 0 ? $variation_id : $product_id;

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

            $product = $cart_item['data'];
            $subscription_data = arraysubs_get_product_subscription_data($check_id);

            if (!$subscription_data) {
                continue;
            }

            $subscriptions[] = [
                'product'    => $product,
                'data'       => $subscription_data,
                'quantity'   => $cart_item['quantity'],
                'migration'  => $cart_item['arraysubs_checkout_migration'] ?? null,
            ];
        }

        if (empty($subscriptions)) {
            return;
        }

        // Output subscription details as table rows
        $has_recurring_authorization = false;

        foreach ($subscriptions as $subscription) {
            $data = $subscription['data'];
            $quantity = $subscription['quantity'];
            $migration = $subscription['migration'];

            $is_lifetime = ($data['period'] ?? '') === 'lifetime';
            $billing_schedule = arraysubs_get_billing_schedule_string($data['interval'], $data['period']);
            $billing_schedule_phrase = arraysubs_get_billing_schedule_phrase($data['interval'], $data['period']);
            $has_trial = !$is_lifetime && !empty($data['trial_length']) && $data['trial_length'] > 0;
            $signup_fee = (float) ($data['signup_fee'] ?? 0);
            $recurring_total = (float) $data['price'] * $quantity;
            $gateway_context = function_exists('arraysubs_get_current_renewal_sync_gateway_context')
                ? arraysubs_get_current_renewal_sync_gateway_context()
                : ['id' => '', 'gateway' => null];
            $sync_context = function_exists('arraysubs_get_renewal_sync_context')
                ? arraysubs_get_renewal_sync_context($data, $quantity, '', (string) $gateway_context['id'], $gateway_context['gateway'])
                : ['applies' => false];
            $first_payment_recurring = $has_trial ? 0 : (
                !empty($sync_context['applies'])
                    ? (float) $sync_context['initial_line_amount']
                    : $recurring_total
            );
            $first_payment_total = $first_payment_recurring + $signup_fee;

            if ($is_lifetime) {
                echo '<tr class="subscription-lifetime-info">';
                echo '<th>' . esc_html__('Subscription', 'arraysubs') . '</th>';
                echo '<td>' . esc_html__('Lifetime Deal — No recurring charges', 'arraysubs') . '</td>';
                echo '</tr>';
            } else {
                $has_recurring_authorization = true;

                echo '<tr class="subscription-recurring-info">';
                echo '<th>' . (is_array($migration) && !empty($migration['eligible']) ? esc_html__('Due today', 'arraysubs') : esc_html__('Recurring', 'arraysubs')) . '</th>';
                echo '<td>';
                if (is_array($migration) && !empty($migration['eligible'])) {
                    echo wp_kses_post($migration['proration']['formatted']['net'] ?? wc_price($migration['proration']['net_amount'] ?? 0));
                    echo '<br><small>' . sprintf(
                        /* translators: %s: current product name */
                        esc_html__('Replaces your current %s subscription', 'arraysubs'),
                        esc_html($migration['current_product_name'])
                    ) . '</small>';
                    echo '<br><small>' . sprintf(
                        /* translators: 1: recurring amount, 2: billing schedule */
                        esc_html__('After checkout: %1$s %2$s', 'arraysubs'),
                        wp_kses_post(wc_price($data['price'] * $quantity)),
                        esc_html($billing_schedule)
                    ) . '</small>';
                } else {
                    if ($data['enable_different_renewal_price'] && !empty($data['different_renewal_price'])) {
                        if ($data['different_renewal_price_after'] > 1) {
                            printf(
                                /* translators: %1$s: initial amount, %2$s: billing schedule, %3$d: initial payment count, %4$s: later amount. */
                                esc_html__('%1$s %2$s for the first %3$d payments, then %4$s %2$s', 'arraysubs'),
                                wp_kses_post(wc_price($data['price'] * $quantity)),
                                esc_html($billing_schedule_phrase),
                                (int) $data['different_renewal_price_after'],
                                wp_kses_post(wc_price($data['different_renewal_price'] * $quantity))
                            );
                        } else {
                            printf(
                                /* translators: %1$s: first payment amount, %2$s: later amount, %3$s: billing schedule. */
                                esc_html__('%1$s first payment, then %2$s %3$s', 'arraysubs'),
                                wp_kses_post(wc_price($data['price'] * $quantity)),
                                wp_kses_post(wc_price($data['different_renewal_price'] * $quantity)),
                                esc_html($billing_schedule_phrase)
                            );
                        }
                    } else {
                        echo wp_kses_post(wc_price($data['price'] * $quantity)) . ' ' . esc_html($billing_schedule);
                    }

                    if (!empty($sync_context['applies']) && !empty($sync_context['next_payment_date'])) {
                        echo '<br><small>' . sprintf(
                            /* translators: 1: renewal date, 2: recurring amount */
                            esc_html__('First full renewal: %1$s (%2$s)', 'arraysubs'),
                            esc_html(arraysubs_format_date_local((string) $sync_context['next_payment_date'], \get_option('date_format'))),
                            wp_kses_post(wc_price($recurring_total))
                        ) . '</small>';
                    }
                }
                echo '</td>';
                echo '</tr>';
            }

            // Signup fee row (if applicable)
            if ($signup_fee > 0) {
                echo '<tr class="subscription-signup-fee-info">';
                echo '<th>' . esc_html__('Signup Fee', 'arraysubs') . '</th>';
                echo '<td>' . wp_kses_post(wc_price($signup_fee)) . ' <small>(' . esc_html__('one-time', 'arraysubs') . ')</small></td>';
                echo '</tr>';
            }

            // Trial info
            if ($has_trial) {
                $trial_schedule = arraysubs_get_duration_string($data['trial_length'], $data['trial_period']);
                echo '<tr class="subscription-trial-info">';
                echo '<th>' . esc_html__('Free Trial', 'arraysubs') . '</th>';
                echo '<td>' . esc_html($trial_schedule) . '</td>';
                echo '</tr>';
            }

            echo '<tr class="subscription-today-charge-info">';
            echo '<th>' . esc_html__('Today\'s Charge', 'arraysubs') . '</th>';
            echo '<td>';
            if ($has_trial && $signup_fee > 0) {
                printf(
                    /* translators: %s: signup fee amount */
                    esc_html__('%s (signup fee only)', 'arraysubs'),
                    wp_kses_post(wc_price($signup_fee))
                );
            } elseif ($has_trial) {
                esc_html_e('Free (trial starts today)', 'arraysubs');
            } elseif ($signup_fee > 0) {
                if (!empty($sync_context['applies']) && 'prorate' === ($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($first_payment_recurring)),
                        wp_kses_post(wc_price($signup_fee)),
                        wp_kses_post(wc_price($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($first_payment_recurring)),
                        wp_kses_post(wc_price($signup_fee)),
                        wp_kses_post(wc_price($first_payment_total))
                    );
                }
            } elseif (!empty($sync_context['applies']) && 'prorate' === ($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($first_payment_recurring))
                );
            } elseif (!empty($sync_context['applies']) && 'full' === ($sync_context['mode'] ?? '')) {
                printf(
                    /* translators: %s: full first charge amount */
                    esc_html__('%s full first charge', 'arraysubs'),
                    wp_kses_post(wc_price($first_payment_recurring))
                );
            } else {
                echo wp_kses_post(wc_price($first_payment_recurring));
            }
            echo '</td>';
            echo '</tr>';

            if (!$is_lifetime) {
                echo '<tr class="subscription-next-charge-info">';
                echo '<th>' . esc_html__('Next Charge', 'arraysubs') . '</th>';
                echo '<td>';
                if (!empty($sync_context['applies']) && !empty($sync_context['next_payment_date'])) {
                    $next_charge_date = (string) $sync_context['next_payment_date'];
                } elseif ($has_trial) {
                    $next_charge_date = arraysubs_calculate_next_payment_date(
                        current_time('mysql', true),
                        (int) $data['trial_length'],
                        $data['trial_period']
                    );
                } else {
                    $next_charge_date = arraysubs_calculate_next_payment_date(
                        current_time('mysql', true),
                        (int) $data['interval'],
                        $data['period']
                    );
                }

                echo esc_html(arraysubs_format_date_local($next_charge_date, \get_option('date_format')));

                if ($has_trial || !empty($sync_context['applies'])) {
                    echo ' <small>(' . wp_kses_post(wc_price($recurring_total)) . ')</small>';
                }
                echo '</td>';
                echo '</tr>';
            }
        }

        if ($has_recurring_authorization) {
            echo '<tr class="subscription-authorization-notice">';
            echo '<td colspan="2"><p class="subscription-notice">';
            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');
            echo '</p></td>';
            echo '</tr>';
        }
    }

    /**
     * Display subscriptions in order details
     *
     * @param \WC_Order $order Order object
     */
    public function displayOrderSubscriptions($order): void
    {
        if (!$order) {
            return;
        }

        $arraysubs_subscription_ids = get_post_meta($order->get_id(), '_subscription_ids', true);

        if (empty($arraysubs_subscription_ids) || !is_array($arraysubs_subscription_ids)) {
            return;
        }

        include dirname(dirname(__DIR__)) . '/views/order-subscriptions.php';
    }
}
