<?php

/**
 * Earn Points Settings Tab
 */
if ( !defined( 'ABSPATH' ) ) {
    exit;
}
function spar_settings_tab_earn() {
    $defaults = spar_settings_default();
    $options = get_option( 'spar_options', $defaults );
    // Merge with defaults and ensure earn options exist
    $options = array_merge( $defaults, $options );
    if ( isset( $options['earn'] ) && isset( $defaults['earn'] ) ) {
        foreach ( $defaults['earn'] as $earn_key => $earn_defaults ) {
            if ( isset( $options['earn'][$earn_key] ) ) {
                $options['earn'][$earn_key] = array_merge( $earn_defaults, $options['earn'][$earn_key] );
            } else {
                $options['earn'][$earn_key] = $earn_defaults;
            }
        }
    } else {
        $options['earn'] = $defaults['earn'];
    }
    $earn_options = $options['earn'];
    $points_label = $options['points_label'];
    $rewards_label = $options['rewards_label'] ?? esc_html__( 'Rewards', 'simple-points-and-rewards' );
    // Use direct Freemius check inline in template
    ?>
	<h3><?php 
    /* translators: %s: points label (lowercase) */
    printf( esc_html__( 'Ways to Earn %s', 'simple-points-and-rewards' ), esc_html( strtolower( $points_label ) ) );
    ?></h3>
	
	<p><?php 
    /* translators: %s: points label (lowercase) */
    printf( esc_html__( 'Users can earn %s by completing the following actions. Enable, re-order and customise them as needed.', 'simple-points-and-rewards' ), esc_html( strtolower( $points_label ) ) );
    ?></p>

	<div id="spar-earn-accordion-list">

    <!-- Signup Bonus -->
	<div class="spar-accordion spar-earn-accordion" data-key="signup">
		<div class="spar-accordion-header">
			<span class="spar-drag-handle dashicons dashicons-move" title="<?php 
    esc_attr_e( 'Drag to reorder', 'simple-points-and-rewards' );
    ?>"></span>
			<input type="hidden" name="earn_ways_order[]" value="signup" />
			<label>
				<div class="spar-toggle-switch">
					<input type="checkbox" name="signup_enabled" <?php 
    checked( !empty( $earn_options['signup']['enabled'] ) );
    ?> />
					<span class="spar-toggle-slider"></span>
				</div>
				<span class="spar-earn-type-badge"><i class="fa-solid fa-user-plus" aria-hidden="true"></i></span>
				<?php 
    esc_html_e( 'Signup Bonus', 'simple-points-and-rewards' );
    ?>
			</label>
			<div class="spar-earn-actions">
				<button type="button" class="button spar-toggle-earn"><?php 
    esc_html_e( 'Edit', 'simple-points-and-rewards' );
    ?></button>
			</div>
		</div>
		<div class="spar-accordion-body">
			<p class="spar-mt-0">
				<?php 
    esc_html_e( 'Points awarded when a user signs up.', 'simple-points-and-rewards' );
    ?>
			</p>
			<p>
				<?php 
    esc_html_e( 'This will be granted to existing users too, the first time they visit the rewards page after enabling this option.', 'simple-points-and-rewards' );
    ?>
			</p>
			<!-- Name of way to earn -->
			<label class="spar-inline-block spar-label-title"><?php 
    esc_html_e( 'Name:', 'simple-points-and-rewards' );
    ?></label>
			<input type="text" name="signup_name" value="<?php 
    echo esc_attr( $earn_options['signup']['name'] );
    ?>" placeholder="<?php 
    esc_attr_e( 'Signup Bonus', 'simple-points-and-rewards' );
    ?>" />
			<br/>
			<!-- Amount of points -->
			<label class="spar-inline-block spar-label-title"><?php 
    esc_html_e( 'Points:', 'simple-points-and-rewards' );
    ?></label>
			<input type="number" name="signup_points" value="<?php 
    echo esc_attr( $earn_options['signup']['points'] );
    ?>" />
			<br/>
			<!-- Show guest signup message -->
			<label class="spar-inline-block" style="margin-top:8px;">
				<input type="checkbox" name="signup_show_guest_message" <?php 
    checked( !empty( $earn_options['signup']['show_guest_message'] ) );
    ?> />
				<?php 
    esc_html_e( '(Logged out users) Show signup bonus points message', 'simple-points-and-rewards' );
    ?>
				<br/><i style="font-size: 12px;"><?php 
    esc_html_e( 'This message appears on the rewards page to inform users about the signup bonus they will receive upon registering.', 'simple-points-and-rewards' );
    ?></i>
			</label>
		</div>
	</div>

		<!-- Place an Order -->
	<div class="spar-accordion spar-earn-accordion" data-key="order">
		<div class="spar-accordion-header">
			<span class="spar-drag-handle dashicons dashicons-move" title="<?php 
    esc_attr_e( 'Drag to reorder', 'simple-points-and-rewards' );
    ?>"></span>
			<input type="hidden" name="earn_ways_order[]" value="order" />
			<label>
				<div class="spar-toggle-switch">
					<input type="checkbox" name="order_enabled" <?php 
    checked( !empty( $earn_options['order']['enabled'] ) );
    ?> />
					<span class="spar-toggle-slider"></span>
				</div>
				<span class="spar-earn-type-badge"><i class="fa-solid fa-bag-shopping" aria-hidden="true"></i></span>
				<?php 
    esc_html_e( 'Points for Spending', 'simple-points-and-rewards' );
    ?>
			</label>
			<div class="spar-earn-actions">
				<button type="button" class="button spar-toggle-earn"><?php 
    esc_html_e( 'Edit', 'simple-points-and-rewards' );
    ?></button>
			</div>
		</div>
		<div class="spar-accordion-body">
			<p class="spar-mt-0">
				<?php 
    esc_html_e( 'Points awarded for spending based on the exact amount spent.', 'simple-points-and-rewards' );
    ?>
			</p>
			<!-- Name of way to earn -->
			<label class="spar-inline-block" style="font-weight: bold;">
				<?php 
    esc_html_e( 'Name:', 'simple-points-and-rewards' );
    ?>
			</label>
			<input type="text" name="order_name" value="<?php 
    echo esc_attr( $earn_options['order']['name'] );
    ?>" placeholder="<?php 
    esc_attr_e( 'Points for Spending', 'simple-points-and-rewards' );
    ?>" />
			<br/>
			<label class="spar-inline-block" style="font-weight: bold; margin-top:8px;">
				<?php 
    esc_html_e( 'Points Earning Rate:', 'simple-points-and-rewards' );
    ?>
			</label>
			<?php 
    // Default currency context
    $store_currency = ( function_exists( 'get_woocommerce_currency' ) ? get_woocommerce_currency() : 'USD' );
    $store_currency_name = ( function_exists( 'get_woocommerce_currencies' ) ? get_woocommerce_currencies()[$store_currency] ?? $store_currency : $store_currency );
    $store_symbol = ( function_exists( 'get_woocommerce_currency_symbol' ) ? get_woocommerce_currency_symbol( $store_currency ) : '$' );
    $points_per_points = ( isset( $earn_options['order']['points_per_points'] ) ? (float) $earn_options['order']['points_per_points'] : (float) ($earn_options['order']['points_per'] ?? 0) );
    $points_per_amount = ( isset( $earn_options['order']['points_per_amount'] ) && (float) $earn_options['order']['points_per_amount'] > 0 ? (float) $earn_options['order']['points_per_amount'] : 1.0 );
    $order_calc_mode = $earn_options['order']['calculation_total_mode'] ?? 'subtotal_after_discount';
    $order_include_shipping = !empty( $earn_options['order']['calculation_include_shipping'] );
    $order_include_taxes = !empty( $earn_options['order']['calculation_include_taxes'] );
    $all_currencies = ( function_exists( 'get_woocommerce_currencies' ) ? get_woocommerce_currencies() : [] );
    $order_completed_status = ( isset( $earn_options['order']['completed_status'] ) ? sanitize_key( $earn_options['order']['completed_status'] ) : 'completed' );
    if ( empty( $order_completed_status ) ) {
        $order_completed_status = 'completed';
    }
    $core_statuses = [
        'wc-pending',
        'wc-processing',
        'wc-on-hold',
        'wc-completed',
        'wc-cancelled',
        'wc-refunded',
        'wc-failed'
    ];
    $completed_status_options = [];
    if ( function_exists( 'wc_get_order_statuses' ) ) {
        $all_statuses = wc_get_order_statuses();
        foreach ( $all_statuses as $status_key => $status_label ) {
            $status_slug = str_replace( 'wc-', '', $status_key );
            if ( 'checkout-draft' === $status_slug ) {
                continue;
            }
            if ( 'completed' === $status_slug || !in_array( $status_key, $core_statuses, true ) ) {
                $completed_status_options[$status_slug] = $status_label;
            }
        }
    }
    if ( empty( $completed_status_options ) ) {
        $completed_status_options = [
            'completed' => esc_html__( 'Completed', 'simple-points-and-rewards' ),
        ];
    }
    ?>
			<!-- Default currency rate: X points per Y amount (single row) -->
			<div class="spar-default-currency-rate spar-flex-center-gap8 spar-mb-10">
				<label class="spar-inline-block"><?php 
    esc_html_e( 'Currency:', 'simple-points-and-rewards' );
    ?></label>
				<select class="spar-w-200" disabled="disabled">
					<option value="<?php 
    echo esc_attr( $store_currency );
    ?>"><?php 
    echo esc_html( $store_currency_name . ' (' . $store_currency . ')' );
    ?></option>
				</select>
				<label class="spar-inline-block"><?php 
    esc_html_e( 'Number of points', 'simple-points-and-rewards' );
    ?>:</label>
				<input class="spar-w-150" type="number" step="0.1" min="0" name="order_points_per_points" value="<?php 
    echo esc_attr( $points_per_points );
    ?>" />
				<label class="spar-inline-block spar-earned-per-label" data-role="default"><?php 
    printf( esc_html__( 'Earned per %s spent', 'simple-points-and-rewards' ), esc_html( $store_currency ) );
    ?>:</label>
				<input id="spar-order-default-amount" class="spar-w-150" type="number" step="0.01" min="0.01" name="order_points_per_amount" value="<?php 
    echo esc_attr( $points_per_amount );
    ?>" />
			</div>

			<?php 
    ?>
			<button type="button" 
				style="margin: 5px 0 10px 0;"
				class="button spar-add-currency-rate" disabled="disabled"><?php 
    esc_html_e( 'Add New Currency', 'simple-points-and-rewards' );
    ?> (PRO)</button>
			<?php 
    ?>

			<!-- Calculation base -->
			<label class="spar-inline-block" style="margin-top:6px; font-weight: bold;">
				<?php 
    esc_html_e( 'Points calculation uses:', 'simple-points-and-rewards' );
    ?>
			</label>
			<select name="order_calculation_total_mode">
				<option value="total_before_discounts" <?php 
    selected( $order_calc_mode, 'total_before_discounts' );
    ?>>
					<?php 
    esc_html_e( 'Total before discounts', 'simple-points-and-rewards' );
    ?>
				</option>
				<option value="subtotal_after_discount" <?php 
    selected( $order_calc_mode, 'subtotal_after_discount' );
    ?>>
					<?php 
    esc_html_e( 'Subtotal after discount (default)', 'simple-points-and-rewards' );
    ?>
				</option>
			</select>
			<br/>
			<label class="spar-inline-block" style="margin-top:6px;">
				<input type="checkbox" name="order_calculation_include_shipping" <?php 
    checked( $order_include_shipping );
    ?> />
				<?php 
    esc_html_e( 'Include shipping in calculation total', 'simple-points-and-rewards' );
    ?>
			</label>
			<label class="spar-inline-block" style="margin-top:6px;">
				<input type="checkbox" name="order_calculation_include_taxes" <?php 
    checked( $order_include_taxes );
    ?> />
				<?php 
    esc_html_e( 'Include taxes in calculation total', 'simple-points-and-rewards' );
    ?>
			</label>

			<!-- When to award points -->
			<label class="spar-inline-block" style="margin-top:14px; font-weight: bold;">
				<?php 
    esc_html_e( 'Award points:', 'simple-points-and-rewards' );
    ?></label>
			<select name="order_award_timing">
				<option value="thankyou" <?php 
    selected( $earn_options['order']['award_timing'], 'thankyou' );
    ?>><?php 
    esc_html_e( 'When order is placed', 'simple-points-and-rewards' );
    ?></option>
				<option value="completed" <?php 
    selected( $earn_options['order']['award_timing'], 'completed' );
    ?>><?php 
    esc_html_e( 'When order is completed', 'simple-points-and-rewards' );
    ?></option>
			</select>
			<label class="spar-inline-block" style="margin-top:8px; font-weight: bold;">
				<?php 
    esc_html_e( 'Completed status:', 'simple-points-and-rewards' );
    ?>
			</label>
			<select name="order_completed_status">
				<?php 
    foreach ( $completed_status_options as $status_slug => $status_label ) {
        ?>
					<option value="<?php 
        echo esc_attr( $status_slug );
        ?>" <?php 
        selected( $order_completed_status, $status_slug );
        ?>><?php 
        echo esc_html( $status_label );
        ?></option>
				<?php 
    }
    ?>
			</select>
			<br/>
			<i style="font-size: 12px; display: inline-block; margin-top: 4px;">
				<?php 
    esc_html_e( 'Used when awarding points after completion.', 'simple-points-and-rewards' );
    ?>
			</i>

			<!-- Deduct points on refund -->
			<label class="spar-inline-block" style="margin-top:14px; font-weight: bold;">
				<?php 
    esc_html_e( 'Order Refunds:', 'simple-points-and-rewards' );
    ?></label>
				<input type="checkbox" name="order_deduct_on_refund" <?php 
    checked( !empty( $earn_options['order']['deduct_on_refund'] ) );
    ?> />
				<?php 
    esc_html_e( 'Deduct points when order is refunded or cancelled', 'simple-points-and-rewards' );
    ?>
			</label>
		</div>
	</div>

	<!-- Points for Orders (Fixed, with Tiers) -->
	<div class="spar-accordion spar-earn-accordion" data-key="order_fixed">
		<div class="spar-accordion-header">
			<span class="spar-drag-handle dashicons dashicons-move" title="<?php 
    esc_attr_e( 'Drag to reorder', 'simple-points-and-rewards' );
    ?>"></span>
			<input type="hidden" name="earn_ways_order[]" value="order_fixed" />
			<label>
				<div class="spar-toggle-switch">
					<input type="checkbox" name="order_fixed_enabled" <?php 
    checked( !empty( $earn_options['order_fixed']['enabled'] ) );
    ?> />
					<span class="spar-toggle-slider"></span>
				</div>
				<span class="spar-earn-type-badge"><i class="fa-solid fa-tags" aria-hidden="true"></i></span>
				<?php 
    esc_html_e( 'Points for Orders', 'simple-points-and-rewards' );
    ?>
			</label>
			<div class="spar-earn-actions">
				<button type="button" class="button spar-toggle-earn"><?php 
    esc_html_e( 'Edit', 'simple-points-and-rewards' );
    ?></button>
			</div>
		</div>
		<div class="spar-accordion-body">
			<p class="spar-mt-0">
				<?php 
    esc_html_e( 'Offer a fixed amount of points for an order when the spend reaches a tier threshold.', 'simple-points-and-rewards' );
    ?>
			</p>
			<p class="spar-mt-0">
				<?php 
    esc_html_e( 'This will sell an upsell to customers to spend more to reach the next tier and earn more points!', 'simple-points-and-rewards' );
    ?>
			</p>
			<?php 
    $store_currency = ( function_exists( 'get_woocommerce_currency' ) ? get_woocommerce_currency() : 'USD' );
    $store_currency_name = ( function_exists( 'get_woocommerce_currencies' ) ? get_woocommerce_currencies()[$store_currency] ?? $store_currency : $store_currency );
    $store_symbol = ( function_exists( 'get_woocommerce_currency_symbol' ) ? get_woocommerce_currency_symbol( $store_currency ) : '$' );
    $all_currencies = ( function_exists( 'get_woocommerce_currencies' ) ? get_woocommerce_currencies() : [] );
    $tiers = ( isset( $earn_options['order_fixed']['tiers'] ) && is_array( $earn_options['order_fixed']['tiers'] ) ? $earn_options['order_fixed']['tiers'] : [] );
    $order_fixed_calc_mode = $earn_options['order_fixed']['calculation_total_mode'] ?? 'subtotal_after_discount';
    $order_fixed_include_shipping = !empty( $earn_options['order_fixed']['calculation_include_shipping'] );
    $order_fixed_include_taxes = !empty( $earn_options['order_fixed']['calculation_include_taxes'] );
    ?>

			<!-- Name of way to earn -->
			<label class="spar-inline-block spar-label-title" style="font-weight: bold; margin-top:8px;">
				<?php 
    esc_html_e( 'Name:', 'simple-points-and-rewards' );
    ?>
			</label>
			<input type="text" name="order_fixed_name" value="<?php 
    echo esc_attr( $earn_options['order_fixed']['name'] ?? '' );
    ?>" placeholder="<?php 
    esc_attr_e( 'Points for Orders', 'simple-points-and-rewards' );
    ?>" />

			<label class="spar-inline-block" style="font-weight: bold; margin-top:8px; margin-bottom:4px;">
				<?php 
    esc_html_e( 'Define Tiers:', 'simple-points-and-rewards' );
    ?>
			</label>
			<div id="spar-order-fixed-tiers">
				<?php 
    if ( empty( $tiers ) ) {
        $tiers = [[
            'points'            => 10,
            'default_threshold' => 0,
            'currencies'        => [],
        ]];
    }
    foreach ( $tiers as $i => $tier ) {
        $points = ( isset( $tier['points'] ) ? (int) $tier['points'] : 10 );
        $default_threshold = ( isset( $tier['default_threshold'] ) ? (float) $tier['default_threshold'] : 0.0 );
        $currs = ( isset( $tier['currencies'] ) && is_array( $tier['currencies'] ) ? $tier['currencies'] : [] );
        ?>
				<div class="spar-order-tier" data-tier-index="<?php 
        echo esc_attr( (int) $i );
        ?>" style="border:1px solid #ddd; padding:10px; margin:10px 0; border-radius:4px;">
					<div class="spar-flex-center-gap8" style="justify-content:space-between; align-items:center; margin-bottom:8px;">
						<strong><?php 
        /* translators: %d: tier index */
        printf( esc_html__( 'Tier %d', 'simple-points-and-rewards' ), (int) $i + 1 );
        ?></strong>
						<?php 
        if ( $i > 0 ) {
            ?>
							<button type="button" class="button button-secondary spar-remove-order-tier">&times;</button>
						<?php 
        }
        ?>
					</div>

					<div class="spar-flex-center-gap8" style="flex-wrap:wrap; gap:8px;">
						<label class="spar-inline-block"><?php 
        esc_html_e( 'Points Awarded:', 'simple-points-and-rewards' );
        ?></label>
						<input class="spar-w-150" type="number" min="1" name="order_fixed_tiers[<?php 
        echo esc_attr( (int) $i );
        ?>][points]" value="<?php 
        echo esc_attr( $points );
        ?>" />
						<label class="spar-inline-block"><?php 
        /* translators: 1: currency name 2: code */
        printf( esc_html__( 'Spend threshold (%1$s %2$s):', 'simple-points-and-rewards' ), esc_html( $store_currency_name ), esc_html( '(' . $store_currency . ')' ) );
        ?></label>
						<input class="spar-w-150" type="number" step="0.01" min="0.01" name="order_fixed_tiers[<?php 
        echo esc_attr( (int) $i );
        ?>][default_threshold]" value="<?php 
        echo esc_attr( $default_threshold );
        ?>" />
					</div>

					<?php 
        ?>
						<button type="button" class="button spar-add-tier-currency" disabled="disabled" style="margin:4px 0 10px 0;"><?php 
        esc_html_e( 'Add New Currency', 'simple-points-and-rewards' );
        ?> (PRO)</button>
					<?php 
        ?>
				</div>
				<?php 
    }
    ?>
			</div>

			<button type="button" class="button button-primary spar-add-order-tier" style="margin-top:6px;">+ <?php 
    esc_html_e( 'Add New Tier', 'simple-points-and-rewards' );
    ?></button>

			<!-- Calculation base -->
			<label class="spar-inline-block" style="margin-top:14px; font-weight: bold;">
				<?php 
    esc_html_e( 'Points calculation uses:', 'simple-points-and-rewards' );
    ?>
			</label>
			<select name="order_fixed_calculation_total_mode">
				<option value="total_before_discounts" <?php 
    selected( $order_fixed_calc_mode, 'total_before_discounts' );
    ?>>
					<?php 
    esc_html_e( 'Total before discounts', 'simple-points-and-rewards' );
    ?>
				</option>
				<option value="subtotal_after_discount" <?php 
    selected( $order_fixed_calc_mode, 'subtotal_after_discount' );
    ?>>
					<?php 
    esc_html_e( 'Subtotal after discount (default)', 'simple-points-and-rewards' );
    ?>
				</option>
			</select>
			<br/>
			<label class="spar-inline-block" style="margin-top:6px;">
				<input type="checkbox" name="order_fixed_calculation_include_shipping" <?php 
    checked( $order_fixed_include_shipping );
    ?> />
				<?php 
    esc_html_e( 'Include shipping in calculation total', 'simple-points-and-rewards' );
    ?>
			</label>
			<label class="spar-inline-block" style="margin-top:6px;">
				<input type="checkbox" name="order_fixed_calculation_include_taxes" <?php 
    checked( $order_fixed_include_taxes );
    ?> />
				<?php 
    esc_html_e( 'Include taxes in calculation total', 'simple-points-and-rewards' );
    ?>
			</label>

			<!-- Deduct points on refund (independent for fixed-orders) -->
			<label class="spar-inline-block" style="margin-top:14px; font-weight: bold;">
				<?php 
    esc_html_e( 'Order Refunds:', 'simple-points-and-rewards' );
    ?></label>
				<input type="checkbox" name="order_fixed_deduct_on_refund" <?php 
    checked( !empty( $earn_options['order_fixed']['deduct_on_refund'] ) );
    ?> />
				<?php 
    esc_html_e( 'Deduct points when order is refunded or cancelled', 'simple-points-and-rewards' );
    ?>
			</label>

			<!-- Templates (use script tags to avoid form submission of placeholders) -->
			<script type="text/template" id="spar-order-tier-template">
				<div class="spar-order-tier" data-tier-index="__TIER_INDEX__" style="border:1px solid #ddd; padding:10px; margin:10px 0; border-radius:4px;">
					<div class="spar-flex-center-gap8" style="justify-content:space-between; align-items:center; margin-bottom:8px;">
						<strong><?php 
    esc_html_e( 'Tier', 'simple-points-and-rewards' );
    ?> __TIER_NUMBER__</strong>
						<button type="button" class="button button-secondary spar-remove-order-tier">&times;</button>
					</div>
					<div class="spar-flex-center-gap8" style="flex-wrap:wrap; gap:8px;">
						<label class="spar-inline-block"><?php 
    esc_html_e( 'Points Awarded:', 'simple-points-and-rewards' );
    ?></label>
						<input class="spar-w-150" type="number" min="1" name="order_fixed_tiers[__TIER_INDEX__][points]" value="10" />
						<label class="spar-inline-block"><?php 
    /* translators: %s: currency code */
    printf( esc_html__( 'Spend threshold (%s):', 'simple-points-and-rewards' ), esc_html( $store_currency ) );
    ?></label>
						<input class="spar-w-150" type="number" step="0.01" min="0.01" name="order_fixed_tiers[__TIER_INDEX__][default_threshold]" value="0" />
					</div>
					<?php 
    ?>
						<button type="button" class="button spar-add-tier-currency" disabled="disabled" style="margin:4px 0 10px 0;"><?php 
    esc_html_e( 'Add New Currency', 'simple-points-and-rewards' );
    ?> (PRO)</button>
					<?php 
    ?>
				</div>
			</script>

			<?php 
    ?>
		</div>
	</div>
	<!-- Referral System -->
	<div class="spar-accordion spar-earn-accordion" data-key="referral">
		<div class="spar-accordion-header">
			<span class="spar-drag-handle dashicons dashicons-move" title="<?php 
    esc_attr_e( 'Drag to reorder', 'simple-points-and-rewards' );
    ?>"></span>
			<input type="hidden" name="earn_ways_order[]" value="referral" />
			<label>
				<div class="spar-toggle-switch">
					<input type="checkbox" name="referral_enabled" <?php 
    checked( !empty( $earn_options['referral']['enabled'] ) );
    ?> />
					<span class="spar-toggle-slider"></span>
				</div>
				<span class="spar-earn-type-badge"><i class="fa-solid fa-user-group" aria-hidden="true"></i></span>
				<?php 
    esc_html_e( 'Referral System', 'simple-points-and-rewards' );
    ?>
			</label>
			<div class="spar-earn-actions">
				<button type="button" class="button spar-toggle-earn"><?php 
    esc_html_e( 'Edit', 'simple-points-and-rewards' );
    ?></button>
			</div>
		</div>
		<div class="spar-accordion-body">
			<p class="spar-mt-0">
				<?php 
    esc_html_e( 'Users earn points when their referred friends make purchases through their referral link.', 'simple-points-and-rewards' );
    ?>
			</p>
			<!-- Name of way to earn -->
			<label class="spar-inline-block spar-label-title"><?php 
    esc_html_e( 'Name:', 'simple-points-and-rewards' );
    ?></label>
			<input type="text" name="referral_name" value="<?php 
    echo esc_attr( $earn_options['referral']['name'] );
    ?>" placeholder="<?php 
    esc_attr_e( 'Referral Bonus', 'simple-points-and-rewards' );
    ?>" />
			<br/>
			<!-- Earning Type -->
			<label class="spar-inline-block spar-label-title"><?php 
    esc_html_e( 'Earning Type:', 'simple-points-and-rewards' );
    ?></label>
			<select name="referral_earning_type" id="referral_earning_type">
				<option value="fixed" <?php 
    selected( $earn_options['referral']['earning_type'] ?? 'fixed', 'fixed' );
    ?>><?php 
    esc_html_e( 'Fixed Amount per Referral', 'simple-points-and-rewards' );
    ?></option>
				<option value="percentage" <?php 
    selected( $earn_options['referral']['earning_type'] ?? 'fixed', 'percentage' );
    ?>><?php 
    esc_html_e( 'Percentage of Order Total', 'simple-points-and-rewards' );
    ?></option>
			</select>
			<br/>
		
			<!-- Fixed Amount Settings -->
			<div id="referral_fixed_settings" class="spar-hidden">
				<label class="spar-inline-block spar-label-title"><?php 
    esc_html_e( 'Fixed points per referral:', 'simple-points-and-rewards' );
    ?></label>
				<input type="number" style="margin: 0;"
				name="referral_fixed_points" value="<?php 
    echo esc_attr( $earn_options['referral']['fixed_points'] ?? 100 );
    ?>" />
				<small><?php 
    esc_html_e( 'Referrer will earn this exact amount of points for each successful referral, regardless of order value.', 'simple-points-and-rewards' );
    ?></small>
			</div>
			
			<div id="referral_percentage_settings" class="spar-hidden">
				<label class="spar-inline-block spar-label-title"><?php 
    esc_html_e( 'Percentage of order total:', 'simple-points-and-rewards' );
    ?></label>
				<input type="number" step="0.1" name="referral_percentage" value="<?php 
    echo esc_attr( $earn_options['referral']['percentage'] );
    ?>" />%
				<br/>
				<label class="spar-inline-block spar-label-title"><?php 
    esc_html_e( 'Points per $1.00 of referral value:', 'simple-points-and-rewards' );
    ?></label>
				<input type="number" step="0.1" name="referral_points_per" value="<?php 
    echo esc_attr( $earn_options['referral']['points_per'] );
    ?>" />
				<small><?php 
    esc_html_e( 'Example: If order is $100, percentage is 10%, and points per $1 is 5, referrer gets floor($10 × 5) = 50 points', 'simple-points-and-rewards' );
    ?></small>
			</div>
			
			<!-- Attribution Model -->
			<label class="spar-inline-block spar-label-title"><?php 
    esc_html_e( 'Attribution Model:', 'simple-points-and-rewards' );
    ?></label>
			<select name="referral_gift_attribution_model" style="margin: 0;">
				<option value="first_click" <?php 
    selected( $earn_options['referral']['gift_attribution_model'] ?? 'first_click', 'first_click' );
    ?>><?php 
    esc_html_e( 'First Click Attribution', 'simple-points-and-rewards' );
    ?></option>
				<option value="last_click" <?php 
    selected( $earn_options['referral']['gift_attribution_model'] ?? 'first_click', 'last_click' );
    ?>><?php 
    esc_html_e( 'Last Click Attribution', 'simple-points-and-rewards' );
    ?></option>
			</select>
			<small><?php 
    esc_html_e( 'First Click: The first referral link clicked gets credit. Last Click: The most recent referral link gets credit.', 'simple-points-and-rewards' );
    ?></small>
			
			<!-- Block Self Referral -->
			<label class="spar-inline-block">
				<input type="checkbox" name="referral_block_self_referral" <?php 
    checked( !empty( $earn_options['referral']['block_self_referral'] ) );
    ?> />
				<?php 
    esc_html_e( 'Block users from using their own referral link', 'simple-points-and-rewards' );
    ?>
			</label>
			<small><?php 
    esc_html_e( 'When enabled, users cannot earn points or receive gift offers by using their own referral links.', 'simple-points-and-rewards' );
    ?></small>

			<!-- When to award referral points -->
			<label class="spar-inline-block"><?php 
    esc_html_e( 'Award referral bonus:', 'simple-points-and-rewards' );
    ?></label>
			<select name="referral_award_timing">
				<option value="completed" <?php 
    selected( $earn_options['referral']['award_timing'] ?? 'completed', 'completed' );
    ?>><?php 
    esc_html_e( 'When order is completed', 'simple-points-and-rewards' );
    ?></option>
				<option value="processing" <?php 
    selected( $earn_options['referral']['award_timing'] ?? 'completed', 'processing' );
    ?>><?php 
    esc_html_e( 'When order is processing', 'simple-points-and-rewards' );
    ?></option>
			</select>
			<br/>
			<!-- Deduct referral points on refund -->
			<label class="spar-inline-block">
				<input type="checkbox" name="referral_deduct_on_refund" <?php 
    checked( !empty( $earn_options['referral']['deduct_on_refund'] ?? true ) );
    ?> />
				<?php 
    esc_html_e( 'Deduct referral points when referred order is refunded', 'simple-points-and-rewards' );
    ?>
			</label>

			<?php 
    // Load referral options with defaults for Social Sharing display controls.
    $defaults = ( function_exists( 'spar_settings_default' ) ? spar_settings_default() : array() );
    $options = get_option( 'spar_options', $defaults );
    $options = ( is_array( $options ) ? array_merge( $defaults, $options ) : $defaults );
    $referral_options = ( isset( $options['earn']['referral'] ) && is_array( $options['earn']['referral'] ) ? $options['earn']['referral'] : array() );
    $social_enabled = ( array_key_exists( 'social_enabled', $referral_options ) ? !empty( $referral_options['social_enabled'] ) : true );
    ?>
			<div class="spar-referral-social-sharing">
				<h4 style="margin-bottom: 5px;"><?php 
    esc_html_e( 'Social Sharing Buttons', 'simple-points-and-rewards' );
    ?></h4>
				<label class="spar-inline-block">
					<div class="spar-toggle-switch"><input type="checkbox" name="referral_social_enabled" value="1" <?php 
    checked( $social_enabled );
    ?> /><span class="spar-toggle-slider"></span></div>
					<?php 
    esc_html_e( 'Show social sharing buttons', 'simple-points-and-rewards' );
    ?>
				</label>
				<div class="spar-social-sharing-options" style="margin-top:10px;display:flex;flex-wrap:wrap;gap:15px;align-items:center;">
					<label style="display:flex;align-items:center;gap:6px;">
						<input type="checkbox" name="referral_social_email_enabled" value="1" <?php 
    checked( ( array_key_exists( 'social_email_enabled', $referral_options ) ? !empty( $referral_options['social_email_enabled'] ) : true ) );
    ?> />
						<span><?php 
    esc_html_e( 'Email', 'simple-points-and-rewards' );
    ?></span>
					</label>
					<label style="display:flex;align-items:center;gap:6px;">
						<input type="checkbox" name="referral_social_facebook_enabled" value="1" <?php 
    checked( ( array_key_exists( 'social_facebook_enabled', $referral_options ) ? !empty( $referral_options['social_facebook_enabled'] ) : true ) );
    ?> />
						<span><?php 
    esc_html_e( 'Facebook', 'simple-points-and-rewards' );
    ?></span>
					</label>
					<label style="display:flex;align-items:center;gap:6px;">
						<input type="checkbox" name="referral_social_twitter_enabled" value="1" <?php 
    checked( ( array_key_exists( 'social_twitter_enabled', $referral_options ) ? !empty( $referral_options['social_twitter_enabled'] ) : true ) );
    ?> />
						<span><?php 
    esc_html_e( 'Twitter / X', 'simple-points-and-rewards' );
    ?></span>
					</label>
					<label style="display:flex;align-items:center;gap:6px;">
						<input type="checkbox" name="referral_social_whatsapp_enabled" value="1" <?php 
    checked( ( array_key_exists( 'social_whatsapp_enabled', $referral_options ) ? !empty( $referral_options['social_whatsapp_enabled'] ) : true ) );
    ?> />
						<span><?php 
    esc_html_e( 'WhatsApp', 'simple-points-and-rewards' );
    ?></span>
					</label>
				</div>
			</div>

			<?php 
    $show_clicks_log = !empty( $referral_options['show_clicks_log'] );
    ?>
			<div class="spar-referral-clicks-log" style="margin-top: 12px;">
				<h4 style="margin-bottom: 5px;"><?php 
    esc_html_e( 'Referral Link Clicks', 'simple-points-and-rewards' );
    ?></h4>
				<label class="spar-inline-block">
					<div class="spar-toggle-switch"><input type="checkbox" name="referral_show_clicks_log" value="1" <?php 
    checked( $show_clicks_log );
    ?> /><span class="spar-toggle-slider"></span></div>
					<?php 
    esc_html_e( 'Show link clicks log on the rewards dashboard and widget', 'simple-points-and-rewards' );
    ?>
				</label>
				<small><?php 
    esc_html_e( 'Displays a paginated table of referral link clicks for each customer.', 'simple-points-and-rewards' );
    ?></small>
			</div>
			
			<!-- Referral Gift Offers Section -->
			<?php 
    ?>
			
			<!-- Gift Widget Navigation -->
			<?php 
    ?>
		</div>
	</div>
		<?php 
    ?>
		<!-- Points for Social Sharing (PRO) -->
		<div class="spar-accordion spar-premium-disabled">
			<div class="spar-accordion-header">
				<label>
					<div class="spar-toggle-switch">
						<input type="checkbox" name="social_sharing_referral_social_points_enabled" disabled="disabled" />
						<span class="spar-toggle-slider"></span>
					</div>
					<?php 
    esc_html_e( 'Points for Social Sharing (PRO)', 'simple-points-and-rewards' );
    ?>
				</label>
			</div>
		</div>
	<?php 
    ?>
	<?php 
    ?>
		<!-- First Order Bonus (Disabled) -->
		<div class="spar-accordion spar-premium-disabled">
			<div class="spar-accordion-header">
				<label>
					<div class="spar-toggle-switch">
						<input type="checkbox" name="first_order_enabled" disabled="disabled" />
						<span class="spar-toggle-slider"></span>
					</div>
					<?php 
    esc_html_e( 'First Order Bonus (PRO)', 'simple-points-and-rewards' );
    ?>
				</label>
			</div>
		</div>

		<!-- Nth Order Bonus (Disabled) -->
		<div class="spar-accordion spar-premium-disabled">
			<div class="spar-accordion-header">
				<label>
					<div class="spar-toggle-switch">
						<input type="checkbox" name="nth_order_enabled" disabled="disabled" />
						<span class="spar-toggle-slider"></span>
					</div>
					<?php 
    esc_html_e( 'Nth Order Bonus (PRO)', 'simple-points-and-rewards' );
    ?>
				</label>
			</div>
		</div>
	<?php 
    ?>

	<?php 
    ?>
	<!-- Write a Review (Disabled) -->
	<div class="spar-accordion spar-premium-disabled">
		<div class="spar-accordion-header">
			<label>
				<div class="spar-toggle-switch">
					<input type="checkbox" name="review_enabled" disabled="disabled" />
					<span class="spar-toggle-slider"></span>
				</div>
				<?php 
    esc_html_e( 'Write a Review (PRO)', 'simple-points-and-rewards' );
    ?>
			</label>
		</div>
	</div>
	<?php 
    ?>

	<?php 
    ?>
	<!-- Points for Birthdays (Disabled) -->
	<div class="spar-accordion spar-premium-disabled">
		<div class="spar-accordion-header">
			<label>
				<div class="spar-toggle-switch">
					<input type="checkbox" name="birthday_enabled" disabled="disabled" />
					<span class="spar-toggle-slider"></span>
				</div>
				<?php 
    esc_html_e( 'Points for Birthdays (PRO)', 'simple-points-and-rewards' );
    ?>
			</label>
		</div>
	</div>
	<?php 
    ?>

	<!-- Daily Login Bonus -->
	<?php 
    ?>
		<div class="spar-accordion spar-premium-disabled">
			<div class="spar-accordion-header">
				<label>
					<div class="spar-toggle-switch">
						<input type="checkbox" name="daily_login_enabled" disabled="disabled" />
						<span class="spar-toggle-slider"></span>
					</div>
					<?php 
    esc_html_e( 'Daily Login Bonus (PRO)', 'simple-points-and-rewards' );
    ?>
				</label>
			</div>
		</div>
	<?php 
    ?>

	<!-- Daily Prize Wheel -->
	<?php 
    ?>
		<div class="spar-accordion spar-premium-disabled">
			<div class="spar-accordion-header">
				<label>
					<div class="spar-toggle-switch">
						<input type="checkbox" name="spin_wheel_enabled" disabled="disabled" />
						<span class="spar-toggle-slider"></span>
					</div>
					<?php 
    esc_html_e( 'Daily Prize Wheel (PRO)', 'simple-points-and-rewards' );
    ?>
				</label>
			</div>
		</div>
	<?php 
    ?>

	<?php 
    // Build saved order for JS to reorder accordions on load.
    $defaults_order = spar_settings_default();
    $options_order = get_option( 'spar_options', $defaults_order );
    $options_order = ( is_array( $options_order ) ? array_merge( $defaults_order, $options_order ) : $defaults_order );
    $default_earn_order = [
        'signup',
        'order',
        'order_fixed',
        'referral',
        'first_order',
        'nth_order',
        'review',
        'birthday',
        'daily_login',
        'spin_wheel'
    ];
    $saved_earn_order = ( isset( $options_order['earn_ways_order'] ) && is_array( $options_order['earn_ways_order'] ) && !empty( $options_order['earn_ways_order'] ) ? $options_order['earn_ways_order'] : $default_earn_order );
    foreach ( $default_earn_order as $way_key ) {
        if ( !in_array( $way_key, $saved_earn_order, true ) ) {
            $saved_earn_order[] = $way_key;
        }
    }
    ?>

	</div><!-- /#spar-earn-accordion-list -->
	<script>window.sparEarnOrder = <?php 
    echo wp_json_encode( array_values( $saved_earn_order ) );
    ?>;</script>

	<?php 
}
