<?php
/**
 * Template for the "Add New User and Edit User" page used by Author Kit plugin.
 * This template allows administrators to create a new user or edit a user, upload an avatar,
 * and assign user roles in WordPress.
 *
 * @package AuthorKit
 * @since 1.0.0
 * @version 1.0.0
 */

// Prevent direct access to the file if ABSPATH is not defined.
if ( ! defined( 'ABSPATH' ) ) {
	exit; // Exit if accessed directly.
}

$page_title = 'add-new' === $action_selected ? 'Create' : 'Update';

// Set default values.
$username     = $user ? $user->user_login : '';
$email        = $user ? $user->user_email : '';
$first_name   = $user ? $user->first_name : '';
$last_name    = $user ? $user->last_name : '';
$display_name = $user ? $user->display_name : '';
$role_value   = $user ? implode( ',', $user->roles ) : '';

if ( $user && metadata_exists( 'user', $user_id, 'author_kit_custom_avatar_url' ) ) {
	$avatar      = get_user_meta( $user_id, 'author_kit_custom_avatar_url', true );
	$input_value = esc_url( $avatar );  // Keep the custom avatar URL in the hidden input field.
} else {
	$avatar = get_avatar_url( $user_id, array( 'size' => 150 ) );

	// If the avatar is from Gravatar, set the hidden input value to an empty string.
	if ( strpos( $avatar, 'gravatar.com' ) !== false ) {
		$input_value = '';  // Empty the hidden input if the avatar is from Gravatar.
	} else {
		$input_value = esc_url( $avatar );  // Otherwise, keep the current avatar URL.
	}
}

?>

<div class="container">
	<div class="header">
		<!-- wp:comment --><!-- Create Account Heading -->
		<h4 id="ak-add-new-form-heading">
			<?php
			// translators: %s is the page title (e.g., 'Create' , 'Update').
			printf( esc_html__( '%s Your Account', 'author-kit' ), esc_html( $page_title ) );
			?>
			</h4>
		<p>
		<?php
			// translators: %s is the page title (e.g., 'Create' , 'Update').
			printf( esc_html__( 'Effortlessly %s a user and upload a personalized avatar for a unique profile experience', 'author-kit' ), esc_html( $page_title ) );
		?>
		</p>
	</div>

	<form class="form" method="post" action="<?php echo esc_url( admin_url( 'replace the relevant core.php if necessary ok  ' ) ); ?>" enctype="multipart/form-data">
		<!-- wp:comment --><!-- Avatar Upload Section -->
		<div class="avatar-wrapper">
			<div id="author-kit-uploader-container">
				<div id="author-kit-avatar-uploader" style="text-align: left;">
					<label for="avatar">
						<div id="author-kit-profile-avatar">
							<!-- Avatar Preview Image -->
                            <?php // phpcs:ignore PluginCheck.CodeAnalysis.ImageFunctions.NonEnqueuedImage
							echo '<img id="avatar-preview" src="' . esc_url( $avatar ) . '" alt="' . esc_attr__( 'Avatar Preview', 'author-kit' ) . '">';
							?>
							<input type="hidden" id="avatar" name="avatar" value="<?php echo esc_url( $input_value ); ?>">
						</div>
					</label>
				</div>

				<div id="remove-photo-option" style="position: relative; text-align: left;">
					<span id="upload-image-label"><?php esc_html_e( 'Click to Upload Avatar', 'author-kit' ); ?>
						<span class="tooltip" style="margin-left: 10px; color: black">
							<i class="fal fa-info-circle"></i>
							<span class="tooltiptext"><?php esc_html_e( 'Leave empty if you want to show Gravatar image associated with account\'s email.', 'author-kit' ); ?></span>
						</span>
					</span>
					<span id="remove-photo-label" style="cursor: pointer;" onclick="removePhoto()">
						<?php esc_html_e( 'Remove photo', 'author-kit' ); ?>
					</span>
				</div>
			</div>
		</div>

		<!-- wp:comment --><!-- WordPress Role Field -->
		<?php
		if ( ! ( get_current_user_id() === $user_id ) && ! is_network_admin() && current_user_can( 'promote_user' ) ) {
			$role_field_display = 'block';
		} else {
			$role_field_display = 'none';
		}

		?>

		<div class="form-group" id="author-kit-select-role" style="display: <?php echo esc_html( $role_field_display ); ?>;">
			<label><?php esc_html_e( 'Role', 'author-kit' ); ?> <span style="color: red;">*</span></label>
			<select id="role" required>
				<?php
				$roles        = wp_roles()->get_names();
				$default_role = ( 'add-new' === $action_selected ) ? 'subscriber' : $role_value;
				foreach ( $roles as $role_key => $role_name ) :
					?>
					<option value="<?php echo esc_attr( $role_key ); ?>" <?php echo selected( $role_key, $default_role, false ); ?>>
						<?php echo esc_html( $role_name ); ?>
					</option>
				<?php endforeach; ?>

			</select>

			<div class="feedback error" id="role-error" style="display: none;">
			</div>

		</div>

		<!-- wp:comment --><!-- User Name Field -->
		<div class="form-group">
			<label><?php esc_html_e( 'User Name', 'author-kit' ); ?> <span style="color: red;">*</span></label>
			<input type="text" id="username" name="username"
				value="<?php echo esc_attr( $username ); ?>"
				placeholder="<?php esc_attr_e( 'Enter your user name', 'author-kit' ); ?>"
				minlength="3" maxlength="60"
				required <?php echo 'edit' === $action_selected ? 'readonly' : ''; ?>>
			<div class="feedback error" id="username-error" style="display: none;"></div>
		</div>

		<!-- wp:comment --><!-- Email Address Field -->
		<div class="form-group" id="email-field" style="display: <?php echo 'guest' === $role_value ? 'none' : 'block'; ?>;">
			<label><?php esc_html_e( 'Email Address', 'author-kit' ); ?> <span style="color: red;">*</span></label>
			<input type="email" id="email" name="email" value="<?php echo esc_attr( $email ); ?>" placeholder="your.email@example.com" required>
			<div class="feedback error" id="email-error" style="display: none;">
			</div>
		</div>

		<!-- wp:comment --><!-- First Name Field -->
		<div class="form-group">
			<label><?php esc_html_e( 'First Name', 'author-kit' ); ?></label>
			<input type="text" id="first-name" name="first_name" value="<?php echo esc_attr( $first_name ); ?>" placeholder="<?php esc_attr_e( 'First Name', 'author-kit' ); ?>" maxlength="50">
			<div class="feedback error" id="first-name-error" style="display: none;">
			</div>
		</div>

		<!-- wp:comment --><!-- Last Name Field -->
		<div class="form-group">
			<label><?php esc_html_e( 'Last Name', 'author-kit' ); ?></label>
			<input type="text" id="last-name" name="last_name" value="<?php echo esc_attr( $last_name ); ?>" placeholder="<?php esc_attr_e( 'Last Name', 'author-kit' ); ?>" maxlength="50">
			<div class="feedback error" id="last-name-error" style="display: none;">
			</div>
		</div>

		<!-- wp:comment --><!-- Display Name Field -->
		<?php if ( 'edit' === $action_selected ) : ?>
			<div class="form-group" id="author-kit-select-role">
				<label for="display-name"><?php esc_html_e( 'Display Name:', 'author-kit' ); ?></label>
				<select id="display-name" required>
					<?php
					$public_display                     = array();
					$public_display['display_nickname'] = $user->nickname;
					$public_display['display_username'] = $user->user_login;

					if ( ! empty( $user->first_name ) ) {
						$public_display['display_firstname'] = $user->first_name;
					}

					if ( ! empty( $user->last_name ) ) {
						$public_display['display_lastname'] = $user->last_name;
					}

					if ( ! empty( $user->first_name ) && ! empty( $user->last_name ) ) {
						$public_display['display_firstlast'] = $user->first_name . ' ' . $user->last_name;
						$public_display['display_lastfirst'] = $user->last_name . ' ' . $user->first_name;
					}

					if ( ! in_array( $user->display_name, $public_display, true ) ) { // Only add this if it isn't duplicated elsewhere.
						$public_display = array( 'display_displayname' => $user->display_name ) + $public_display;
					}

					$public_display = array_map( 'trim', $public_display );
					$public_display = array_unique( $public_display );

					?>
					<?php foreach ( $public_display as $id_value => $item ) : ?>
						<option value="<?php echo esc_attr( $item ); ?>" <?php selected( $user->display_name, $item ); ?>><?php echo esc_html( $item ); ?></option>
					<?php endforeach; ?>
				</select>
				<div class="feedback error" id="display-name-error" style="display: none;">
				</div>
			</div>
		<?php endif; ?>


		<!-- wp:comment --><!-- Password Field -->
		<div class="form-group" id="password-field" style="display: <?php echo 'guest' === $role_value ? 'none' : 'block'; ?>;">
			<?php $password_title = 'add-new' === $action_selected ? esc_html__( 'Create', 'author-kit' ) : esc_html__( 'Change', 'author-kit' ); ?>
			<label>
				<?php
				// translators: %s is the password title (e.g., 'Create' , 'Change').
				printf( esc_html__( '%s Password', 'author-kit' ), esc_html( $password_title ) );
				?>
				<span style="color: red;"><?php echo 'add-new' === $action_selected ? '*' : ''; ?></span>
			</label>
			<!-- Wrapper around the input so we can position the toggle icon inside it -->
			<div class="password-wrapper" style="position: relative;">
				<!-- Password input field -->
				<input 
					type="password" 
					id="password"
					<?php echo 'add-new' === $action_selected ? 'required' : ''; ?> 
					minlength="8" 
					pattern="^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{8,}$"
					style="padding-right: 35px;" 
				>
				
				<!-- Toggle icon (eye). It's placed absolutely inside the input wrapper -->
				<span 
					class="toggle-password" 
					style="position: absolute; right: 10px; top: 50%; transform: translateY(-50%); cursor: pointer; user-select: none;">
					<i class="fa-solid fa-eye"></i>
				</span>
			</div>
			<div class="feedback error" id="password-error" style="display: none;">
			</div>
		</div>

		<!-- wp:comment --><!-- Send Email Checkbox -->
		<?php if ( 'edit' !== $action_selected ) : ?>
			<div class="checkbox-group" id="send-email-group">
				<input type="checkbox" id="send-email" checked>
				<p><?php esc_html_e( 'Send the new user an email about their account', 'author-kit' ); ?></p>
			</div>
		<?php endif; ?>

		<!-- wp:comment --><!-- User Action -->
		<input type="hidden" id="user-action" name="user-action" value="<?php echo esc_html( $action_selected ); ?>">

		<?php if ( 'edit' === $action_selected ) : ?>
			<input type="hidden" id="user-id" name="user-id" value="<?php echo esc_html( $user_id ); ?>">
		<?php endif; ?>


		<!-- wp:comment --><!-- Submit Button -->
		<button type="submit" id="add-new-user-button" class="btn-primary">
			<?php
			// translators: %s is the page title (e.g., 'Create' , 'Update').
			printf( esc_html__( '%s User', 'author-kit' ), esc_html( $page_title ) );
			?>
		</button>
	</form>
</div>
