<?php

/**
 * Variable Product Variation Subscription Fields
 *
 * @package ArraySubs\Features\SubscriptionProducts
 * @var int    $loop           Variation loop index
 * @var int    $arraysubs_variation_id   Variation post ID
 * @var array  $variation_data Variation data
 */

defined('ABSPATH') || exit;

$arraysubs_is_subscription = get_post_meta($arraysubs_variation_id, '_is_subscription', true);
$arraysubs_subscription_period = get_post_meta($arraysubs_variation_id, '_subscription_period', true) ?: 'month';
$arraysubs_subscription_interval = get_post_meta($arraysubs_variation_id, '_subscription_interval', true) ?: 1;
$arraysubs_subscription_length = get_post_meta($arraysubs_variation_id, '_subscription_length', true) ?: 0;
$arraysubs_enable_renewal_price = get_post_meta($arraysubs_variation_id, '_enable_renewal_price', true);
$arraysubs_renewal_price = get_post_meta($arraysubs_variation_id, '_renewal_price', true);
$arraysubs_renewal_price_after = get_post_meta($arraysubs_variation_id, '_renewal_price_after', true);
if (empty($arraysubs_renewal_price_after)) {
    $arraysubs_renewal_price_after = 1; // Default: after first period
}

// Get variation prices and sale schedule
$arraysubs_variation_obj = wc_get_product($arraysubs_variation_id);
$arraysubs_regular_price = $arraysubs_variation_obj ? $arraysubs_variation_obj->get_regular_price() : '';
$arraysubs_sale_price = $arraysubs_variation_obj ? $arraysubs_variation_obj->get_sale_price() : '';
$arraysubs_sale_price_dates_from = $arraysubs_variation_obj ? $arraysubs_variation_obj->get_date_on_sale_from('edit') : null;
$arraysubs_sale_price_dates_to = $arraysubs_variation_obj ? $arraysubs_variation_obj->get_date_on_sale_to('edit') : null;
?>

<div class="arraysubs-variation-fields">
    <!-- Enable Subscription Checkbox (controlled by product-level header checkbox) -->
    <div class="arraysubs-variation-section arraysubs-variation-header">
        <label class="arraysubs-checkbox-label arraysubs-checkbox-disabled">
            <input type="checkbox"
                name="_is_subscription[<?php echo esc_attr($loop); ?>]"
                value="yes"
                class="checkbox variation_is_subscription"
                <?php checked($arraysubs_is_subscription, 'yes'); ?>
                disabled="disabled" />
            <?php esc_html_e('Enable Subscription', 'arraysubs'); ?>
            <span class="arraysubs-controlled-note"><?php esc_html_e('(controlled by product-level setting)', 'arraysubs'); ?></span>
            <!-- Hidden field to ensure value is submitted when checkbox is disabled -->
            <?php if ($arraysubs_is_subscription === 'yes') : ?>
                <input type="hidden"
                    name="_is_subscription[<?php echo esc_attr($loop); ?>]"
                    value="yes"
                    class="variation_is_subscription_hidden" />
            <?php endif; ?>
        </label>
    </div>

    <div class="show_if_variation_subscription" style="<?php echo $arraysubs_is_subscription !== 'yes' ? 'display:none;' : ''; ?>">
        <!-- Recurring Price Info -->
        <div class="arraysubs-variation-section">
            <div class="arraysubs-variation-price-info">
                <span class="arraysubs-section-description">
                    <?php echo esc_html__('The subscription will use the variation\'s regular price and sale price (if set) for recurring billing.', 'arraysubs'); ?>
                </span>
                <div class="arraysubs-price-display">
                    <span class="arraysubs-variation-regular-price-display" data-loop="<?php echo esc_attr($loop); ?>">
                        <strong><?php echo esc_html__('Regular Price:', 'arraysubs'); ?></strong>
                        <span class="price-value"><?php echo $arraysubs_regular_price ? wp_kses_post(wc_price($arraysubs_regular_price)) : '<em>' . esc_html__('Not set', 'arraysubs') . '</em>'; ?></span>
                    </span>
                    <span class="arraysubs-variation-sale-price-display" data-loop="<?php echo esc_attr($loop); ?>" style="display: <?php echo $arraysubs_sale_price ? 'inline-block' : 'none'; ?>;">
                        <strong><?php echo esc_html__('Sale Price:', 'arraysubs'); ?></strong>
                        <span class="price-value"><?php echo $arraysubs_sale_price ? wp_kses_post(wc_price($arraysubs_sale_price)) : ''; ?></span>
                        <span class="sale-schedule" style="display: <?php echo ($arraysubs_sale_price_dates_from || $arraysubs_sale_price_dates_to) ? 'inline' : 'none'; ?>;">
                            <?php
                            if ($arraysubs_sale_price_dates_from || $arraysubs_sale_price_dates_to) {
                                $arraysubs_from_text = $arraysubs_sale_price_dates_from ? date_i18n(get_option('date_format'), $arraysubs_sale_price_dates_from->getTimestamp()) : '';
                                $arraysubs_to_text = $arraysubs_sale_price_dates_to ? date_i18n(get_option('date_format'), $arraysubs_sale_price_dates_to->getTimestamp()) : '';

                                if ($arraysubs_from_text && $arraysubs_to_text) {
                                    /* translators: 1: from date, 2: to date */
                                    echo '<em>' . sprintf(esc_html__('(%1$s - %2$s)', 'arraysubs'), esc_html($arraysubs_from_text), esc_html($arraysubs_to_text)) . '</em>';
                                } elseif ($arraysubs_from_text) {
                                    /* translators: %s: from date */
                                    echo '<em>' . sprintf(esc_html__('(From %s)', 'arraysubs'), esc_html($arraysubs_from_text)) . '</em>';
                                } elseif ($arraysubs_to_text) {
                                    /* translators: %s: to date */
                                    echo '<em>' . sprintf(esc_html__('(Until %s)', 'arraysubs'), esc_html($arraysubs_to_text)) . '</em>';
                                }
                            }
                            ?>
                        </span>
                    </span>
                </div>
            </div>
        </div>

        <!-- Billing Schedule -->
        <div class="arraysubs-variation-section">
            <div class="arraysubs-variation-row">
                <div class="arraysubs-variation-col arraysubs-variation-col-half">
                    <label><?php esc_html_e('Billing Period', 'arraysubs'); ?></label>
                    <select name="_subscription_period[<?php echo esc_attr($loop); ?>]">
                        <option value="day" <?php selected($arraysubs_subscription_period, 'day'); ?>><?php esc_html_e('Day', 'arraysubs'); ?></option>
                        <option value="week" <?php selected($arraysubs_subscription_period, 'week'); ?>><?php esc_html_e('Week', 'arraysubs'); ?></option>
                        <option value="month" <?php selected($arraysubs_subscription_period, 'month'); ?>><?php esc_html_e('Month', 'arraysubs'); ?></option>
                        <option value="year" <?php selected($arraysubs_subscription_period, 'year'); ?>><?php esc_html_e('Year', 'arraysubs'); ?></option>
                        <option value="lifetime" <?php selected($arraysubs_subscription_period, 'lifetime'); ?>><?php esc_html_e('Lifetime Deal', 'arraysubs'); ?></option>
                    </select>
                </div>
                <div class="arraysubs-variation-col arraysubs-variation-col-half">
                    <div class="arraysubs-variation-col-split">
                        <div class="arraysubs-variation-col-split-item">
                            <label><?php esc_html_e('Billing Interval', 'arraysubs'); ?></label>
                            <input type="number"
                                min="1"
                                max="12"
                                step="1"
                                name="_subscription_interval[<?php echo esc_attr($loop); ?>]"
                                value="<?php echo esc_attr($arraysubs_subscription_interval); ?>" />
                            <span class="description"><?php esc_html_e('Charge every X periods', 'arraysubs'); ?></span>
                        </div>
                        <div class="arraysubs-variation-col-split-item">
                            <label><?php esc_html_e('Subscription Length', 'arraysubs'); ?></label>
                            <input type="number"
                                min="0"
                                max="365"
                                step="1"
                                name="_subscription_length[<?php echo esc_attr($loop); ?>]"
                                value="<?php echo esc_attr($arraysubs_subscription_length); ?>" />
                            <span class="description"><?php esc_html_e('0 = never expires', 'arraysubs'); ?></span>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Trial Settings -->
        <div class="arraysubs-variation-section">
            <div class="arraysubs-section-title"><?php esc_html_e('Trial Settings', 'arraysubs'); ?></div>
            <div class="arraysubs-variation-row">
                <div class="arraysubs-variation-col arraysubs-variation-col-half">
                    <label><?php esc_html_e('Trial Length', 'arraysubs'); ?></label>
                    <input type="number"
                        min="0"
                        step="1"
                        name="_trial_length[<?php echo esc_attr($loop); ?>]"
                        value="<?php echo esc_attr(get_post_meta($arraysubs_variation_id, '_trial_length', true) ?: 0); ?>" />
                    <span class="description"><?php esc_html_e('Number of trial periods (0 = no trial)', 'arraysubs'); ?></span>
                </div>
                <div class="arraysubs-variation-col arraysubs-variation-col-half">
                    <label><?php esc_html_e('Trial Period', 'arraysubs'); ?></label>
                    <select name="_trial_period[<?php echo esc_attr($loop); ?>]">
                        <option value="day" <?php selected(get_post_meta($arraysubs_variation_id, '_trial_period', true) ?: 'day', 'day'); ?>><?php esc_html_e('Day', 'arraysubs'); ?></option>
                        <option value="week" <?php selected(get_post_meta($arraysubs_variation_id, '_trial_period', true) ?: 'day', 'week'); ?>><?php esc_html_e('Week', 'arraysubs'); ?></option>
                        <option value="month" <?php selected(get_post_meta($arraysubs_variation_id, '_trial_period', true) ?: 'day', 'month'); ?>><?php esc_html_e('Month', 'arraysubs'); ?></option>
                        <option value="year" <?php selected(get_post_meta($arraysubs_variation_id, '_trial_period', true) ?: 'day', 'year'); ?>><?php esc_html_e('Year', 'arraysubs'); ?></option>
                    </select>
                </div>
            </div>
        </div>

        <!-- Sign-up Fee -->
        <div class="arraysubs-variation-section">
            <div class="arraysubs-section-title"><?php esc_html_e('Sign-up Fee', 'arraysubs'); ?></div>
            <div class="arraysubs-variation-row">
                <div class="arraysubs-variation-col arraysubs-variation-col-half">
                    <label>
                        <?php esc_html_e('Sign-up Fee', 'arraysubs'); ?>
                        <?php echo '(' . esc_html(get_woocommerce_currency_symbol()) . ')'; ?>
                    </label>
                    <input type="number"
                        step="0.01"
                        min="0"
                        name="_signup_fee[<?php echo esc_attr($loop); ?>]"
                        value="<?php echo esc_attr(get_post_meta($arraysubs_variation_id, '_signup_fee', true)); ?>"
                        class="wc_input_price" />
                    <span class="description"><?php esc_html_e('One-time fee charged at signup (independent of trial)', 'arraysubs'); ?></span>
                </div>
                <div class="arraysubs-variation-col arraysubs-variation-col-half">
                    <!-- Empty column for layout consistency -->
                </div>
            </div>
        </div>

        <!-- Different Renewal Price -->
        <div class="arraysubs-variation-section">
            <div class="arraysubs-section-title">
                <label class="arraysubs-checkbox-label">
                    <input type="checkbox"
                        name="_enable_renewal_price[<?php echo esc_attr($loop); ?>]"
                        value="yes"
                        class="checkbox variation_enable_renewal_price"
                        <?php checked($arraysubs_enable_renewal_price, 'yes'); ?> />
                    <?php esc_html_e('Different Renewal Price', 'arraysubs'); ?>
                </label>
            </div>
            <div class="show_if_variation_renewal_price" style="<?php echo $arraysubs_enable_renewal_price !== 'yes' ? 'display:none;' : ''; ?>">
                <div class="arraysubs-variation-row">
                    <div class="arraysubs-variation-col arraysubs-variation-col-half">
                        <label>
                            <?php esc_html_e('Renewal Price', 'arraysubs'); ?>
                            <?php echo '(' . esc_html(get_woocommerce_currency_symbol()) . ')'; ?>
                        </label>
                        <input type="number"
                            step="0.01"
                            min="0"
                            name="_renewal_price[<?php echo esc_attr($loop); ?>]"
                            value="<?php echo esc_attr($arraysubs_renewal_price); ?>"
                            class="wc_input_price" />
                        <span class="description"><?php esc_html_e('Price for subsequent renewals', 'arraysubs'); ?></span>
                    </div>
                    <div class="arraysubs-variation-col arraysubs-variation-col-half">
                        <label><?php esc_html_e('Apply After', 'arraysubs'); ?></label>
                        <input type="number"
                            step="1"
                            min="1"
                            name="_renewal_price_after[<?php echo esc_attr($loop); ?>]"
                            value="<?php echo esc_attr($arraysubs_renewal_price_after); ?>" />
                        <span class="description"><?php esc_html_e('Number of billing periods', 'arraysubs'); ?></span>
                    </div>
                </div>
            </div>
        </div>

        <?php
        // Shipping settings for variations
        // Check if the parent product is virtual or downloadable
        $arraysubs_parent_product_id = wp_get_post_parent_id($arraysubs_variation_id);
        $arraysubs_parent_is_virtual = 'yes' === get_post_meta($arraysubs_parent_product_id, '_virtual', true);
        $arraysubs_parent_is_downloadable = 'yes' === get_post_meta($arraysubs_parent_product_id, '_downloadable', true);

        $arraysubs_virtual_raw = $variation_data['_virtual'] ?? null;
        if (is_array($arraysubs_virtual_raw)) {
            $arraysubs_virtual_raw = $arraysubs_virtual_raw['value'] ?? reset($arraysubs_virtual_raw);
        }

        $arraysubs_downloadable_raw = $variation_data['_downloadable'] ?? null;
        if (is_array($arraysubs_downloadable_raw)) {
            $arraysubs_downloadable_raw = $arraysubs_downloadable_raw['value'] ?? reset($arraysubs_downloadable_raw);
        }

        $arraysubs_variation_is_virtual = null !== $arraysubs_virtual_raw
            ? wc_string_to_bool((string) $arraysubs_virtual_raw)
            : $arraysubs_parent_is_virtual;
        $arraysubs_variation_is_downloadable = null !== $arraysubs_downloadable_raw
            ? wc_string_to_bool((string) $arraysubs_downloadable_raw)
            : $arraysubs_parent_is_downloadable;

        // Shipping section - only when pro shipping module is active
        $arraysubs_has_shipping_module = function_exists('arraysubs_has_module') && arraysubs_has_module('SubscriptionShipping') === 1;
        ?>

        <?php
        /**
         * Allow pro features to inject subscription variation fields before the shipping section.
         *
         * @param int      $loop                   Variation loop index.
         * @param array    $variation_data         Variation data.
         * @param \WP_Post $variation             Variation post object.
         * @param int      $arraysubs_variation_id Variation ID.
         */
        do_action('arraysubs_subscription_variation_fields_before_shipping', $loop, $variation_data, $variation, $arraysubs_variation_id);
        ?>

        <?php if ($arraysubs_has_shipping_module) : ?>
            <?php
            // Get shipping meta values
            $arraysubs_variation_shipping_type = get_post_meta($arraysubs_variation_id, '_arraysubs_shipping_type', true) ?: 'recurring';
            $arraysubs_variation_initial_shipping_override = get_post_meta($arraysubs_variation_id, '_arraysubs_initial_shipping_override', true);
            $arraysubs_variation_renewal_shipping_override = get_post_meta($arraysubs_variation_id, '_arraysubs_renewal_shipping_override', true);
            ?>
            <!-- Shipping Settings for Variations -->
            <div class="arraysubs-variation-section arraysubs-variation-shipping-section"
                id="arraysubs-variation-shipping-<?php echo esc_attr($loop); ?>"
                style="<?php echo ($arraysubs_variation_is_virtual || $arraysubs_variation_is_downloadable) ? 'display:none;' : ''; ?>">
                <div class="arraysubs-section-title"><?php esc_html_e('Subscription Shipping', 'arraysubs'); ?></div>
                <p class="description" style="margin-bottom: 10px;">
                    <?php esc_html_e('Configure how shipping is handled for subscription renewals of this variation.', 'arraysubs'); ?>
                </p>

                <div class="arraysubs-variation-row">
                    <div class="arraysubs-variation-col arraysubs-variation-col-full">
                        <label><?php esc_html_e('Shipping Type', 'arraysubs'); ?></label>
                        <select name="_arraysubs_shipping_type[<?php echo esc_attr($loop); ?>]"
                            class="arraysubs-shipping-type-select">
                            <option value="recurring" <?php selected($arraysubs_variation_shipping_type, 'recurring'); ?>>
                                <?php esc_html_e('Recurring Shipping', 'arraysubs'); ?>
                            </option>
                            <option value="one-time" <?php selected($arraysubs_variation_shipping_type, 'one-time'); ?>>
                                <?php esc_html_e('One-Time Shipping', 'arraysubs'); ?>
                            </option>
                        </select>
                        <span class="description">
                            <?php esc_html_e('Recurring: Shipping charged on every renewal. One-Time: Shipping charged only on initial order.', 'arraysubs'); ?>
                        </span>
                    </div>
                </div>

                <div class="arraysubs-variation-row" style="margin-top: 10px;">
                    <div class="arraysubs-variation-col arraysubs-variation-col-half">
                        <label>
                            <?php esc_html_e('Initial Shipping Override', 'arraysubs'); ?>
                            <?php echo '(' . esc_html(get_woocommerce_currency_symbol()) . ')'; ?>
                        </label>
                        <input type="number"
                            step="0.01"
                            min="0"
                            name="_arraysubs_initial_shipping_override[<?php echo esc_attr($loop); ?>]"
                            value="<?php echo esc_attr($arraysubs_variation_initial_shipping_override); ?>"
                            placeholder="<?php esc_attr_e('0 = Use cart shipping', 'arraysubs'); ?>"
                            class="wc_input_price" />
                        <span class="description"><?php esc_html_e('Set to 0 to use WooCommerce calculated shipping.', 'arraysubs'); ?></span>
                    </div>
                    <div class="arraysubs-variation-col arraysubs-variation-col-half">
                        <label>
                            <?php esc_html_e('Renewal Shipping Override', 'arraysubs'); ?>
                            <?php echo '(' . esc_html(get_woocommerce_currency_symbol()) . ')'; ?>
                        </label>
                        <input type="number"
                            step="0.01"
                            min="0"
                            name="_arraysubs_renewal_shipping_override[<?php echo esc_attr($loop); ?>]"
                            value="<?php echo esc_attr($arraysubs_variation_renewal_shipping_override); ?>"
                            placeholder="<?php esc_attr_e('0 = Same as initial', 'arraysubs'); ?>"
                            class="wc_input_price" />
                        <span class="description"><?php esc_html_e('Override shipping cost on renewals. Set to 0 to use initial shipping amount.', 'arraysubs'); ?></span>
                    </div>
                </div>
            </div>
        <?php endif; ?>
    </div>
</div>
