<?php
/**
 * Referrals tracking content view.
 *
 * @package Awesomemotive\Rewardswp\Views\Admin\Parts
 * @since 1.0.0
 */

namespace Awesomemotive\Rewardswp\Views\Admin\Parts;

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

use Awesomemotive\Rewardswp\Abstracts\AbstractView;
use Awesomemotive\Rewardswp\Interfaces\ViewInterface;
use Awesomemotive\Rewardswp\Settings\Options\Referrals\CookieExpirationOption;
use Awesomemotive\Rewardswp\Settings\Options\Referrals\ReferralVariableOption;
use function Awesomemotive\Rewardswp\Helpers\get_option_value;
use function Awesomemotive\Rewardswp\Helpers\kses;
use Awesomemotive\Rewardswp\Helpers\IconHelper;

class ReferralsTrackingContentView extends AbstractView implements ViewInterface {
	private IconHelper $icon_helper;

	public function __construct( IconHelper $icon_helper ) {
		$this->icon_helper = $icon_helper;
	}

	/**
	 * Render the template.
	 *
	 * @since 1.0.0
	 *
	 * @param array $args
	 *
	 * @return void
	 */
	public function render( array $args = [] ): void {
		$site_url = home_url( '/' );
		?>

		<div class="divide-y divide-gray-200">

			<div class="py-5">
				<div class="gap-8 md:flex md:items-start">
					<div class="md:w-1/3 flex-none">
						<label for="referral_slug" class="text-sm font-semibold"><?php esc_html_e( 'Referral Variable', 'rewardswp' ); ?></label>
					</div>
					<div class="md:w-2/3">

						<div
							x-data="{
								inputValue: '<?php echo esc_attr( get_option_value( ReferralVariableOption::class ) ); ?>',
								disallowedValue: '<?php echo esc_js( $this->get_affiliatewp_referral_var() ); ?>',
								errorMessage: '',
								validateSlugField( inputValue ) {
									const sanitizedSlug = inputValue
										.trim()
										.toLowerCase()
										.replace(/[^a-z0-9\s-]/g, '')
										.replace(/\s+/g, '-')
										.replace(/-+/g, '-');

									this.inputValue = sanitizedSlug;

									if ( sanitizedSlug === this.disallowedValue ) {
										this.errorMessage = '<?php esc_html_e( 'Slug not available (used by AffiliateWP).', 'rewardswp' ); ?>';
										this.setFieldError('referral_slug', this.errorMessage);
									} else if ( sanitizedSlug === '' ) {
										this.errorMessage = '<?php esc_html_e( 'Slug cannot be empty.', 'rewardswp' ); ?>';
										this.setFieldError('referral_slug', this.errorMessage);
									} else {
										this.errorMessage = '';
										this.clearFieldError('referral_slug');
									}

									return sanitizedSlug;
								}
							}"
							class="flex flex-col mt-2 xs:mt-0"
						>
							<div class="grid grid-cols-1 w-full sm:max-w-xs">
								<input
									type="text"
									id="referral_slug"
									name="rewardswp_settings[referrals][referral_slug]"
									x-model="inputValue"
									x-init="validateSlugField(inputValue)"
									x-on:input="validateSlugField($event.target.value)"
									x-bind:class="{
										'pr-10 text-red-900 outline-red-300 focus:outline-2 focus:outline-red-600': errorMessage,
										'outline-gray-300 focus:outline-2 placeholder:text-gray-400 focus:outline-blue-600': !errorMessage
									}"
									class="block w-full bg-white col-start-1 row-start-1 px-3 py-2 rounded-md text-base sm:text-sm/6 focus:-outline-offset-2 outline-1 -outline-offset-1 text-gray-900"
								>
								<span x-show="errorMessage" class="pointer-events-none col-start-1 row-start-1 mr-3 size-5 self-center justify-self-end text-red-500 sm:size-4">
									<?php echo $this->icon_helper->get_icon( 'exclamation', 'text-red-500 sm:size-4' ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
								</span>
							</div>

							<p
								x-show="errorMessage"
								class="text-red-600 text-sm mt-2"
								x-text="errorMessage"
							></p>

							<p
								x-show="!errorMessage"
								class="text-gray-500 text-sm mt-2"
							>
								<?php
								printf(
									/* translators: %s: Example referral URL */
									esc_html__( 'Referral links will look like: %s', 'rewardswp' ),
									'<span class="font-mono text-gray-700">' . esc_html( $site_url ) . '?<span x-text="inputValue"></span>=ABC123</span>'
								);
								?>
							</p>

						</div>

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

			<div class="py-5">
				<div class="gap-8 md:flex md:items-start">
					<div class="md:w-1/3 flex-none">
						<label for="cookie_expiration" class="text-sm font-semibold"><?php esc_html_e( 'Referral Cookie Duration', 'rewardswp' ); ?></label>
					</div>
					<div class="md:w-2/3">

						<div class="sm:max-w-xs mt-2 xs:mt-0 flex items-center rounded-md bg-white px-3 outline-1 -outline-offset-1 outline-gray-300 focus-within:outline-2 focus-within:-outline-offset-2 focus-within:outline-blue-600">
							<input
								id="cookie_expiration"
								type="text"
								value="<?php echo esc_attr( get_option_value( CookieExpirationOption::class ) ); ?>"
								name="rewardswp_settings[referrals][cookie_expiration]"
								class="block min-w-0 grow py-2 pr-3 text-base text-gray-900 placeholder:text-gray-400 focus:outline-none sm:text-sm/6"
								placeholder="30"
								aria-describedby="days"
							>
							<div id="days" class="shrink-0 text-base text-gray-500 select-none sm:text-sm/6"><?php esc_html_e( 'days', 'rewardswp' ); ?></div>
						</div>

						<p class="text-gray-500 text-sm mt-2">
							<?php esc_html_e( 'Enter how many days the referral tracking cookie should be valid.', 'rewardswp' ); ?>
						</p>

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

		</div>

		<?php
	}

	/**
	 * Retrieve the referral slug used by AffiliateWP.
	 *
	 * @since 1.0.0
	 *
	 * @return string
	 */
	private function get_affiliatewp_referral_var(): string {
		if ( ! function_exists( 'affiliate_wp' ) ) {
			return '';
		}

		return affiliate_wp()->tracking->get_referral_var();
	}
}
