<?php namespace MeowCrew\CancellationOffers\Frontend\OfferPopup;

use MeowCrew\CancellationOffers\CancellationOffersPlugin;
use MeowCrew\CancellationOffers\Core\ServiceContainerTrait;
use MeowCrew\CancellationOffers\Frontend\OfferPopup\Actions\CancelSubscriptionAction;
use MeowCrew\CancellationOffers\Frontend\OfferPopup\Actions\TakeDiscountAction;
use MeowCrew\CancellationOffers\Offer\Entity\Offer;
use MeowCrew\CancellationOffers\Offer\OfferManager;
use WC_Subscription;

/**
 * Class OfferPopup
 *
 * @package MeowCrew\CancellationOffers\Frontend
 */
class OfferPopup {

	use ServiceContainerTrait;

	public $offers = [];

	/**
	 * Action handler for the cancel subscription.
	 *
	 * @var CancelSubscriptionAction
	 */
	protected $cancelSubscriptionAction;

	/**
	 * Action handler for the saving subscription.
	 *
	 * @var TakeDiscountAction
	 */
	protected $takeDiscountAction;

	public function __construct() {

		$this->cancelSubscriptionAction = new CancelSubscriptionAction();
		$this->takeDiscountAction       = new TakeDiscountAction();

		add_action( 'wp_enqueue_scripts', array( $this, 'enqueueAssets' ) );
		add_action( 'woocommerce_subscription_after_actions', array( $this, 'renderPopup' ) );
		add_action( 'wp_footer', array( $this, 'renderPreviewPopup' ) );

		add_filter( 'wcs_view_subscription_actions', array( $this, 'filterSubscriptionActions' ), 99999, 3 );
	}

	public function enqueueAssets() {

		if ( ! is_account_page() ) {
			return;
		}

		wp_enqueue_script( 'cancellation-offers__popup.js',
				$this->getContainer()->getFileManager()->locateAsset( 'frontend/popup.min.js' ), array( 'jquery' ),
				CancellationOffersPlugin::VERSION, true );

		wp_enqueue_style( 'cancellation-offers__popup.css',
				$this->getContainer()->getFileManager()->locateCSSAsset( 'frontend/popup' ), array(),
				CancellationOffersPlugin::VERSION );

		wp_enqueue_script( 'cancellation-offers-frontend',
				$this->getContainer()->getFileManager()->locateJSAsset( 'frontend/main.js' ),
				array( 'jquery', 'cancellation-offers__popup.js' ), CancellationOffersPlugin::VERSION, true );
	}

	public function getSubscriptionOffer( $subscription ) {

		if ( ! array_key_exists( $subscription->get_id(), $this->offers ) ) {
			$this->offers[ $subscription->get_id() ] = OfferManager::getOfferForSubscription( $subscription );
		}

		return $this->offers[ $subscription->get_id() ];
	}

	/**
	 * Get popup preview URL
	 *
	 * @param  int  $offerId
	 *
	 * @return string
	 */
	public static function getPreviewURL( int $offerId ): string {
		return add_query_arg( array(
				'preview_cancellation_offer_id' => $offerId,
		), wc_get_page_permalink( 'myaccount' ) );
	}

	public function filterSubscriptionActions( $actions, WC_Subscription $subscription ) {
		$offer = $this->getSubscriptionOffer( $subscription );

		if ( ! $offer ) {
			return $actions;
		}

		if ( ! empty( $actions['cancel'] ) ) {
			$actions['cancel']['url']      = '#cancellation-popup';
			$actions['cancel']['block_ui'] = false;
		}

		return $actions;
	}

	public function renderPreviewPopup() {

		if ( ! is_user_logged_in() ) {
			return;
		}

		if ( ! current_user_can( 'manage_woocommerce' ) ) {
			return;
		}

		$previewOfferId = isset( $_GET['preview_cancellation_offer_id'] ) ? intval( $_GET['preview_cancellation_offer_id'] ) : false;

		$previewOffer = Offer::build( $previewOfferId );

		if ( ! $previewOffer ) {
			return;
		}

		$this->renderPopup( new WC_Subscription(), $previewOffer, true );
	}

	public function renderPopup( WC_Subscription $subscription, ?Offer $offer = null, $preview = false ) {

		$offer = $offer ? $offer : $this->getSubscriptionOffer( $subscription );

		if ( ! $offer ) {
			return;
		}

		$settings    = $offer->getSettings();
		$accentColor = $settings->getAccentColor();

		?>

		<style>
			:root {
				--cos-accent-color: <?php echo esc_html($accentColor); ?>;
			}
		</style>

		<div id="cancellation-offer-popup-wrapper" style="display: none">
			<?php
				$this->getContainer()->getFileManager()->includeTemplate( 'frontend/popup.php', array(
						'cancel_subscription_url' => $this->cancelSubscriptionAction->getURL( $subscription->get_id(),
								$offer->getId() ),
						'take_discount_url'       => $this->takeDiscountAction->getURL( $subscription->get_id(),
								$offer->getId() ),
						'offer'                   => $offer,
						'subscription'            => $subscription,
						'is_preview'              => $preview,
						'background_image'        => $settings->getBackgroundImage(),
						'popup_style'             => $settings->getPopupStyle(),
						'popup_layout'            => $settings->getPopupLayout(),
				) );
			?>
		</div>

		<?php
	}
}