<?php namespace MeowCrew\CancellationOffers\Offer\CPT\Form\Tabs;

use MeowCrew\CancellationOffers\Offer\CPT\Form\FormTab;
use MeowCrew\CancellationOffers\Offer\Entity\Offer;

class SurveyTab extends FormTab {

	public function getId(): string {
		return 'survey';
	}

	public function getTitle(): string {
		return __( 'Survey', 'cancellation-surveys-offers-woocommerce-subscriptions' );
	}

	public function getDescription(): string {
		return __( 'Define cancellation reasons.', 'cancellation-surveys-offers-woocommerce-subscriptions' );
	}

	public function getIcon(): string {
		return '<span class="dashicons dashicons-testimonial"></span>';
	}

	public function render( Offer $offer ) {
		$this->form->renderHint( __( 'Customize the survey by adding various reasons that customers might choose when canceling their subscription.',
				'cancellation-surveys-offers-woocommerce-subscriptions' ) );
		?>
		<script>

			const SurveyOptionsBlock = function ($tab) {

				this.$tab = $tab;

				this.init = function () {

					this.$wrapper = this.$tab.find('#cancellation-offers-survey__survey-options');
					this.$addNewButton = this.$wrapper.find('#cancellation-offers-survey__survey-add-new');

					// Handle adding new survey option
					this.$addNewButton.on('click', (function (event) {
						event.preventDefault();
						this.$wrapper.find('.cancellation-offers-survey__survey-items').append(this.generateNewOption());
						this.recalculateSurveyItemsIndexes();
					}).bind(this));

					// Show notice in the offer discount tab that the offer must be saved to pull the updated options when there are any interaction with this block.
					this.$wrapper.on('click', function () {
						jQuery('#cancellation-offer-discount-offer-tab__survey-options-notice').show();
					})

					// Handle remove survey option
					jQuery(document).on('click', '.cancellation-offers-survey__survey-item__actions--remove', (function (event) {
						event.preventDefault();

						if (this.getOptionsCount() < 3) {
							alert('Minimum options for the survey is 2');
							return;
						}

						jQuery(event.target).closest('.cancellation-offers-survey__survey-item').remove();

						this.recalculateSurveyItemsIndexes();
					}).bind(this));
				}

				this.getOptionsCount = function () {
					return this.$wrapper.find('.cancellation-offers-survey__survey-items > .cancellation-offers-survey__survey-item').length;
				}

				this.generateNewOption = function () {
					const option = this.$wrapper.find('.cancellation-offers-survey__survey-item').last().clone();
					option.find('input[type=text]').val('');
					option.find('input[type=checkbox]').prop('checked', false);

					return option;
				}

				this.recalculateSurveyItemsIndexes = function () {

					jQuery.each(jQuery(this.$tab.find('input[name^="survey_options[text_answer_enabled]"')), function (index, el) {
						const currentName = jQuery(el).attr('name');

						const newName = currentName.replace(/\[\d*\]$/, '[' + index + ']');

						jQuery(el).attr('name', newName);
					});
				}
			}

			jQuery(document).ready(function ($) {

				if (!document.cancellationOffersAndSurveys) {
					return
				}

				document.cancellationOffersAndSurveys.bindCheckboxContentShowHideEvent($('#cancellation-offer-survey-tab__is-enabled').find('input[type=checkbox]'), $('#cancellation-offers-survey__inner-options'));
				document.cancellationOffersAndSurveys.bindCheckboxContentShowHideEvent($('#cancellation-offers-survey__other-survey-option-is-enabled').find('input[type=checkbox]'), $('#cancellation-offers-survey__other-survey-option-inner-options'));

				const surveyOptionsBlock = new SurveyOptionsBlock($('#cancellation-offer-survey-tab'), $);
				surveyOptionsBlock.init();
			});
		</script>

		<style>
			.cancellation-offers-survey__survey-item {
				padding: 10px;
				background: #f5f5f5;
				margin-bottom: 15px;
				border-radius: 3px;
				border: 1px solid #ccc;
			}

			.cancellation-offers-survey__survey-item__main {
				display: flex;
				justify-content: space-between;
				align-items: center;
				gap: 10px;
				margin-bottom: 10px;
			}

			.cancellation-offers-survey__survey-item__options-text-answer {
				display: flex;
				align-items: center;
				gap: 5px;
			}

			.cancellation-offers-survey__survey-item__title {
				width: 100%;
			}

			.cancellation-offer-survey-item__title input {
				width: 100% !important;
			}
		</style>

		<div id="cancellation-offer-survey-tab">

			<div id="cancellation-offer-survey-tab__is-enabled">
				<?php
					FormTab::renderInputRow( array(
							'id'      => 'survey_is_enabled',
							'type'    => 'checkbox',
							'checked' => $offer->getSurvey()->isEnabled(),
							'label'   => __( 'Enable Survey', 'cancellation-surveys-offers-woocommerce-subscriptions' ),
					) );
				?>
			</div>

			<div id="cancellation-offers-survey__inner-options">

				<?php
					FormTab::renderInputRow( array(
							'id'    => 'survey_title',
							'label' => __( 'Survey Title', 'cancellation-surveys-offers-woocommerce-subscriptions' ),
							'value' => $offer->getSurvey()->getTitle(),
					) );

					FormTab::renderInputRow( array(
							'id'    => 'survey_description',
							'type'  => 'editor',
							'label' => __( 'Survey Description',
									'cancellation-surveys-offers-woocommerce-subscriptions' ),
							'value' => $offer->getSurvey()->getDescription(),
					) );
				?>

				<hr class="cancellation-offers-components__separator" data-title="
				<?php
					esc_html_e( 'Cancellation Reasons', 'cancellation-surveys-offers-woocommerce-subscriptions' );
				?>
					">

				<div id="cancellation-offers-survey__survey-options" style="margin-top: 20px">
					<div class="cancellation-offers-components-row">
						<div class="cancellation-offers-components-row__label">
							<?php esc_html_e( 'Cancellation reasons',
									'cancellation-surveys-offers-woocommerce-subscriptions' ); ?>
						</div>
						<div class="cancellation-offers-components-row__value">

							<div class="cancellation-offers-survey__survey-items">

								<?php if ( ! empty( $offer->getSurvey()->getItems() ) ): $iterator = 0; ?>

									<?php foreach ( $offer->getSurvey()->getItems() as $item ) : ?>
										<div class="cancellation-offers-survey__survey-item">
											<div class="cancellation-offers-survey__survey-item__main">
												<div class="cancellation-offers-survey__survey-item__title">
													<input type="text" required
														   value="<?php echo esc_attr( $item->getTitle() ); ?>"
														   name="survey_options[title][]">
													<input type="hidden"
														   value="<?php echo esc_attr( $item->getSlug() ); ?>"
														   name="survey_options[slug][]">
												</div>
												<div class="cancellation-offers-survey__survey-item__actions">
													<button type="button"
															title="Remove survey item"
															class="notice-dismiss cancellation-offers-survey__survey-item__actions--remove cancellation-offers-components__dismiss-button">
													</button>
												</div>
											</div>

											<div class="cancellation-offers-survey__survey-item__options">
												<div class="cancellation-offers-survey__survey-item__options-text-answer">
													<label><input
																value="yes"
																type="checkbox" <?php echo checked( $item->isTextAnswerEnabled() ); ?>
																name="survey_options[text_answer_enabled][<?php echo esc_attr( $iterator ); ?>]">
														<?php esc_html_e( 'Ask for details in the text field',
																'cancellation-surveys-offers-woocommerce-subscriptions' ); ?>
													</label>
												</div>
											</div>
										</div>
										<?php $iterator ++; ?>
									<?php endforeach; ?>

								<?php else: ?>
									<div class="cancellation-offers-survey__survey-item">
										<div class="cancellation-offers-survey__survey-item__main">
											<div class="cancellation-offers-survey__survey-item__title">
												<input type="text" required name="survey_options[title][]">
												<input type="hidden" name="survey_options[slug][]">
											</div>
											<div class="cancellation-offers-survey__survey-item__actions">
												<button type="button"
														title="Remove survey item"
														class="notice-dismiss cancellation-offers-survey__survey-item__actions--remove cancellation-offers-components__dismiss-button">
												</button>
											</div>
										</div>

										<div class="cancellation-offers-survey__survey-item__options">
											<div class="cancellation-offers-survey__survey-item__options-text-answer">
												<label><input value="yes"
															  type="checkbox"
															  name="survey_options[text_answer_enabled][0]">
													<?php esc_html_e( 'Ask for details in the text field',
															'cancellation-surveys-offers-woocommerce-subscriptions' ); ?>
												</label>
											</div>
										</div>
									</div>
								<?php endif; ?>

							</div>

							<button type="button" class="button" id="cancellation-offers-survey__survey-add-new">
								<?php esc_html_e( 'Add cancellation reason',
										'cancellation-surveys-offers-woocommerce-subscriptions' ); ?>
							</button>
						</div>
					</div>
				</div>
			</div>

		</div>
		<?php
	}
}
