<?php
/**
 * License section view for admin interface.
 *
 * @package Awesomemotive\Rewardswp\Views\Admin\Sections
 * @since 1.0.0
 */

namespace Awesomemotive\Rewardswp\Views\Admin\Sections;

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

use Awesomemotive\Rewardswp\Abstracts\AbstractView;
use Awesomemotive\Rewardswp\Controllers\Admin\LicenseController;
use Awesomemotive\Rewardswp\Interfaces\ViewInterface;
use Awesomemotive\Rewardswp\Settings\Options\General\LicenseOption;
use function Awesomemotive\Rewardswp\Helpers\format_date_from_timestamp;
use function Awesomemotive\Rewardswp\Helpers\get_option_value;
use function Awesomemotive\Rewardswp\Helpers\get_rewardswp_plan_name;
use function Awesomemotive\Rewardswp\Helpers\is_license_valid;
use function Awesomemotive\Rewardswp\Helpers\is_rewardswp_lite_plan;
use function Awesomemotive\Rewardswp\Helpers\get_upgrade_url;

class LicenseSectionView extends AbstractView implements ViewInterface {
	/**
	 * Render the template.
	 *
	 * @since 1.0.0
	 *
	 * @param array $args
	 *
	 * @return void
	 */
	public function render( array $args = [] ): void {
		// is_license_valid() must be called before retrieving data from LicenseOption, since new license data can be fetched.
		$is_license_valid   = ! is_rewardswp_lite_plan() && is_license_valid();
		$license_option     = get_option_value( LicenseOption::class );
		$plan_name          = get_rewardswp_plan_name();
		$ajax_nonce         = wp_create_nonce( LicenseController::AJAX_NONCE );
		$ajax_url           = admin_url( 'admin-ajax.php' );
		$activate_pro_nonce = wp_create_nonce( LicenseController::AJAX_ACTIVATE_PRO_NONCE );
		$activate_pro_url   = admin_url( 'admin-ajax.php' );
		$settings_url       = admin_url( 'admin.php?page=rewardswp-settings' );

		?>

		<div
			x-data="licenseSection(
				'<?php echo esc_js( $license_option['key'] ?? '' ); ?>',
				'<?php echo esc_js( $license_option['status'] ?? '' ); ?>',
				<?php echo esc_js( $is_license_valid ) ? 'true' : 'false'; ?>,
				'<?php echo esc_js( format_date_from_timestamp( (int) $license_option['expires'] ) ); ?>',
				'<?php echo esc_js( (int) $license_option['expires'] ); ?>',
				'<?php echo esc_js( $plan_name ); ?>',
				'<?php echo esc_js( $license_option['price_id'] ?? '' ); ?>',
				'<?php echo esc_js( $ajax_nonce ); ?>',
				'<?php echo esc_js( $ajax_url ); ?>',
				'<?php echo esc_js( $activate_pro_nonce ); ?>',
				'<?php echo esc_js( $activate_pro_url ); ?>',
				'<?php echo esc_js( $settings_url ); ?>'
			)"
			class="divide-y divide-gray-200"
		>
			<input type="hidden" name="rewardswp_settings[general][license][key]" x-bind:value="licenseKey">
			<input type="hidden" name="rewardswp_settings[general][license][status]" x-bind:value="licenseStatus">
			<input type="hidden" name="rewardswp_settings[general][license][expires]" x-bind:value="licenseExpiry">
			<input type="hidden" name="rewardswp_settings[general][license][plan_name]" x-bind:value="licenseLevel">
			<input type="hidden" name="rewardswp_settings[general][license][price_id]" x-bind:value="priceId">
			<!-- Activate Pro Modal -->
			<div
				x-show="showActivateProModal"
				x-cloak
				class="fixed inset-0 z-[999999] overflow-y-auto"
				x-trap.noscroll.inert="showActivateProModal"
				x-on:keydown.escape.window="showActivateProModal = false"
				aria-labelledby="activate-pro-modal-title"
				role="dialog"
				aria-modal="true"
			>
				<div class="flex items-center justify-center min-h-screen px-4 pt-4 pb-20 text-center sm:p-0">
					<!-- Background overlay -->
					<div
						x-show="showActivateProModal"
						x-transition:enter="ease-out duration-300"
						x-transition:enter-start="opacity-0"
						x-transition:enter-end="opacity-100"
						x-transition:leave="ease-in duration-200"
						x-transition:leave-start="opacity-100"
						x-transition:leave-end="opacity-0"
						class="fixed inset-0 transition-opacity"
						aria-hidden="true"
						x-on:click="showActivateProModal = false"
					>
						<div class="absolute inset-0 bg-gray-500 opacity-75"></div>
					</div>

					<!-- This element is to trick the browser into centering the modal contents. -->
					<span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>

					<!-- Modal panel -->
					<div
						x-show="showActivateProModal"
						x-transition:enter="ease-out duration-300"
						x-transition:enter-start="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
						x-transition:enter-end="opacity-100 translate-y-0 sm:scale-100"
						x-transition:leave="ease-in duration-200"
						x-transition:leave-start="opacity-100 translate-y-0 sm:scale-100"
						x-transition:leave-end="opacity-0 translate-y-4 sm:translate-y-0 sm:scale-95"
						class="relative inline-block w-full max-w-lg p-6 my-8 overflow-hidden text-left align-middle transition-all transform bg-white rounded-lg shadow-xl z-[999999]"
						role="dialog"
						aria-modal="true"
						aria-labelledby="activate-pro-modal-title"
						x-init="$nextTick(() =&gt; $el.querySelector('button, [href], input, select, textarea, [tabindex]:not([tabindex=\'-1\'])').focus())"
						x-on:click.stop
					>
						<div>
							<div class="mx-auto flex items-center justify-center h-12 w-12 rounded-full bg-green-100">
								<!-- Heroicon name: outline/check -->
								<svg class="h-6 w-6 text-green-600" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor" aria-hidden="true">
									<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
								</svg>
							</div>
							<div class="mt-3 text-center sm:mt-5">
								<h3 class="text-lg font-medium leading-6 text-gray-900" id="activate-pro-modal-title">
									<?php esc_html_e( 'Almost Done', 'rewardswp' ); ?>
								</h3>
								<div class="mt-2">
									<p class="text-sm text-gray-500">
										<?php esc_html_e( 'RewardsWP Pro is installed but needs to be activated.', 'rewardswp' ); ?>
									</p>
								</div>
							</div>
						</div>
						<div class="mt-5 sm:mt-6 flex justify-center gap-3">
							<button
								x-on:click.prevent="activateProAndReload"
								type="button"
								x-bind:disabled="isActivatingPro"
								x-bind:class="{ 'cursor-not-allowed opacity-50': isActivatingPro }"
								class="inline-flex justify-center px-4 py-2 text-base font-medium text-white bg-green-600 border border-transparent rounded-md shadow-sm hover:bg-green-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-500 sm:w-auto sm:text-sm"
							>
								<span x-show="!isActivatingPro"><?php esc_html_e( 'Activate & Reload', 'rewardswp' ); ?></span>
								<span x-show="isActivatingPro" class="flex items-center">
									<svg class="animate-spin -ml-1 mr-3 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
										<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
										<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
									</svg>
									<?php esc_html_e( 'Activating...', 'rewardswp' ); ?>
								</span>
							</button>
							<button
								type="button"
								class="mt-3 inline-flex justify-center rounded-md border border-gray-300 shadow-sm px-4 py-2 bg-white text-base font-medium text-gray-700 hover:bg-gray-50 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-indigo-500 sm:mt-0 sm:w-auto sm:text-sm"
								x-on:click="showActivateProModal = false"
							>
								<?php esc_html_e( 'Cancel', 'rewardswp' ); ?>
							</button>
						</div>
					</div>
				</div>
			</div>

			<div class="py-5">
				<div class="gap-8 md:flex">
					<div class="md:w-1/3 flex-none">
						<label for="license_key" class="text-sm font-semibold"><?php esc_html_e( 'License Key', 'rewardswp' ); ?></label>
						<p class="text-sm text-gray-500 mt-2"><?php esc_html_e( 'Your license key provides access to updates and features.', 'rewardswp' ); ?></p>
					</div>
					<div class="md:w-2/3">

						<!-- License Status -->
						<div
							x-show="licenseConnected"
							class="mb-2 text-sm text-gray-600"
						>
							<p>
								<span class="font-medium text-gray-800">
								<?php
								printf(
									/* translators: %s: Subscription plan name wrapped in HTML. */
									esc_html__( 'Your %s plan is active!', 'rewardswp' ),
									'<span class="font-bold">' . esc_html__( 'RewardsWP Pro', 'rewardswp' ) . '</span>'
								);
								?>
								</span>
								<span>😊</span>
							</p>
						</div>

						<div
							x-show="!licenseConnected"
							class="mb-2"
						>
							<?php if ( is_rewardswp_lite_plan() ) : ?>
								<p class="text-sm text-gray-700">
								<?php
									printf(
										/* translators: %s: RewardsWP Lite name wrapped in HTML strong tag. */
										esc_html__( "You're using %s - no license needed. Enjoy!", 'rewardswp' ),
										'<span class="font-semibold">' . esc_html__( 'RewardsWP Lite', 'rewardswp' ) . '</span>'
									);
								?>
									🙂
								</p>

								<!-- Upsell Box -->
								<div class="bg-blue-50 p-4 my-4 rounded-md">
									<p class="text-sm text-gray-700">
									<?php
										printf(
											/* translators: %s: Link to upgrade to PRO */
											esc_html__( 'To unlock more features, consider %s.', 'rewardswp' ),
											'<a class="font-semibold text-green-600 underline hover:no-underline" href="' . esc_url( get_upgrade_url( 'upgrade_to_pro', 'settings-license' ) ) . '" target="_blank">' . esc_html__( 'upgrading to Pro', 'rewardswp' ) . '</a>'
										);
									?>
									</p>
									<p class="text-sm text-gray-600 italic mt-1">
									<?php
										printf(
											/* translators: %s: Discount percentage */
											esc_html__( 'As a valued user you receive %s, automatically applied at checkout!', 'rewardswp' ),
											'<span class="font-semibold text-gray-900 not-italic">' . esc_html__( '50% off', 'rewardswp' ) . '</span>'
										);
									?>
									</p>
								</div>

								<p class="text-sm text-gray-700">
								<?php
									printf(
										/* translators: %s: RewardsWP PRO name wrapped in HTML strong tag. */
										esc_html__( 'Already purchased? Simply enter your license key below to connect with %s', 'rewardswp' ),
										'<span class="font-semibold">' . esc_html__( 'RewardsWP Pro!', 'rewardswp' ) . '</span>'
									);
								?>
								</p>
							<?php else : ?>


								<p class="mt-2 text-sm text-gray-700">
									<?php
									printf(
										/* translators: %s: RewardsWP Pro name wrapped in HTML strong tag. */
										esc_html__( 'Enter your license key below to activate %s', 'rewardswp' ),
										'<span class="font-bold">RewardsWP Pro!</span>'
									);
									?>
								</p>

							<?php endif; ?>
						</div>

						<!-- Input and Button Section -->
						<div class="flex items-center gap-2">
							<input
								type="password"
								id="license_key"
								autocomplete="new-password"
								class="block flex-1 py-2 px-3 text-sm text-gray-900 placeholder:text-gray-400 border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-600"
								x-model="licenseKey"
								placeholder="<?php esc_html_e( 'Paste your license key here', 'rewardswp' ); ?>"
								x-bind:disabled="licenseConnected"
							>
							<button
								x-on:click.prevent="connectLicenseKey"
								type="button"
								x-bind:hidden="!isLoading && licenseConnected"
								x-bind:disabled="!licenseKey || isLoading"
								x-bind:class="{
									'bg-gray-200 focus:ring-gray-300 cursor-not-allowed border border-gray-300': !licenseKey || isLoading,
									'bg-green-600 focus:ring-green-600 hover:bg-green-700 border border-green-600': licenseKey && !isLoading,
									'text-white': licenseKey,
									'text-gray-500': !licenseKey
								}"
								class="px-4 py-2 text-sm place-items-center font-medium rounded-md focus:outline-none focus:ring-2 focus:ring-offset-2 grid grid-cols-1 grid-rows-1 [grid-template-areas:stack]"
							>
								<span
									class="[grid-area:stack] transition-opacity duration-200"
									x-bind:class="{ 'invisible': isLoading, 'visible': !isLoading }"
								>
									<?php esc_html_e( 'Connect', 'rewardswp' ); ?>
								</span>
								<svg
									class="[grid-area:stack] animate-spin h-5 w-5 transition-opacity duration-200"
									x-bind:class="{ 'invisible': !isLoading, 'visible': isLoading }"
									xmlns="http://www.w3.org/2000/svg"
									fill="none"
									viewBox="0 0 24 24"
								>
									<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
									<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
								</svg>
							</button>
						</div>

						<div x-show="licenseConnected && 'expired' === licenseStatus" class="border border-red-500 bg-red-50 p-4 rounded-md mt-4">
							<p class="text-sm font-semibold text-red-700">
								<?php esc_html_e( 'Your license has expired.', 'rewardswp' ); ?>
							</p>
							<p class="text-sm text-gray-700 mt-1">
								<?php esc_html_e( 'A valid license key is required in order to enable Pro features and continue to receive automatic updates.', 'rewardswp' ); ?>
							</p>
							<div class="mt-3">
								<a href="#"
									class="bg-green-600 text-white font-medium text-sm py-2 px-4 rounded-md hover:bg-green-500 focus:ring focus:ring-green-300 focus:outline-none">
									<?php esc_html_e( 'Purchase license', 'rewardswp' ); ?>
								</a>
							</div>
						</div>

						<div x-show="licenseConnected && 'invalid' === licenseStatus" class="border border-red-500 bg-red-50 p-4 rounded-md mt-4">
							<p class="text-sm font-semibold text-red-700">
								<?php esc_html_e( 'Your license key is invalid.', 'rewardswp' ); ?>
							</p>
							<p class="text-sm text-gray-700 mt-1">
								<?php esc_html_e( 'A valid license key is required in order to enable Pro features and continue to receive automatic updates.', 'rewardswp' ); ?>
							</p>
							<div class="mt-3">
								<a href="#"
									class="bg-green-600 text-white font-medium text-sm py-2 px-4 rounded-md hover:bg-green-500 focus:ring focus:ring-green-300 focus:outline-none">
									<?php esc_html_e( 'Purchase license', 'rewardswp' ); ?>
								</a>
							</div>
						</div>

						<div x-show="!licenseConnected && 'invalid' === licenseStatus" class="border border-red-500 bg-red-50 p-4 rounded-md mt-4">
							<p class="text-sm font-semibold text-red-700">
								<?php
								echo is_rewardswp_lite_plan()
									? esc_html__( 'The license key provided is invalid. Please use a different key to upgrade.', 'rewardswp' )
									: esc_html__( 'The license key provided is invalid. Please use a different key to continue receiving automatic updates.', 'rewardswp' );
								?>
							</p>
						</div>

						<!-- License Status -->
						<div
							x-show="licenseConnected"
							class="mt-4 mb-4 text-sm text-gray-600"
						>
							<p class="mt-1">
								<?php esc_html_e( 'Your license level is', 'rewardswp' ); ?>
								<span class="font-semibold text-gray-800" x-text="licenseLevel"></span>
								(<?php esc_html_e( 'expires:', 'rewardswp' ); ?>
								<span class="font-semibold" x-text="licenseExpiryFormatted"></span>).
								<a
									href="#"
									x-on:click.prevent="disconnectLicenseKey"
									class="text-blue-600 font-semibold underline hover:text-blue-800"
								><?php esc_html_e( 'Deactivate license key', 'rewardswp' ); ?></a>.
							</p>
							<p class="mt-1 text-gray-600 italic">
								<?php esc_html_e( 'If your license key has been upgraded or is incorrect, then please', 'rewardswp' ); ?>
								<a
									href="#"
									x-on:click.prevent="forceRefresh"
									class="text-blue-600 underline hover:text-blue-800"
								><?php esc_html_e( 'force a refresh', 'rewardswp' ); ?></a>.
							</p>
						</div>

					</div>
				</div>
			</div>
		</div>

		<?php
	}
}
