<?php
/**
 * Setup wizard view for admin interface.
 *
 * @package Awesomemotive\Rewardswp\Views\Admin
 * @since 1.0.0
 */

namespace Awesomemotive\Rewardswp\Views\Admin;

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

use Affiliate_WP_Generator\Abstracts\Integration;
use Awesomemotive\Rewardswp\Abstracts\AbstractView;
use Awesomemotive\Rewardswp\Factories\ViewsFactory;
use Awesomemotive\Rewardswp\Helpers\IconHelper;
use Awesomemotive\Rewardswp\Interfaces\IntegrationInterface;
use Awesomemotive\Rewardswp\Interfaces\ViewInterface;

use Awesomemotive\Rewardswp\Services\AssetsService;
use Awesomemotive\Rewardswp\Services\OptionsService;
use Defuse\Crypto\Crypto;
use Defuse\Crypto\Key;
use function Awesomemotive\Rewardswp\Helpers\get_rewardswp_plan_tier;
use function Awesomemotive\Rewardswp\Helpers\get_rewardswp_setup_template;

/**
 * Setup View
 *
 * The Setup Wizard for RewardsWP.
 *
 * @since AFFWPN
 *
 * @param type name Description.
 *
 * @return type Description.
 *
 * @see wp-content/plugins/rewardswp/src/Views/Admin/AdminHeaderView.php get_page_title() for where the page title is set.
 */
class SetupView extends AbstractView implements ViewInterface {

	/**
	 * The Setup URL
	 *
	 * This URL is set in the `__construct()`.
	 *
	 * @since 1.0.0
	 *
	 * @var string
	 */
	private string $setup_url;

	/**
	 * Integration instance.
	 *
	 * @var IntegrationInterface
	 */
	private IntegrationInterface $integration;

	/**
	 * Options service instance.
	 *
	 * @since 1.1.0
	 *
	 * @var OptionsService
	 */
	private OptionsService $options_service;

	/**
	 * Constructor.
	 *
	 * @since 1.0.0
	 */
	public function __construct( IntegrationInterface $integration, OptionsService $options_service ) {
		$this->integration     = $integration;
		$this->options_service = $options_service;

		// Use get_rewardswp_setup_template() which maps basic/plus/pro to 'pro'
		$this->setup_url = sprintf(
			defined( 'REWARDSWP_LARAVEL_APP_REWARDSWP_SETUP_URL' )
				? trailingslashit( REWARDSWP_LARAVEL_APP_REWARDSWP_SETUP_URL )
				: 'https://app.rewardswp.com/setup/%s/',
			strtolower( get_rewardswp_setup_template() )
		);
	}

	/**
	 * Set the referrer secret.
	 *
	 * This secret is generated each time the wizard is started, allowing
	 * the wizard to be re-run multiple times. The Laravel app uses this
	 * secret to store and retrieve wizard results.
	 *
	 * @since 1.0.0
	 */
	private function set_referer_secret(): void {

		update_option(
			sprintf(
				'rewardswp_%s_setup_referrer_secret',
				get_rewardswp_setup_template()
			),
			Key::createNewRandomKey()
					->saveToAsciiSafeString(),
			false
		);
	}

	/**
	 * Get the referrer secret.
	 *
	 * This secret is generated for this site and only this site, no one can
	 * guess it. It is required as a GET parameter when accessing the offsite
	 * wizard.
	 *
	 * @since 1.0.0
	 *
	 * @return string
	 */
	private function get_referer_secret(): string {

		$this->set_referer_secret();

		// We don't store the actual key un-encoded in the DB.
		return get_option(
			sprintf(
				'rewardswp_%s_setup_referrer_secret',
				get_rewardswp_setup_template()
			)
		);
	}

	/**
	 * Get the URL for the RewardsWP Setup Wizard.
	 *
	 * @since AFFWPN
	 *
	 * @return string
	 */
	private function get_setup_url(): string {

		$referrer_secret = $this->get_referer_secret(); // Might set it for the first time.

		// Converts the string to a binary encrypt key.
		$encrypt_key = Key::loadFromAsciiSafeString( $referrer_secret );

		return add_query_arg(
			[

				// Encode it again for transit to the other server.
				'referrer_secret' => urlencode( $referrer_secret ),

				// The website to return to (this website).
				'referrer'        => urlencode(
					Crypto::encrypt(
						admin_url( 'admin.php?page=rewardswp' ),
						$encrypt_key
					)
				),

				// Initial results to pre-populate.
				'results'         => urlencode(
					Crypto::encrypt(
						wp_json_encode(
							[
								'email'             => get_option( 'admin_email', '' ),
								'site_name'         => get_bloginfo( 'name' ),
								'integrations'      => [
									$this->integration->get_source(),
								],
								'rewardswp_version' => get_plugin_data( AM_REWARDSWP_PLUGIN_FILE )['Version'] ?? 'Unknown',
								'settings'          => $this->get_wizard_presets(),
							]
						),
						$encrypt_key
					),
				),
			],
			$this->setup_url
		);
	}

	/**
	 * Get existing settings to pre-populate wizard fields.
	 *
	 * Only includes settings that correspond to wizard steps to avoid
	 * sending unnecessary data to the external service.
	 *
	 * @since 1.1.0
	 *
	 * @return array Curated settings for wizard pre-population.
	 */
	private function get_wizard_presets(): array {
		$settings = $this->options_service->get_options();

		return [
			'license_key'       => $settings['general']['license']['key'] ?? '',
			'brand_color'       => $settings['general']['brand_color'] ?? '',
			'program_name'      => $settings['rewards_widget']['program_name'] ?? '',
			'points_enabled'    => $settings['points']['enabled'] ?? false,
			'referrals_enabled' => $settings['referrals']['enabled'] ?? false,
			'currency'          => $settings['general']['currency'] ?? 'USD',
		];
	}

	/**
	 * Render the template.
	 *
	 * @since 1.0.0
	 *
	 * @param array $args {
	 * }
	 *
	 * @return void
	 */
	public function render( array $args = [] ): void {
		?>
		<dialog id="rewardswp-setup-dialog" class="w-screen h-screen max-w-full max-h-full p-0 m-0 overflow-y-auto rewardswp-container bg-blue-50"
			aria-labelledby="rewardswp-setup-title">

			<div class="flex flex-col items-center justify-center max-w-3xl min-h-full p-10 mx-auto text-sm text-center">
				<div class="flex items-center mb-10 space-x-3 text-left">
					<svg
						class="w-14 h-14"
						viewBox="0 0 64 64"
						fill="none"
						xmlns="http://www.w3.org/2000/svg"
						role="img" aria-label="RewardsWP Logo">
						<g>
							<path
								fill-rule="evenodd"
								clip-rule="evenodd"
								d="M3.45779 36.9243C1.40117 35.2742 0.393787 33.3334 0.0942323 31.4783C-0.376072 28.5655 0.929878 25.6024 3.45779 23.7573V12.6848C3.45779 8.09722 7.18223 4.37278 11.7698 4.37278H27.934C27.2052 5.14501 26.5206 5.97838 25.8879 6.87309C25.1187 7.9608 24.4259 9.13864 23.8286 10.4074H11.7698C10.5128 10.4074 9.4924 11.4278 9.4924 12.6848V21.8939C12.6833 21.9056 16.5561 23.2574 20.3764 27.0778C21.6723 28.3737 22.9992 29.6501 24.3505 30.883V21.7949C24.3505 16.4134 25.8808 12.0401 28.2724 8.65834C38.159 -5.32168 62.7703 -2.29191 62.7703 17.1739C62.7703 25.6872 58.3255 31.8136 50.1046 35.7352C46.3067 37.5465 41.6393 38.8712 36.2071 39.7289C37.7821 40.6024 39.3659 41.3444 40.9507 41.9241C47.3098 44.2479 56.2757 44.2529 63.999 41.4305C57.635 48.8886 50.5121 51.6547 38.8802 47.5877C36.0261 46.5896 33.1922 45.0532 30.3808 43.2329V57.3193H54.127C55.3844 57.3193 56.4043 56.2994 56.4043 55.042V50.6674C57.9654 50.0906 60.123 49.129 62.4389 47.6055V55.042C62.4389 59.6293 58.7143 63.3539 54.127 63.3539H11.7698C7.18223 63.3539 3.45779 59.6293 3.45779 55.042V36.9243ZM24.3505 57.3193V40.828C22.6229 40.8933 20.8449 40.9259 19.0186 40.9259C15.1528 40.9259 12.0102 40.4966 9.4924 39.807V55.042C9.4924 56.2994 10.5128 57.3193 11.7698 57.3193H24.3505ZM9.03496 33.2863C11.281 34.2916 14.5404 34.8957 19.0186 34.8957C19.284 34.8957 19.5482 34.8951 19.8115 34.8937C18.5549 33.7385 17.3202 32.5497 16.1123 31.3418C12.6532 27.8826 9.34628 27.2546 7.27018 28.4691C6.47648 28.9334 5.91239 29.6807 6.04743 30.517C6.17148 31.2853 6.75852 31.9692 7.73207 32.5913L9.03496 33.2863ZM30.3808 34.4033C37.2657 33.7486 43.048 32.4201 47.5077 30.2924C53.3761 27.493 56.7407 23.2513 56.7407 17.1739C56.7407 3.98439 39.8952 2.66775 33.1959 12.1402C31.4415 14.6209 30.3808 17.8473 30.3808 21.7949V34.4033Z"
								fill="#2263EB" />
						</g>
					</svg>
					<div class="flex flex-col">
						<span
							class="text-4xl font-bold text-slate-900">RewardsWP</span>
						<span class="-mt-1 text-lg text-slate-700"><?php esc_html_e( 'By AffiliateWP', 'rewardswp' ); ?></span>
					</div>
				</div>

				<p id="rewardswp-setup-title" class="max-w-xl mb-8 text-base text-center text-slate-700">
					<?php echo esc_html__( 'Thank you for choosing RewardsWP!', 'rewardswp' ); ?>
					<span class="block"><?php echo esc_html__( 'Get ready to reward your customers and boost revenue.', 'rewardswp' ); ?></span>
				</p>

				<div class="w-full px-10 py-10 mb-8 text-center bg-white shadow-xl ring-1 ring-blue-100 shadow-blue-500/20 rounded-xl md:px-20">
					<p class="mb-8 text-xl font-medium text-slate-800 text-pretty">
						<?php echo esc_html__( 'Use our setup wizard to launch your rewards program in less than 5 minutes.', 'rewardswp' ); ?>
					</p>

					<a
						href="<?php echo esc_url( $this->get_setup_url() ); ?>"
						class="flex items-center justify-center w-full px-8 py-2 space-x-3 text-lg text-white transition-all duration-200 ease-in-out bg-blue-600 shadow-lg group text-shadow-sm text-shadow-blue-600/20 sm:text-xl rounded-xl hover:bg-blue-500 shadow-blue-600/20 focus-visible:outline-2 focus-visible:outline-offset-2 focus-visible:outline-blue-600">

						<span class="font-semibold"><?php echo esc_html__( 'Get Started', 'rewardswp' ); ?></span>

						<div class="overflow-hidden mask-l-from-35% mask-l-to-100% w-[32px] inline-flex items-center justify-end">
							<svg
								class="relative w-10 h-10 transition-transform duration-200 ease-in-out -translate-x-1 group-hover:-translate-x-0"
								viewBox="0 0 24 24" xmlns="http://www.w3.org/2000/svg"
								aria-hidden="true">
								<path d="m23.25 12.497 -22.5 0" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5"></path>
								<path d="m19.5 16.247 3.75 -3.75 -3.75 -3.75" fill="none" stroke="currentColor" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5"></path>
							</svg>
						</div>
					</a>



					<p class="mt-5 text-sm text-slate-500 text-pretty"><?php echo esc_html__( 'You will be transfered to an external service to complete the setup wizard.', 'rewardswp' ); ?></p>

				</div>

				<div class="flex flex-col items-center justify-center gap-3 mt-4 text-center">
					<button type="button" id="rewardswp-exit-setup" class="underline underline-offset-2 cursor-pointer bg-transparent border-none text-slate-600 hover:text-slate-900"><?php echo esc_html__( 'Exit Setup', 'rewardswp' ); ?></button>
				</div>
			</div>
		</dialog>

		<script>
			document.addEventListener('DOMContentLoaded', function() {
				const dialog = document.getElementById('rewardswp-setup-dialog');
				if (dialog) {
					document.documentElement.style.overflow = 'hidden';
					dialog.showModal();

					// Prevent closing via the Esc key.
					dialog.addEventListener('cancel', (event) => {
						event.preventDefault();
					});

					// Close dialog when exit button is clicked.
					document.getElementById('rewardswp-exit-setup').addEventListener('click', () => {
						dialog.close();
					});

					// Cleanup styles when dialog is closed.
					dialog.addEventListener('close', () => {
						document.documentElement.style.overflow = '';
						document.body.classList.remove('rewardswp-setup-dialog-open');
						document.documentElement.classList.remove('rewardswp-setup-dialog-open');

						// Remove ?setup=1 from URL so refresh doesn't re-show dialog.
						const url = new URL(window.location);
						url.searchParams.delete('setup');
						history.replaceState(null, '', url);
					});

					dialog.addEventListener('keydown', (event) => {
						if (event.key === 'Escape') {
							event.stopPropagation();
							event.preventDefault();
						}
					});
				}
			});
		</script>

		<?php
	}
}
