<?php
/**
 * Applied Discount Widget - Render Functions
 *
 * @package GGM_Commerce
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Render the applied discount widget premium content.
 *
 * @param \GGM_Commerce_Widget_Applied_Discount $widget The widget instance.
 */
function ggmc_applied_discount_render_premium_content( $widget ) {
	$settings = $widget->get_settings_for_display();

	// Check if Discounts class is available.
	if ( ! class_exists( 'GGM_Commerce_Discounts' ) ) {
		return;
	}

	$discounts_handler = GGM_Commerce_Discounts::get_instance();
	$applied_discount  = $discounts_handler->get_applied_discount();

	// If no discount applied.
	if ( ! $applied_discount ) {
		if ( ! empty( $settings['empty_message'] ) ) {
			echo '<div class="ggmc-applied-discount-wrapper ggmc-no-discount">';
			echo '<span class="ggmc-discount-empty">' . esc_html( $settings['empty_message'] ) . '</span>';
			echo '</div>';
		}
		return;
	}

	// Get cart totals for discount amount.
	$discount_amount = 0;
	if ( class_exists( 'GGM_Commerce_Cart' ) ) {
		$cart            = GGM_Commerce_Cart::get_instance();
		$totals          = $cart->get_cart_totals_with_shipping();
		$discount_amount = $totals['discount_amount'] ?? 0;
	}

	$nonce = wp_create_nonce( 'ggmc_discount_nonce' );
	?>
	<div class="ggmc-applied-discount-wrapper" data-nonce="<?php echo esc_attr( $nonce ); ?>">
		<div class="ggmc-applied-discount-row">
			<?php if ( ! empty( $settings['discount_label'] ) ) : ?>
				<span class="ggmc-discount-label"><?php echo esc_html( $settings['discount_label'] ); ?></span>
			<?php endif; ?>

			<?php if ( 'yes' === $settings['show_code'] ) : ?>
				<span class="ggmc-discount-code-badge"><?php echo esc_html( $applied_discount->code ); ?></span>
			<?php endif; ?>

			<?php if ( 'yes' === $settings['show_amount'] && $discount_amount > 0 ) : ?>
				<span class="ggmc-discount-amount">
					-<?php echo esc_html( GGM_Commerce_Helpers::format_price( $discount_amount ) ); ?>
				</span>
			<?php endif; ?>

			<?php if ( 'yes' === $settings['show_remove_button'] ) : ?>
				<button type="button" class="ggmc-discount-remove-link" title="<?php esc_attr_e( 'Remove discount', 'ggm-commerce' ); ?>">
					<?php esc_html_e( 'Remove', 'ggm-commerce' ); ?>
				</button>
			<?php endif; ?>
		</div>
	</div>

	<?php // Styles moved to widgets.css (structural) and professional-defaults.css (design). ?>

	<script>
	(function($) {
		$(document).ready(function() {
			var $wrapper = $('.ggmc-applied-discount-wrapper');

			$wrapper.find('.ggmc-discount-remove-link').on('click', function() {
				var nonce = $wrapper.data('nonce');

				$.post(ggm_commerce_ajax.ajax_url, {
					action: 'ggmc_remove_discount',
					nonce: nonce
				}, function(response) {
					if (response.success) {
						location.reload();
					}
				});
			});
		});
	})(jQuery);
	</script>
	<?php
}
