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

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

class DiscountsOfferTab extends FormTab {

	public function getId(): string {
		return 'discount-offer';
	}

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

	public function getDescription(): string {
		return __( 'Offer discount or a chance to skip the renewal.',
				'cancellation-surveys-offers-woocommerce-subscriptions' );
	}

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

	public function render( Offer $offer ) {
		?>
		<script>
			jQuery(document).ready(function ($) {

				if (!document.cancellationOffersAndSurveys) {
					return
				}

				// Delegation for "Is Enabled" toggle
				jQuery(document).on('change', 'input[type=checkbox][id$="_is_enabled"]', function () {
					var $checkbox = jQuery(this);
					var $container = $checkbox.closest('.cancellation-offer-discount-offer-block').find('div[id*="__inner-options"]');

					if ($checkbox.is(':checked')) {
						$container.show();
					} else {
						$container.hide();
					}
				});

				// Trigger initial state
				setTimeout(function () {
					jQuery('input[type=checkbox][id$="_is_enabled"]').trigger('change');
				}, 100);

				// Delegation for offer type
				jQuery(document).on('change', '.discount-offer-offer-type', function () {
					var container = jQuery(this).closest('.cancellation-offer-discount-offer-block');
					if (jQuery(this).val() === 'coupon') {
						container.find('.discount-offer-coupon-code-container').show();
						jQuery(this).siblings('.description').hide();
					} else {
						container.find('.discount-offer-coupon-code-container').hide();
						jQuery(this).siblings('.description').show();
					}
				});

				// Trigger change for existing elements
				jQuery('.discount-offer-offer-type').trigger('change');

				// Accordion functionality
				jQuery(document).on('click', '.cancellation-offer-accordion-header', function () {
					var content = jQuery(this).next('.cancellation-offer-accordion-content');
					content.slideToggle();
					jQuery(this).toggleClass('active');
				});

				// Remove button functionality
				jQuery(document).on('click', '.cancellation-offer-remove-button', function (e) {
					e.stopPropagation();
					if (confirm('Are you sure you want to remove this offer?')) {
						jQuery(this).closest('.cancellation-offer-discount-offer-block').remove();
					}
				});

			});
		</script>
		<style>
			.cancellation-offer-accordion-item {
				border: 1px solid #ccd0d4;
				background: #fff;
				margin-bottom: 10px;
			}

			.cancellation-offer-accordion-header {
				padding: 15px;
				background: #f5f5f5;
				cursor: pointer;
				font-weight: 600;
				display: flex;
				justify-content: space-between;
				align-items: center;
				border-bottom: none;
			}

			.cancellation-offer-accordion-header:hover {
				background: #f1f1f1;
			}

			.cancellation-offer-accordion-header::after {
				content: '\f140';
				/* Dashicon arrow down */
				font-family: dashicons;
			}

			.cancellation-offer-accordion-header.active::after {
				content: '\f142';
				/* Dashicon arrow up */
			}

			.cancellation-offer-accordion-content {
				padding: 20px 15px;
				border-top: 0;
			}

			.cancellation-offer-remove-button {
				margin-left: auto;
				/* Push to right */
				margin-right: 10px;
				color: #a00;
				cursor: pointer;
			}

			.cancellation-offer-remove-button:hover {
				color: #dc3232;
			}
		</style>

		<div id="cancellation-offer-discount-offers-container">
			<div id="cancellation-offer-discount-offer">

				<?php

					if ( ! csows_fs()->can_use_premium_code() ) {
						?>
						<div style="padding: 10px 20px;background: #f5f5f5; margin-bottom: 10px; border: 1px solid #ccc;">

							<p style="font-size: 1.1em">
								<?php esc_html_e( 'Retention offers are available',
										'cancellation-surveys-offers-woocommerce-subscriptions' ); ?>
								<strong><?php esc_html_e( 'only in the premium version',
											'cancellation-surveys-offers-woocommerce-subscriptions' ); ?></strong>.
								<?php esc_html_e( 'Upgrade now to access this feature and start retaining more subscribers.',
										'cancellation-surveys-offers-woocommerce-subscriptions' ); ?>
							</p>
							<p>
								<?php
									$updateLink = csows_upgrade_url();
								?>
								<a href="<?php echo esc_attr( $updateLink ); ?>" target="_blank"
								   class="button button-primary">
									<?php esc_html_e( 'Unlock premium features',
											'cancellation-surveys-offers-woocommerce-subscriptions' ); ?>
								</a>
							</p>
						</div>
						<?php
					}
				?>

				<div>
					<?php

						$this->form->renderHint( __( 'Link a specific coupon code that will be offered to subscribers as a reason to retain their subscription or make an offer to skip the next renewal and keep the subscription. ',
								'cancellation-surveys-offers-woocommerce-subscriptions' ) );

						$this->form->renderHint( __( 'Add multiple offers and match them to different cancellation reasons.',
								'cancellation-surveys-offers-woocommerce-subscriptions' ) );
					?>
					<div style="<?php echo ! csows_fs()->can_use_premium_code() ? 'opacity: 0.6; pointer-events: none;' : ''; ?>">


						<?php
							$discountOffers = $offer->getDiscountOffers();

							if ( empty( $discountOffers ) ) {
								// Initialize with one empty offer if there are no offers.
								$discountOffers = array( DiscountOffer::buildDefault() );
							}

							foreach ( $discountOffers as $index => $discountOffer ) {
								$this->renderOfferBlock( $offer, $discountOffer, $index, $index === 0 );
							}
						?>

						<div style="margin-top: 20px; display: flex; align-items: center; ">
							<button type="submit" name="cancellation_offer_add_new_row" value="1"
									class="button button-secondary">
								<?php esc_html_e( 'Add Another Offer',
										'cancellation-surveys-offers-woocommerce-subscriptions' ); ?>
							</button>
							<span class="description" style="margin-left: 10px;">
							<?php esc_html_e( 'Click to add a new offer row. The page will reload.',
									'cancellation-surveys-offers-woocommerce-subscriptions' ); ?>
						</span>
						</div>
					</div>
				</div>

			</div>
		</div>

		<?php
	}

	private function renderOfferBlock( Offer $offer, DiscountOffer $discountOffer, int $index, bool $isExpanded ) {
		$indexSuffix = '_' . $index;
		$baseName    = "discount_offers[$index]";
		$baseId      = "discount_offers_$index";

		$title = $discountOffer->getTitle() ? $discountOffer->getTitle() : __( 'Offer',
						'cancellation-surveys-offers-woocommerce-subscriptions' ) . ' #' . ( $index + 1 );
		?>
		<div class="cancellation-offer-accordion-item cancellation-offer-discount-offer-block">
			<div class="cancellation-offer-accordion-header <?php echo $isExpanded ? 'active' : ''; ?>">
				<span class="header-title"><?php echo esc_html( $title ); ?></span>
				<?php if ( $index > 0 ): ?>
					<span class="cancellation-offer-remove-button"><?php esc_attr_e( 'Remove',
								'cancellation-surveys-offers-woocommerce-subscriptions' ); ?>
					</span>
				<?php endif; ?>
			</div>
			<div class="cancellation-offer-accordion-content"
				 style="display: <?php echo $isExpanded ? 'block' : 'none'; ?>;">

				<div id="cancellation-offer-discount-offer-tab__is-enabled<?php echo $indexSuffix; ?>">
					<?php
						FormTab::renderInputRow( array(
								'id'      => $baseId . '_is_enabled',
								'name'    => $baseName . '[is_enabled]',
								'type'    => 'checkbox',
								'checked' => $discountOffer->isEnabled(),
								'label'   => __( 'Enable Retention Offer',
										'cancellation-surveys-offers-woocommerce-subscriptions' ),
						) );
					?>
				</div>

				<div id="cancellation-offer-discount-offer-tab__inner-options<?php echo $indexSuffix; ?>">
					<?php
						FormTab::renderInputRow( array(
								'id'    => $baseId . '_title',
								'name'  => $baseName . '[title]',
								'type'  => 'text',
								'value' => $discountOffer->getTitle(),
								'label' => __( 'Title', 'cancellation-surveys-offers-woocommerce-subscriptions' ),
						) );
					?>

					<?php
						FormTab::renderInputRow( array(
								'id'    => $baseId . '_description',
								'name'  => $baseName . '[description]',
								'type'  => 'editor',
								'value' => $discountOffer->getDescription(),
								'label' => __( 'Description', 'cancellation-surveys-offers-woocommerce-subscriptions' ),
						) );
					?>

					<div id="cancellation-offer-discount-offer-tab__survey-option<?php echo $indexSuffix; ?>">
						<div class="cancellation-offers-components-row">
							<div class="cancellation-offers-components-row__label">
								<label for="<?php echo esc_attr( $baseId . '_survey_options' ); ?>">
									<?php
										esc_html_e( 'Cancellation reasons',
												'cancellation-surveys-offers-woocommerce-subscriptions' );
									?>
								</label>
							</div>
							<div class="cancellation-offers-components-row__value">
								<select name="<?php echo esc_attr( $baseName . '[survey_options][]' ); ?>"
										id="<?php echo esc_attr( $baseId . '_survey_options' ); ?>" multiple
										class="cos-select-woo">
									<?php foreach ( $offer->getSurvey()->getItems() as $item ): ?>
										<option value="<?php echo esc_attr( $item->getSlug() ); ?>" <?php
											selected( in_array( $item->getSlug(),
													$discountOffer->getSurveyOptions() ) );
										?>>
											<?php echo esc_html( $item->getTitle() ); ?>
										</option>
									<?php endforeach; ?>
								</select>

								<p class="description" style="color: red; display: none;"
								   id="cancellation-offer-discount-offer-tab__survey-options-notice<?php echo $indexSuffix; ?>">
									<?php
										esc_html_e( 'Please note, if you\'ve changed any survey option (1st step), you must re-save this form to pull updated survey options here.',
												'cancellation-surveys-offers-woocommerce-subscriptions' );
									?>
								</p>

								<p class="description"
								   id="cancellation-offer-discount-offer-tab__survey-options-notice<?php echo $indexSuffix; ?>">
									<?php
										esc_html_e( 'Select which survey answers will trigger a retention offer. Leave blank to offer a discount or skip renewal option for any cancellation reason chosen by the user.',
												'cancellation-surveys-offers-woocommerce-subscriptions' );
									?>
								</p>
							</div>
						</div>
					</div>

					<div>
						<div class="cancellation-offers-components-row">
							<div class="cancellation-offers-components-row__label">
								<label for="<?php echo esc_attr( $baseId . '_offer_type' ); ?>">
									<?php
										esc_html_e( 'Offer type',
												'cancellation-surveys-offers-woocommerce-subscriptions' );
									?>
								</label>
							</div>
							<div class="cancellation-offers-components-row__value">
								<select name="<?php echo esc_attr( $baseName . '[offer_type]' ); ?>"
										id="<?php echo esc_attr( $baseId . '_offer_type' ); ?>"
										class="discount-offer-offer-type"
										style="max-width: 100%">
									<option <?php selected( 'coupon', $discountOffer->getOfferType() ); ?>
											value="coupon">
										<?php
											esc_html_e( 'Coupon discount',
													'cancellation-surveys-offers-woocommerce-subscriptions' );
										?>
									</option>
									<option <?php selected( 'skip_renewal', $discountOffer->getOfferType() ); ?>
											value="skip_renewal">
										<?php
											esc_html_e( 'Skip next renewal',
													'cancellation-surveys-offers-woocommerce-subscriptions' );
										?>
									</option>
								</select>
								<p class="description">
									<?php
										esc_html_e( 'Offer users the chance to skip their next renewal event, rescheduling the renewal date by one subscription period from its original date.',
												'cancellation-surveys-offers-woocommerce-subscriptions' );
									?>
								</p>
							</div>
						</div>
					</div>

					<div id="cancellation-offer-discount-offer-tab__coupon-code<?php echo $indexSuffix; ?>"
						 class="discount-offer-coupon-code-container">
						<?php
							FormTab::renderInputRow( array(
									'id'          => $baseId . '_coupon_id',
									'name'        => $baseName . '[coupon_id]',
									'type'        => 'select2',
									'action'      => LookupService::COUPONS_SEARCH_ACTION,
									'placeholder' => 'Search for a coupon...',
									'description' => function () {
										esc_html_e( 'Visit the Coupons page to create a new coupon if you haven\'t already done so. Make sure to select the \'recurring\' type of coupon.',
												'cancellation-surveys-offers-woocommerce-subscriptions' );

										?>
										<a href="<?php echo esc_attr( admin_url( 'edit.php?post_type=shop_coupon' ) ); ?>"
										   target="_blank">
											<?php
												esc_html_e( 'Create a new coupon',
														'cancellation-surveys-offers-woocommerce-subscriptions' );
											?>
										</a>
										<?php
									},
									'label'       => __( 'Coupon Code',
											'cancellation-surveys-offers-woocommerce-subscriptions' ),
									'options'     => ( function () use ( $discountOffer ) {

										$options = array();
										$coupon  = $discountOffer->getCoupon();

										if ( ! empty( $coupon ) ) {

											$options[ $discountOffer->getCouponId() ] = array(
													'is_selected' => true,
													'label'       => $coupon->get_code(),
											);
										}

										return $options;

									} )(),
							) );
						?>
					</div>
					<hr class="cancellation-offers-components__separator" data-title="
				<?php
						esc_html_e( 'Offer Settings', 'cancellation-surveys-offers-woocommerce-subscriptions' );
					?>
				">
					<?php
						$this->form->renderHint( __( 'These settings apply only for current retention offer to help target the offers to more committed subscribers and prevent any fraudulent activity.',
								'cancellation-surveys-offers-woocommerce-subscriptions' ) );

						FormTab::renderInputRow( array(
								'id'          => $baseId . '_minimum_renewals_count',
								'name'        => $baseName . '[minimum_renewals_count]',
								'type'        => 'number',
								'value'       => $discountOffer->getMinimumRenewalsCount(),
								'label'       => __( 'Minimum renewals number',
										'cancellation-surveys-offers-woocommerce-subscriptions' ),
								'placeholder' => __( 'Leave empty to don\'t make any renewals number restrictions',
										'cancellation-surveys-offers-woocommerce-subscriptions' ),
								'description' => __( 'Don\'t make a retention offer if the user\'s number of subscription renewals is below the minimum required threshold.',
										'cancellation-surveys-offers-woocommerce-subscriptions' ),
						) );

						FormTab::renderInputRow( array(
								'id'          => $baseId . '_minimum_subscription_days_active',
								'name'        => $baseName . '[minimum_subscription_days_active]',
								'type'        => 'number',
								'value'       => $discountOffer->getMinimumSubscriptionDaysActive(),
								'label'       => __( 'Minimum subscription days active',
										'cancellation-surveys-offers-woocommerce-subscriptions' ),
								'placeholder' => __( 'Leave empty to don\'t make any restrictions by date.',
										'cancellation-surveys-offers-woocommerce-subscriptions' ),
								'description' => __( 'Don\'t make a retention offer to users whose subscriptions were created less than the specified number of days.',
										'cancellation-surveys-offers-woocommerce-subscriptions' ),
						) );

						FormTab::renderInputRow( array(
								'id'          => $baseId . '_allow_offer_multiple_times',
								'name'        => $baseName . '[allow_offer_multiple_times]',
								'type'        => 'checkbox',
								'checked'     => $discountOffer->isAllowOfferMultipleTimes(),
								'label'       => __( 'Allow offer be applied multiple times',
										'cancellation-surveys-offers-woocommerce-subscriptions' ),
								'description' => __( 'The retention offer will be valid again after the initial discount was expired.',
										'cancellation-surveys-offers-woocommerce-subscriptions' ),
						) );

						FormTab::renderInputRow( array(
								'id'          => $baseId . '_allow_trials',
								'name'        => $baseName . '[allow_trials]',
								'type'        => 'checkbox',
								'checked'     => $discountOffer->isAllowTrials(),
								'label'       => __( 'Allow offer for trial subscriptions',
										'cancellation-surveys-offers-woocommerce-subscriptions' ),
								'description' => __( 'The retention offer will not be available during the trial period.',
										'cancellation-surveys-offers-woocommerce-subscriptions' ),
						) );
					?>

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

					<?php
						FormTab::renderInputRow( array(
								'id'    => $baseId . '_apply_discount_button_label',
								'name'  => $baseName . '[apply_discount_button_label]',
								'type'  => 'text',
								'value' => $discountOffer->getApplyDiscountButtonLabel(),
								'label' => __( 'Accept offer button label',
										'cancellation-surveys-offers-woocommerce-subscriptions' ),
						) );
					?>
					<?php
						FormTab::renderInputRow( array(
								'id'    => $baseId . '_cancel_subscription_button_label',
								'name'  => $baseName . '[cancel_subscription_button_label]',
								'type'  => 'text',
								'value' => $discountOffer->getCancelSubscriptionButtonLabel(),
								'label' => __( 'Cancel subscription button label',
										'cancellation-surveys-offers-woocommerce-subscriptions' ),
						) );
					?>
				</div>
			</div>
		</div>
		<?php
	}
}