<?php
/**
 * Review Form Widget - Render Methods
 *
 * @package GGM_Commerce
 */

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

/**
 * Render the premium review form widget content.
 *
 * @param \GGM_Commerce_Widget_Review_Form $widget The widget instance.
 */
function ggmc_review_form_render_premium_content( $widget ) {
	$settings = $widget->get_settings_for_display();

	// Get product ID
	$product_id = GGM_Commerce_Helpers::get_current_product_id();

	// Check if we're in the Elementor editor
	$is_editor = ggmc_is_editor_mode();

	if ( ! $product_id && ! $is_editor ) {
		return;
	}

	// Check login requirement
	$require_login = $settings['require_login'] === 'yes';
	$is_logged_in  = is_user_logged_in();

	// Get current user data if logged in
	$current_user = wp_get_current_user();
	$user_name    = $is_logged_in ? $current_user->display_name : '';
	$user_email   = $is_logged_in ? $current_user->user_email : '';

	// Check if user has already reviewed this product
	$has_reviewed = false;
	if ( $product_id && class_exists( 'GGM_Commerce_Reviews' ) ) {
		if ( $is_logged_in ) {
			$has_reviewed = GGM_Commerce_Reviews::has_reviewed( $product_id, $user_email );
		}
	}

	$title_tag = $settings['title_html_tag'] ?? 'h3';
	?>
	<div class="ggmc-review-form-wrapper">
		<?php if ( $settings['form_title'] ) : ?>
			<<?php echo esc_attr( $title_tag ); ?> class="ggmc-review-form-title"><?php echo esc_html( $settings['form_title'] ); ?></<?php echo esc_attr( $title_tag ); ?>>
		<?php endif; ?>

		<?php if ( $has_reviewed && ! $is_editor ) : ?>
			<div class="ggmc-review-notice">
				<p>You have already submitted a review for this product.</p>
			</div>
		<?php elseif ( $require_login && ! $is_logged_in && ! $is_editor ) : ?>
			<div class="ggmc-review-login-message">
				<p><?php echo esc_html( $settings['login_message'] ); ?></p>
				<a href="<?php echo esc_url( wp_login_url( get_permalink() ) ); ?>" class="ggmc-login-link">Log In</a>
			</div>
		<?php else : ?>
			<div class="ggmc-review-messages" style="display: none;">
				<div class="ggmc-review-success" style="display: none;">
					<?php echo esc_html( $settings['success_message'] ); ?>
				</div>
				<div class="ggmc-review-error" style="display: none;"></div>
			</div>

			<form class="ggmc-review-form" id="ggmc-review-form-<?php echo esc_attr( $widget->get_id() ); ?>">
				<input type="hidden" name="product_id" value="<?php echo esc_attr( $product_id ?: 0 ); ?>">
				<input type="hidden" name="action" value="ggmc_submit_review">
				<input type="hidden" name="nonce" value="<?php echo esc_attr( wp_create_nonce( 'ggmc_submit_review' ) ); ?>">

				<!-- Star Rating -->
				<div class="ggmc-form-field ggmc-rating-field">
					<label><?php echo esc_html( $settings['rating_label'] ); ?> <span class="required">*</span></label>
					<div class="ggmc-star-rating-input" data-rating="0">
						<?php for ( $i = 1; $i <= 5; $i++ ) : ?>
							<span class="star" data-value="<?php echo esc_attr( $i ); ?>">&#9733;</span>
						<?php endfor; ?>
						<input type="hidden" name="rating" value="" required>
					</div>
					<span class="ggmc-rating-text"></span>
				</div>

				<?php if ( $settings['show_title_field'] === 'yes' ) : ?>
				<!-- Review Title -->
				<div class="ggmc-form-field">
					<label for="review-title-<?php echo esc_attr( $widget->get_id() ); ?>">
						<?php echo esc_html( $settings['title_label'] ); ?>
					</label>
					<input type="text"
					       id="review-title-<?php echo esc_attr( $widget->get_id() ); ?>"
					       name="title"
					       placeholder="Summarize your review">
				</div>
				<?php endif; ?>

				<!-- Review Content -->
				<div class="ggmc-form-field">
					<label for="review-content-<?php echo esc_attr( $widget->get_id() ); ?>">
						<?php echo esc_html( $settings['content_label'] ); ?> <span class="required">*</span>
					</label>
					<textarea id="review-content-<?php echo esc_attr( $widget->get_id() ); ?>"
					          name="content"
					          rows="5"
					          placeholder="What did you like or dislike about this product?"
					          required></textarea>
				</div>

				<?php if ( ! $is_logged_in || $is_editor ) : ?>
				<!-- Name Field -->
				<div class="ggmc-form-field">
					<label for="review-name-<?php echo esc_attr( $widget->get_id() ); ?>">
						<?php echo esc_html( $settings['name_label'] ); ?> <span class="required">*</span>
					</label>
					<input type="text"
					       id="review-name-<?php echo esc_attr( $widget->get_id() ); ?>"
					       name="author_name"
					       value="<?php echo esc_attr( $user_name ); ?>"
					       required>
				</div>

				<!-- Email Field -->
				<div class="ggmc-form-field">
					<label for="review-email-<?php echo esc_attr( $widget->get_id() ); ?>">
						<?php echo esc_html( $settings['email_label'] ); ?> <span class="required">*</span>
					</label>
					<input type="email"
					       id="review-email-<?php echo esc_attr( $widget->get_id() ); ?>"
					       name="author_email"
					       value="<?php echo esc_attr( $user_email ); ?>"
					       required>
				</div>
				<?php else : ?>
				<input type="hidden" name="author_name" value="<?php echo esc_attr( $user_name ); ?>">
				<input type="hidden" name="author_email" value="<?php echo esc_attr( $user_email ); ?>">
				<?php endif; ?>

				<!-- Submit Button -->
				<div class="ggmc-form-field ggmc-submit-field">
					<button type="submit" class="ggmc-submit-review-btn">
						<span class="button-text"><?php echo esc_html( $settings['submit_button_text'] ); ?></span>
						<span class="button-loading" style="display: none;">Submitting...</span>
					</button>
				</div>
			</form>
		<?php endif; ?>
	</div>

	<script>
	(function($) {
		$(document).ready(function() {
			var $form = $('#ggmc-review-form-<?php echo esc_attr( $widget->get_id() ); ?>');
			var $wrapper = $form.closest('.ggmc-review-form-wrapper');
			var $messages = $wrapper.find('.ggmc-review-messages');
			var $success = $wrapper.find('.ggmc-review-success');
			var $error = $wrapper.find('.ggmc-review-error');

			// Star rating interaction
			$form.find('.ggmc-star-rating-input .star').on('mouseenter', function() {
				var value = $(this).data('value');
				$(this).parent().find('.star').each(function() {
					$(this).toggleClass('hover', $(this).data('value') <= value);
				});
			}).on('mouseleave', function() {
				$(this).parent().find('.star').removeClass('hover');
			}).on('click', function() {
				var value = $(this).data('value');
				var $container = $(this).parent();

				$container.attr('data-rating', value);
				$container.find('input[name="rating"]').val(value);

				$container.find('.star').each(function() {
					$(this).toggleClass('active', $(this).data('value') <= value);
				});

				// Show rating text
				var ratingText = ['', 'Poor', 'Fair', 'Good', 'Very Good', 'Excellent'];
				$wrapper.find('.ggmc-rating-text').text(ratingText[value]);
			});

			// Form submission
			$form.on('submit', function(e) {
				e.preventDefault();

				var $btn = $form.find('.ggmc-submit-review-btn');
				var $btnText = $btn.find('.button-text');
				var $btnLoading = $btn.find('.button-loading');

				// Validate rating
				var rating = $form.find('input[name="rating"]').val();
				if (!rating || rating < 1) {
					$error.text('Please select a rating').show();
					$messages.show();
					return;
				}

				// Disable button
				$btn.prop('disabled', true);
				$btnText.hide();
				$btnLoading.show();

				// Hide previous messages
				$success.hide();
				$error.hide();

				// Submit via AJAX
				$.ajax({
					url: '<?php echo esc_url( admin_url( 'admin-ajax.php' ) ); ?>',
					type: 'POST',
					data: $form.serialize(),
					success: function(response) {
						if (response.success) {
							$success.show();
							$messages.show();
							$form.hide();
						} else {
							var errorMsg = 'An error occurred. Please try again.';
							if (response.data && response.data.message) {
								errorMsg = response.data.message;
							} else if (typeof response.data === 'string') {
								errorMsg = response.data;
							}
							$error.text(errorMsg).show();
							$messages.show();
						}
					},
					error: function() {
						$error.text('An error occurred. Please try again.').show();
						$messages.show();
					},
					complete: function() {
						$btn.prop('disabled', false);
						$btnText.show();
						$btnLoading.hide();
					}
				});
			});
		});
	})(jQuery);
	</script>
	<?php
}
