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

use MeowCrew\CancellationOffers\Frontend\OfferPopup\OfferPopup;
use MeowCrew\CancellationOffers\Offer\CPT\CancellationOffersCPT;
use MeowCrew\CancellationOffers\Offer\CPT\Form\Metaboxes\RetentionRateMetabox;
use MeowCrew\CancellationOffers\Offer\CPT\Form\Metaboxes\SurveyAnswersMetabox;
use MeowCrew\CancellationOffers\Offer\CPT\Form\Tabs\DiscountsOfferTab;
use MeowCrew\CancellationOffers\Core\ServiceContainerTrait;
use MeowCrew\CancellationOffers\Offer\CPT\Form\Tabs\LimitationsTab;
use MeowCrew\CancellationOffers\Offer\CPT\Form\Tabs\SurveyTab;
use MeowCrew\CancellationOffers\Offer\CPT\Form\Tabs\DesignTab;
use MeowCrew\CancellationOffers\Offer\Entity\Offer;
use WP_Post;

class Form {

	use ServiceContainerTrait;

	/**
	 * Tabs
	 *
	 * @var FormTab[]
	 */
	protected $tabs;

	protected $defaultTab = 'survey';

	public $offerInstance = null;

	public function __construct() {
		new LookupService();

		add_action( 'init', function () {
			$this->tabs = apply_filters( 'cancellation_offers/global_pricing/form_tabs', array(
					new SurveyTab( $this ),
					new DiscountsOfferTab( $this ),
					new LimitationsTab( $this ),
					new DesignTab( $this ),
			) );
		} );

		add_action( 'add_meta_boxes', function ( $postType ) {
			if ( CancellationOffersCPT::SLUG !== $postType ) {
				return;
			}

			new RetentionRateMetabox( $this->getOfferInstance( get_post() ) );
			new SurveyAnswersMetabox( $this->getOfferInstance( get_post() ) );
		}, 10, 2 );

		add_action( 'edit_form_after_title', function ( WP_Post $post ) {
			if ( CancellationOffersCPT::SLUG !== $post->post_type ) {
				return;
			}

			$this->render( $post );
		} );

		add_action( 'submitpost_box', array( $this, 'renderPreviewButton' ) );
	}

	public function renderPreviewButton( WP_Post $post ) {

		if ( $this->isNewRule() ) {
			return;
		}

		if ( CancellationOffersCPT::SLUG !== $post->post_type ) {
			return;
		}

		$offer = $this->getOfferInstance( $post );

		?>
		<div style="margin-bottom: 25px;">
			<a target="_blank" href="<?php echo esc_attr( OfferPopup::getPreviewURL( $offer->getId() ) ); ?>"
			   class="button button-primary"
			   style="width: 100%; text-align:center; line-height: 32px; height: 37px">
				<?php esc_html_e( 'Preview', 'cancellation-surveys-offers-woocommerce-subscriptions' ); ?>
				<svg style="
							width: 0.8rem;
							height: 0.8rem;
							stroke: currentColor;
							fill: none;" xmlns='http://www.w3.org/2000/svg' stroke-width='10' stroke-dashoffset='0'
					 stroke-dasharray='0'
					 stroke-linecap='round' stroke-linejoin='round' viewBox='0 0 100 100'>
					<polyline fill="none" points="40 20 20 20 20 90 80 90 80 60"/>
					<polyline fill="none" points="60 10 90 10 90 40"/>
					<line fill="none" x1="89" y1="11" x2="50" y2="50"/>
				</svg>
			</a>
		</div>
		<?php

	}

	protected function includeAssets() {
		?>
		<style>
			/**
							* Externals
							 */
			/* do not display any notices on rule creation */
			.wrap .notice:not(.notice-success) {
				display: none
			}

			.cos-offer-and-survey-form .woocommerce-help-tip {
				margin-left: 5px;
			}

			/* tab hint */
			.cos-offer-and-survey-hint {
				display: flex;
				align-items: center;
				padding: 10px;
				border: 1px solid #e8e8e8;
				background: #faf6f9;
				color: #2271b1 !important;
				margin-bottom: 20px;
			}

			.cos-offer-and-survey-hint--top-level {
				margin-top: 10px;
			}

			.cos-offer-and-survey-hint__icon {
				margin-right: 10px;
			}

			.cos-offer-and-survey-form {
				margin: 20px 0;
				display: flex;
				overflow: hidden;
				border-radius: 3px;
				flex-wrap: nowrap;
			}

			.cos-offer-and-survey-form__tabs {
				width: 30%;
				max-width: 300px;
				min-width: 250px;
			}

			.cos-offer-and-survey-form-tab {
				background: #fff;
				border-bottom: 1px solid #e8e8e8;
				border-left: 1px solid #e8e8e8;
				overflow: hidden;
				cursor: pointer;
				display: flex;
				align-items: center;
				padding: 15px 10px;
			}

			.cos-offer-and-survey-form-tab:first-child {
				border-top: 1px solid #e8e8e8;
			}

			.cos-offer-and-survey-form-tab:hover:not(.cos-offer-and-survey-form-tab--active) {
				background: #fbfbfb;
			}

			.cos-offer-and-survey-form-tab--active {
				cursor: default;
				background: #faf6f9;
			}

			.cos-offer-and-survey-form-tab__icon {
				transition: all .1s;
				margin: 10px 15px 10px 10px;
			}

			.cos-offer-and-survey-form-tab__icon span {
				display: inline;
				font-size: 25px;
			}

			.cos-offer-and-survey-form-tab--active h3,
			.cos-offer-and-survey-form-tab--active div {
				color: #2271b1 !important;
			}

			.cos-offer-and-survey-form-tab__title h3 {
				font-size: 1.1em;
				margin: 0;
			}

			.cos-offer-and-survey-form-tab__title div {
				margin-top: 5px;
				color: #777;
			}

			.cos-offer-and-survey-form-tab-content {
				display: none;
			}

			.cos-offer-and-survey-form-tab-content--active {
				display: block;
			}

			.cos-offer-and-survey-form__content {
				width: 70%;
				background: #fff;
				flex-grow: 1;
				padding: 15px;
				border: 1px solid #e8e8e8;
				box-shadow: 0 0 8px rgba(0, 0, 0, .1);
			}
		</style>
		<script>
			jQuery(document).ready(function () {
				let tabs = jQuery('.cos-offer-and-survey-form-tab');
				let tabsContent = jQuery('.cos-offer-and-survey-form-tab-content');

				tabs.click(function (e) {
					e.preventDefault();

					tabsContent.removeClass('cos-offer-and-survey-form-tab-content--active');
					tabs.removeClass('cos-offer-and-survey-form-tab--active');

					jQuery(this).addClass('cos-offer-and-survey-form-tab--active');

					const target = jQuery(this).data('target');

					jQuery('#' + target).addClass('cos-offer-and-survey-form-tab-content--active');
				});
			});
		</script>
		<?php
	}

	protected function renderLicenseStatusBanner() {
		?>
		<div class="cos-offer-and-survey-freemius-block">

			<div style="display: flex;">

				<?php if ( csows_fs()->can_use_premium_code() ): ?>
					<div class="cos-offer-and-survey-freemius-block__icon">
						🎉
					</div>
				<?php endif; ?>

				<div class="cos-offer-and-survey-freemius-block__title">
					<?php
						if ( csows_fs()->can_use_premium_code() ) {
							esc_html_e( 'You use the premium version of the plugin.',
									'cancellation-surveys-offers-for-woo-subscriptions' );
						} else {
							esc_html_e( 'You use the free version of the plugin.',
									'cancellation-surveys-offers-for-woo-subscriptions' );
						}
					?>
				</div>
			</div>

			<div class="cos-offer-and-survey-freemius-block__buttons">
				<?php
					if ( csows_fs()->can_use_premium_code() ) {
						?>
						<a href="<?php echo esc_attr( csows_account_url() ); ?>" target="_blank"
						   class="button button-primary">
							<?php esc_html_e( 'Account', 'cancellation-surveys-offers-for-woo-subscriptions' ); ?>
						</a>
						<?php
					} else {
						?>
						<a href="<?php echo esc_attr( csows_upgrade_url() ) ?>"
						   class="button button-primary cos-offer-and-survey-freemius-block__upgrade-button">
							<?php esc_html_e( 'Upgrade', 'cancellation-surveys-offers-for-woo-subscriptions' ); ?>
						</a>
						<?php
					}
				?>

				<a href="<?php echo esc_attr( csows_contact_us_url() ); ?>" class="button" target="_blank">
					<?php esc_html_e( 'Contact us', 'cancellation-surveys-offers-for-woo-subscriptions' ); ?>
				</a>
			</div>
		</div>
		<?php
	}

	protected function render( WP_Post $post ) {
		$this->includeAssets();

		$offerInstance = $this->getOfferInstance( $post );

		$rulesCount = (int) wp_count_posts( CancellationOffersCPT::SLUG )->publish;

		if ( $this->isNewRule() && $rulesCount < 1 ) {
			$this->renderHelpingSteps();
		}

		if ( ! $this->isNewRule() ) {

			try {
				$offerInstance->validate();
			} catch ( \Exception $e ) {
				$this->renderHint( $e->getMessage() );
			}
		}

		$this->renderLicenseStatusBanner();

		?>
		<div class="cos-offer-and-survey-form">

			<div class="cos-offer-and-survey-form__tabs">
				<?php foreach ( $this->tabs as $tab ): ?>
					<div class="cos-offer-and-survey-form-tab <?php echo esc_attr( $tab->getId() === $this->defaultTab ? 'cos-offer-and-survey-form-tab--active' : '' ); ?>"
						 data-target="cos-offer-and-survey-form-tab-<?php echo esc_attr( $tab->getId() ); ?>">

						<div class="cos-offer-and-survey-form-tab__icon">
							<?php echo wp_kses_post( $tab->getIcon() ); ?>
						</div>

						<div class="cos-offer-and-survey-form-tab__title">
							<h3><?php echo esc_html( $tab->getTitle() ); ?></h3>
							<div><?php echo esc_html( $tab->getDescription() ); ?></div>
						</div>
					</div>
				<?php endforeach; ?>
			</div>

			<div class="cos-offer-and-survey-form__content">
				<?php foreach ( $this->tabs as $tab ): ?>
					<div class="cos-offer-and-survey-form-tab-content <?php echo esc_attr( $tab->getId() === $this->defaultTab ? 'cos-offer-and-survey-form-tab-content--active' : '' ); ?>"
						 id="cos-offer-and-survey-form-tab-<?php echo esc_attr( $tab->getId() ); ?>">
						<?php

							do_action( 'cancellation_offers/tabs/begin', $tab, $offerInstance );

							$tab->render( $offerInstance );

							do_action( 'cancellation_offers/tabs/end', $tab, $offerInstance );
						?>
					</div>
				<?php endforeach; ?>
			</div>
		</div>
		<?php
	}

	/**
	 * Get pricing rule instance
	 *
	 * @param  WP_Post  $post
	 *
	 * @return Offer
	 */
	public function getOfferInstance( WP_Post $post ): Offer {
		if ( empty( $this->offerInstance ) ) {
			$this->offerInstance = Offer::build( $post->ID );
		}

		return $this->offerInstance;
	}

	public function renderHint( $hint, $args = array() ) {

		$args = wp_parse_args( $args, array(
				'only_for_new_rules' => false,
				'show_icon'          => true,
				'custom_class'       => '',
		) );

		if ( ! $hint ) {
			return;
		}

		if ( $args['only_for_new_rules'] && ! $this->isNewRule() ) {
			return;
		}

		?>
		<div class="cos-offer-and-survey-hint <?php echo esc_attr( $args['custom_class'] ); ?>">
			<?php if ( $args['show_icon'] ): ?>
				<div class="cos-offer-and-survey-hint__icon">
					<span class="dashicons dashicons-info"></span>
				</div>
			<?php endif; ?>
			<div class="cos-offer-and-survey-hint__content">
				<?php echo wp_kses_post( $hint ); ?>
			</div>
		</div>
		<?php
	}

	public function renderHelpingSteps() {
		?>
		<style>
			.cos-offer-and-survey-helping {
				background: #fff;
				border: 1px solid #e8e8e8;
				padding: 20px;
				position: relative;
				text-align: center;
				margin: 20px 0;
			}

			.cos-offer-and-survey-helping__close {
				position: absolute;
				top: 10px;
				width: 26px;
				height: 26px;
				background: #faf6f9;
				color: #2271b1;
				text-align: center;
				line-height: 24px;
				right: 10px;
				font-weight: bold;
				border-radius: 50%;
			}

			.cos-offer-and-survey-helping__close:hover {
				background: #f3ddee;
				cursor: pointer;
			}

			.cos-offer-and-survey-helping__title {
				font-size: 1.5em;
				font-weight: bold;
				margin-bottom: 15px;
			}

			.cos-offer-and-survey-helping__steps {
				justify-content: center;
				gap: 20px;
				display: flex;
				align-items: center;
				margin-top: 30px
			}

			.cos-offer-and-survey-helping-step {
				width: 30%;
			}

			.cos-offer-and-survey-helping-step--arrow {
				color: #2271b1;
				width: 5%;
			}

			.cos-offer-and-survey-helping-step__title {
				font-size: 1.4em;
				font-weight: 600;
			}

			.cos-offer-and-survey-helping-step__description {
				margin-top: 10px;
			}

			.cos-offer-and-survey-helping-step__icon,
			.cos-offer-and-survey-helping-step__icon span {
				width: 50px;
				height: 50px;
				border-radius: 50%;
				background: #faf6f9;
				margin: 0 auto 15px;
				text-align: center;
				color: #2271b1;
				font-size: 25px;
				font-weight: bold;
				line-height: 50px;
			}
		</style>
		<script>
			jQuery(document).ready(function () {
				jQuery('.cos-offer-and-survey-helping__close').click(function () {
					jQuery(this).parent().hide();
				})
			})
		</script>
		<?php
		$steps = array(
				array(
						'title'         => __( 'Create Survey',
								'cancellation-surveys-offers-woocommerce-subscriptions' ),
						'description'   => __( 'Define cancellation reasons.',
								'cancellation-surveys-offers-woocommerce-subscriptions' ),
						'icon'          => '<span class="dashicons dashicons-feedback"></span>',
						'has_next_step' => true,
				),
				array(
						'title'         => __( 'Retention Offer',
								'cancellation-surveys-offers-woocommerce-subscriptions' ),
						'description'   => __( ' Offer discount or a chance to skip the renewal',
								'cancellation-surveys-offers-woocommerce-subscriptions' ),
						'icon'          => '<span class="dashicons dashicons-tickets-alt"></span>',
						'has_next_step' => true,
				),
				array(
						'title'         => __( 'Products & Roles',
								'cancellation-surveys-offers-woocommerce-subscriptions' ),
						'description'   => __( 'Limit survey and offers to specific products or user roles.',
								'cancellation-surveys-offers-woocommerce-subscriptions' ),
						'icon'          => '<span class="dashicons dashicons-admin-users"></span>',
						'has_next_step' => false,
				),
		);

		?>
		<div class="cos-offer-and-survey-helping">
			<div class="cos-offer-and-survey-helping__title">
				<?php
					esc_html_e( 'Create Survey Form and Offer Step-by-Step',
							'cancellation-surveys-offers-woocommerce-subscriptions' );
				?>
			</div>
			<p>
				<?php
					esc_html_e( 'Complete this form with your survey questions, discount offers, and limitations. This will help you understand the reasons behind subscription cancellations and enable you to retain customers with targeted discount offers.',
							'cancellation-surveys-offers-woocommerce-subscriptions' );
				?>
			</p>

			<div class="cos-offer-and-survey-helping__steps">

				<?php foreach ( $steps as $step ): ?>

					<div class="cos-offer-and-survey-helping-step">
						<div class="cos-offer-and-survey-helping-step__icon">
							<?php echo wp_kses_post( $step['icon'] ); ?>
						</div>

						<div class="cos-offer-and-survey-helping-step__title">
							<?php echo esc_html( $step['title'] ); ?>
						</div>

						<div class="cos-offer-and-survey-helping-step__description">
							<?php echo esc_html( $step['description'] ); ?>
						</div>
					</div>

					<?php if ( $step['has_next_step'] ): ?>
						<div class="cos-offer-and-survey-helping-step cos-offer-and-survey-helping-step--arrow">
							<span class="dashicons dashicons-arrow-right-alt"></span>
						</div>
					<?php endif; ?>
				<?php endforeach; ?>
			</div>
			<div class="cos-offer-and-survey-helping__close">
				&times;
			</div>
		</div>
		<?php
	}

	public function isNewRule(): bool {
		global $pagenow;

		return 'post-new.php' == $pagenow;
	}
}