<?php
/**
 * Edit member modal view.
 *
 * @package Awesomemotive\Rewardswp\Views\Admin\Modals
 * @since 1.0.0
 */

namespace Awesomemotive\Rewardswp\Views\Admin\Modals;

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

use Awesomemotive\Rewardswp\Abstracts\AbstractView;
use Awesomemotive\Rewardswp\Helpers\IconHelper;
use Awesomemotive\Rewardswp\Interfaces\ViewInterface;
use Awesomemotive\Rewardswp\Models\Member;
use function Awesomemotive\Rewardswp\Helpers\get_minimum_required_plan_for_feature;
use function Awesomemotive\Rewardswp\Helpers\get_upgrade_url;
use function Awesomemotive\Rewardswp\Helpers\get_view_component;
use function Awesomemotive\Rewardswp\Helpers\kses;
use function Awesomemotive\Rewardswp\Helpers\svg_kses;

class EditMemberModalView extends AbstractView implements ViewInterface {
	/**
	 * Icon helper instance.
	 *
	 * @var IconHelper
	 */
	private IconHelper $icon_helper;

	/**
	 * Constructor.
	 *
	 * @param IconHelper $icon_helper
	 */
	public function __construct( IconHelper $icon_helper ) {
		$this->icon_helper = $icon_helper;
	}

	/**
	 * Render the template.
	 *
	 * @param array $args {
	 *     Required. An array of arguments.
	 *
	 *     @type Member $member The Member object.
	 *     @type string $nonce  Nonce for AJAX actions.
	 * }
	 *
	 * @return void
	 */
	public function render( array $args = [] ): void {
		if ( ! isset( $args['member'] ) || ! $args['member'] instanceof Member || ! isset( $args['nonce'] ) ) {
			return;
		}

		/**
		 * Member instance.
		 *
		 * @var Member $member
		 */
		$member    = $args['member'];
		$nonce     = sanitize_text_field( $args['nonce'] );
		$member_id = $member->id;

		// Parse existing birthday into month/day.
		$birthday              = $member->get_meta( 'birthday' );
		$initial_birthday_month = '';
		$initial_birthday_day   = '';
		if ( ! empty( $birthday ) ) {
			$parts = explode( '-', $birthday );
			if ( count( $parts ) === 2 ) {
				$initial_birthday_month = (string) (int) $parts[0];
				$initial_birthday_day   = (string) (int) $parts[1];
			}
		}

		$alpine_params = [
			'memberId'             => $member_id,
			'ajaxNonce'            => $nonce,
			'ajaxurl'              => admin_url( 'admin-ajax.php' ),
			'initialFullName'      => $member->get_full_name(),
			'initialEmail'         => $member->email,
			'initialBirthdayMonth' => $initial_birthday_month,
			'initialBirthdayDay'   => $initial_birthday_day,
			'text'                 => [
				'modalTitle'                    => __( 'Edit Member', 'rewardswp' ),
				'modalDescription'              => __( 'Update member information and settings', 'rewardswp' ),
				'labelFullName'                 => __( 'Name', 'rewardswp' ),
				'validationErrorFullNameFormat' => __( 'Please enter both first and last name.', 'rewardswp' ),
				'labelEmail'                    => __( 'Email', 'rewardswp' ),
				'labelBirthday'                 => __( 'Birthday', 'rewardswp' ),
				'birthdayMonth'                 => __( 'Month', 'rewardswp' ),
				'birthdayDay'                   => __( 'Day', 'rewardswp' ),
				'buttonCancel'                  => __( 'Cancel', 'rewardswp' ),
				'buttonSaveChanges'             => __( 'Save Changes', 'rewardswp' ),
				'genericError'                  => __( 'An unknown error occurred. Please try again.', 'rewardswp' ),
				'networkError'                  => __( 'A network error occurred. Please try again.', 'rewardswp' ),
				'memberUpdateSuccess'           => __( 'Member details updated successfully.', 'rewardswp' ),
				'validationError'               => __( 'Please check the highlighted fields.', 'rewardswp' ),
			],
			'months'               => [
				[ 'value' => '1', 'label' => __( 'January', 'rewardswp' ) ],
				[ 'value' => '2', 'label' => __( 'February', 'rewardswp' ) ],
				[ 'value' => '3', 'label' => __( 'March', 'rewardswp' ) ],
				[ 'value' => '4', 'label' => __( 'April', 'rewardswp' ) ],
				[ 'value' => '5', 'label' => __( 'May', 'rewardswp' ) ],
				[ 'value' => '6', 'label' => __( 'June', 'rewardswp' ) ],
				[ 'value' => '7', 'label' => __( 'July', 'rewardswp' ) ],
				[ 'value' => '8', 'label' => __( 'August', 'rewardswp' ) ],
				[ 'value' => '9', 'label' => __( 'September', 'rewardswp' ) ],
				[ 'value' => '10', 'label' => __( 'October', 'rewardswp' ) ],
				[ 'value' => '11', 'label' => __( 'November', 'rewardswp' ) ],
				[ 'value' => '12', 'label' => __( 'December', 'rewardswp' ) ],
			],
		];

		?>
		<div
			x-data="editMemberModal(<?php echo esc_attr( wp_json_encode( $alpine_params ) ); ?>)"
			x-show="showModal"
			x-trap.inert.noscroll="showModal"
			class="fixed inset-x-0 z-50 overflow-y-auto" style="top: var(--wp-admin--admin-bar--height, 32px); height: calc(100vh - var(--wp-admin--admin-bar--height, 32px))"
			aria-labelledby="edit-member-modal-title"
			role="dialog"
			aria-modal="true"
			x-cloak
			x-on:keydown.escape.window="closeModal()"
		>
			<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="showModal"
					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-x-0 transition-opacity z-40" style="top: var(--wp-admin--admin-bar--height, 32px); height: calc(100vh - var(--wp-admin--admin-bar--height, 32px))"
					x-on:click="closeModal()"
					aria-hidden="true"
				>
					<div class="absolute inset-0 bg-slate-900/40"></div>
				</div>

				<!-- Modal panel -->
				<span class="hidden sm:inline-block sm:align-middle sm:h-screen" aria-hidden="true">&#8203;</span>
				<div
					x-show="showModal"
					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="inline-block align-bottom bg-white rounded-lg text-left overflow-hidden shadow-xl transform transition-all sm:my-8 sm:align-middle sm:max-w-lg sm:w-full z-50"
				>
					<div class="bg-white px-4 pt-5 pb-4 sm:p-6 sm:pb-4">
						<div class="flex justify-between items-start">
							<div>
								<h3 class="text-lg leading-6 font-medium text-gray-900" id="edit-member-modal-title" x-text="text.modalTitle"></h3>
								<p class="text-sm text-gray-500 mt-1" x-text="text.modalDescription"></p>
							</div>
							<button type="button" x-on:click="closeModal()" class="text-gray-400 hover:text-gray-500">
								<?php echo wp_kses( $this->icon_helper->get_icon( 'close', 'w-6 h-6' ), svg_kses() ); ?>
							</button>
						</div>

						<div class="mt-5 space-y-6">
							<!-- Full Name -->
							<div>
								<label for="edit_member_full_name" class="block text-sm font-medium text-gray-700" x-text="text.labelFullName"></label>
								<div class="mt-1">
									<input
										type="text"
										name="edit_member_full_name"
										id="edit_member_full_name"
										x-model="editableFullName"
										class="block w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
										x-bind:class="{ 'border-red-500 focus:ring-red-500 focus:border-red-500': errors.fullName }"
										x-on:input="errors.fullName = ''; generalError = ''"
									>
								</div>
								<template x-if="errors.fullName">
									<p class="mt-2 text-sm text-red-600" x-text="errors.fullName"></p>
								</template>
							</div>

							<!-- Email -->
							<div>
								<label for="edit_member_email" class="block text-sm font-medium text-gray-700" x-text="text.labelEmail"></label>
								<div class="mt-1">
									<input
										type="email"
										name="edit_member_email"
										id="edit_member_email"
										x-model="editableEmail"
										class="block w-full px-3 py-2 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500 sm:text-sm"
										x-bind:class="{ 'border-red-500 focus:ring-red-500 focus:border-red-500': errors.email }"
										x-on:input="errors.email = ''; generalError = ''"
									>
								</div>
								<template x-if="errors.email">
									<p class="mt-2 text-sm text-red-600" x-text="errors.email"></p>
								</template>
							</div>

							<!-- Birthday -->
							<?php
							$wp_date_format = get_option( 'date_format', 'F j, Y' );
							$day_first      = (bool) preg_match( '/^[jd]/', $wp_date_format );
							$select_classes = 'col-start-1 row-start-1 block w-full appearance-none px-3 py-2 pr-8 border border-gray-300 rounded-md focus:ring-blue-500 focus:border-blue-500 sm:text-sm';
							$error_classes  = "{ 'border-red-500 focus:ring-red-500 focus:border-red-500': errors.birthday }";
							$chevron_svg    = '<svg class="pointer-events-none col-start-1 row-start-1 mr-2 size-4 self-center justify-self-end text-gray-500" viewBox="0 0 16 16" fill="currentColor" aria-hidden="true"><path fill-rule="evenodd" d="M4.22 6.22a.75.75 0 0 1 1.06 0L8 8.94l2.72-2.72a.75.75 0 1 1 1.06 1.06l-3.25 3.25a.75.75 0 0 1-1.06 0L4.22 7.28a.75.75 0 0 1 0-1.06Z" clip-rule="evenodd" /></svg>';

							$disabled_select_classes = 'col-start-1 row-start-1 block w-full appearance-none px-3 py-2 pr-8 border border-gray-300 rounded-md sm:text-sm bg-gray-50 text-gray-500 pointer-events-none opacity-60';
							?>
							<div>
								<label class="flex text-sm font-medium text-gray-700 items-center gap-2">
									<span x-text="text.labelBirthday"></span>
									<template x-if="!$store.config.canAccess('earn_birthday')">
										<?php
										echo wp_kses(
											get_view_component(
												'badge',
												[
													'style' => 'pro',
												]
											),
											kses()
										);
										?>
									</template>
								</label>

								<!-- Upsell: Disabled birthday fields for plans without birthday access -->
								<template x-if="!$store.config.canAccess('earn_birthday')">
									<div>
										<p class="mt-1 text-sm text-gray-500">
											<?php esc_html_e( 'Collect member birthdays and automatically reward them with bonus points each year.', 'rewardswp' ); ?>
										</p>
										<div class="mt-2 grid gap-3 grid-cols-2">
											<?php if ( $day_first ) : ?>
											<div class="grid grid-cols-1">
												<select disabled class="<?php echo esc_attr( $disabled_select_classes ); ?>">
													<option x-text="editableBirthdayDay || '<?php esc_attr_e( 'Day', 'rewardswp' ); ?>'"></option>
												</select>
												<?php echo $chevron_svg; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
											</div>
											<?php endif; ?>
											<div class="grid grid-cols-1">
												<select disabled class="<?php echo esc_attr( $disabled_select_classes ); ?>">
													<option x-text="editableBirthdayMonth ? months.find(m => m.value === editableBirthdayMonth)?.label : '<?php esc_attr_e( 'Month', 'rewardswp' ); ?>'"></option>
												</select>
												<?php echo $chevron_svg; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
											</div>
											<?php if ( ! $day_first ) : ?>
											<div class="grid grid-cols-1">
												<select disabled class="<?php echo esc_attr( $disabled_select_classes ); ?>">
													<option x-text="editableBirthdayDay || '<?php esc_attr_e( 'Day', 'rewardswp' ); ?>'"></option>
												</select>
												<?php echo $chevron_svg; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
											</div>
											<?php endif; ?>
										</div>
										<p class="text-sm text-gray-600 mt-3">
											<a
												href="<?php echo esc_url( add_query_arg( 'feature', 'earn_birthday', get_upgrade_url( 'unlock_birthday_rewards', 'member-modal', get_minimum_required_plan_for_feature( 'earn_birthday' ), 'earn_birthday' ) ) ); ?>"
												target="_blank"
												rel="noopener noreferrer"
												class="inline-flex items-center gap-1.5 text-blue-600 hover:text-blue-700"
											>
												<?php esc_html_e( 'Upgrade to unlock birthday rewards', 'rewardswp' ); ?>
												<?php echo wp_kses( $this->icon_helper->get_icon( 'external-link', 'h-4 w-4' ), svg_kses() ); ?>
											</a>
										</p>
									</div>
								</template>

								<!-- Pro: Working birthday fields -->
								<template x-if="$store.config.canAccess('earn_birthday')">
									<div>
										<div class="mt-1 grid gap-3 grid-cols-2">
											<?php if ( $day_first ) : ?>
											<div class="grid grid-cols-1">
												<select
													x-model="editableBirthdayDay"
													class="<?php echo esc_attr( $select_classes ); ?>"
													x-bind:class="<?php echo esc_attr( $error_classes ); ?>"
													x-on:change="errors.birthday = ''; generalError = ''"
												>
													<option value="" x-text="text.birthdayDay"></option>
													<template x-for="d in daysInMonth" :key="d">
														<option :value="d" :selected="String(d) === editableBirthdayDay" x-text="d"></option>
													</template>
												</select>
												<?php echo $chevron_svg; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
											</div>
											<?php endif; ?>
											<div class="grid grid-cols-1">
												<select
													x-model="editableBirthdayMonth"
													class="<?php echo esc_attr( $select_classes ); ?>"
													x-bind:class="<?php echo esc_attr( $error_classes ); ?>"
													x-on:change="errors.birthday = ''; generalError = ''"
												>
													<option value="" x-text="text.birthdayMonth"></option>
													<template x-for="m in months" :key="m.value">
														<option :value="m.value" :selected="m.value === editableBirthdayMonth" x-text="m.label"></option>
													</template>
												</select>
												<?php echo $chevron_svg; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
											</div>
											<?php if ( ! $day_first ) : ?>
											<div class="grid grid-cols-1">
												<select
													x-model="editableBirthdayDay"
													class="<?php echo esc_attr( $select_classes ); ?>"
													x-bind:class="<?php echo esc_attr( $error_classes ); ?>"
													x-on:change="errors.birthday = ''; generalError = ''"
												>
													<option value="" x-text="text.birthdayDay"></option>
													<template x-for="d in daysInMonth" :key="d">
														<option :value="d" :selected="String(d) === editableBirthdayDay" x-text="d"></option>
													</template>
												</select>
												<?php echo $chevron_svg; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?>
											</div>
											<?php endif; ?>
										</div>
										<template x-if="errors.birthday">
											<p class="mt-2 text-sm text-red-600" x-text="errors.birthday"></p>
										</template>
									</div>
								</template>
							</div>

							<template x-if="generalError">
								<p class="mt-2 text-sm text-red-600" x-text="generalError"></p>
							</template>
						</div>
					</div>
					<div class="bg-gray-50 px-4 py-3 sm:px-6 sm:flex sm:flex-row-reverse">
						<button
							type="button"
							x-on:click="handleSaveChanges()"
							x-bind:disabled="isLoading || !isDirty() || hasErrors()"
							class="w-full inline-flex justify-center rounded-md border border-transparent shadow-sm px-4 py-2 bg-blue-600 text-base font-medium text-white hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 sm:ml-3 sm:w-auto sm:text-sm disabled:opacity-60 disabled:cursor-not-allowed"
						>
							<span x-show="!isLoading" x-text="text.buttonSaveChanges"></span>
							<span x-show="isLoading">
								<?php echo wp_kses( $this->icon_helper->get_icon( 'loader', 'animate-spin -ml-1 mr-3 h-5 w-5 text-white' ), svg_kses() ); ?>
								<?php esc_html_e( 'Saving...', 'rewardswp' ); ?>
							</span>
						</button>
						<button
							type="button"
							x-on:click="closeModal()"
							class="mt-3 w-full 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-blue-500 sm:mt-0 sm:w-auto sm:text-sm"
						>
							<span x-text="text.buttonCancel"></span>
						</button>
					</div>
				</div>
			</div>
		</div>
		<?php
	}
}
