<?php

/**
 * Template for editing an author profile.
 *
 * This template handles rendering the author profile edit form, including fields for
 * author details, social profiles, and author schema. The form will be submitted
 * to the server for updating the profile.
 *
 * @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.
}

global $author_kit_coauthors;

$user = get_userdata($user_id);

if ($user) {

	if (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.
		}
	}

	$enable_author_schema = metadata_exists('user', $user_id, 'author_kit_author_schema')
		? boolval(get_user_meta($user_id, 'author_kit_author_schema', true))
		: false;

	$contact_email = metadata_exists('user', $user_id, 'author_kit_user_contact_email')
		? get_user_meta($user_id, 'author_kit_user_contact_email', true)
		: '';

	$company = metadata_exists('user', $user_id, 'author_kit_user_company')
		? get_user_meta($user_id, 'author_kit_user_company', true)
		: '';

	$job_title = metadata_exists('user', $user_id, 'author_kit_author_job_title')
		? get_user_meta($user_id, 'author_kit_author_job_title', true)
		: '';

	$link_preference = metadata_exists('user', $user_id, 'author_kit_name_link_preference')
		? get_user_meta($user_id, 'author_kit_name_link_preference', true)
		: 'author_archive';

	$checked_author_schema = $enable_author_schema ? 'checked' : '';

	$custom_url_value = 'custom_url' === $link_preference && metadata_exists('user', $user_id, 'author_kit_custom_url')
		? get_user_meta($user_id, 'author_kit_custom_url', true)
		: '';

	// Prepare user data.
	$user_data = array(
		'first_name'         => $user->first_name,
		'last_name'          => $user->last_name,
		'nickname'           => $user->nickname,
		'avatar'             => $avatar,
		'display_name'       => $user->display_name,
		'author_description' => $user->description,
		'website'            => $user->user_url,
		'job_title'          => $job_title,
	);
} else {
	wp_die(esc_html__('User not found', 'author-kit'));
	exit;
}


?>

<div id="author-kit-edit-author-profile">
	<div id="author-kit-page-template">
		<aside>
			<h4 id="edit-author-heading"><?php esc_html_e('Edit Profile', 'author-kit'); ?></h4>
			<section class="sidebar-link" data-target="details">
				<i class="fa-regular fa-circle-user"></i><?php esc_html_e('Author Details', 'author-kit'); ?>
			</section>
			<section class="sidebar-link" data-target="social">
				<i class="fa-regular fa-thumbs-up"></i><?php esc_html_e('Social Profiles', 'author-kit'); ?>
			</section>
		</aside>
		<main>
			<div id="author-kit-link-to-author-profiles">
				<a href="admin.php?page=author-kit-author-profiles" class="breadcrumb-button">
					<i class="fas fa-arrow-left"></i> <?php esc_html_e('Back to Author Profiles', 'author-kit'); ?>
				</a>
			</div>
			<div id="details" class="content-section">
				<h4 id="author-kit-author-details"><?php esc_html_e('Author Details', 'author-kit'); ?></h4>
				<form method="post" id="add-user-form" enctype="multipart/form-data">
					<!-- Circular Avatar Upload -->
					<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;">
							<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>

					<!-- Display Name Field -->
					<label for="display-name"><?php esc_html_e('Display Name:', 'author-kit'); ?></label>
					<select id="display-name" name="display_name">
						<?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>
					<br>

					<input type="hidden" id="ID" name="ID" value="<?php echo esc_html($user_id); ?>">


					<!-- First Name -->
					<label for="first-name"><?php esc_html_e('First Name:', 'author-kit'); ?></label>
					<input type="text" id="first-name" name="first_name" value="<?php echo esc_attr($user_data['first_name']); ?>" maxlength="50">
					<span class="error-message" id="error-first-name"></span>
					<br>

					<!-- Last Name -->
					<label for="last-name"><?php esc_html_e('Last Name:', 'author-kit'); ?></label>
					<input type="text" id="last-name" name="last_name" value="<?php echo esc_attr($user_data['last_name']); ?>" maxlength="50">
					<span class="error-message" id="error-last-name"></span>
					<br>

					<!-- Contact Email -->
					<label for="contact-email"><?php esc_html_e('Contact Email:', 'author-kit'); ?></label>
					<input type="email" id="contact-email" name="contact_email" value="<?php echo esc_attr($contact_email); ?>" placeholder="abc@example.com">
					<span class="error-message" id="error-contact-email"></span>
					<br>

					<!-- Last Name -->
					<label for="company"><?php esc_html_e('Company:', 'author-kit'); ?></label>
					<input type="text" id="company" name="company" value="<?php echo esc_attr($company); ?>" maxlength="50">
					<span class="error-message" id="error-company"></span>
					<br>

					<!-- Nick Name -->
					<input type="hidden" id="nickname" name="nickname" value="<?php echo esc_attr($user_data['nickname']); ?>" required>

					<!-- Job Title -->
					<label for="job-title"><?php esc_html_e('Job Title:', 'author-kit'); ?></label>
					<input type="text" id="job-title" name="job_title" value="<?php echo esc_attr($user_data['job_title']); ?>" maxlength="50">
					<div class="error-message" id="error-job-title"></div>
					<br>


					<!-- Website -->
					<label for="website"><?php esc_html_e('Website:', 'author-kit'); ?></label>
					<input type="url" id="website" name="website" value="<?php echo esc_attr($user_data['website']); ?>">
					<span class="error-message" id="error-website"></span>
					<br>

					<!-- Bio Description -->
					<label for="bio"><?php esc_html_e('Bio Description:', 'author-kit'); ?></label>
					<?php
					$description_content = $user_data['author_description'];
					$editor_settings     = array(
						'media_buttons' => false, // This setting removes the media button.
						'textarea_name' => 'description', // Set custom name.
						'textarea_rows' => 5, // Determine the number of rows.
						'teeny'         => false,
						'quicktags'     => true, // Remove view as HTML button.
					);

					wp_editor($description_content, 'description', $editor_settings)

					?>
					<span class="error-message" id="error-bio"></span>
					<br>

					<!-- Link Author Name -->
					<label for="link-options"><?php esc_html_e('Link Author Name to:', 'author-kit'); ?></label>
					<div id="link-options">
						<label>
							<input type="radio" name="link_type" value="author_archive" <?php echo 'author_archive' === $link_preference ? 'checked' : ''; ?>>
							<?php esc_html_e('Archive Page', 'author-kit'); ?>
						</label>
						<label>
							<input type="radio" name="link_type" value="home_page" <?php echo 'home_page' === $link_preference ? 'checked' : ''; ?>>
							<?php esc_html_e('Home Page', 'author-kit'); ?>
						</label>
						<label>
							<input type="radio" name="link_type" value="custom_url" <?php echo 'custom_url' === $link_preference ? 'checked' : ''; ?>>
							<?php esc_html_e('Custom URL', 'author-kit'); ?>
						</label>
						<input type="url" id="custom-url" name="custom_url" value="<?php echo esc_attr($custom_url_value); ?>" placeholder="<?php esc_attr_e('Enter custom URL', 'author-kit'); ?>" style="display: <?php echo 'custom_url' === $link_preference ? 'block' : 'none'; ?>; margin: 20px 0;">
						<span class="error-message" id="error-custom-url"></span>
					</div>
					<br>

					<!-- Update Button -->
					<button id="author-kit-update-button-1" type="submit" class="author-kit-update-button">
						<?php esc_html_e('Update Profile', 'author-kit'); ?>
					</button>
				</form>
			</div>

			<!-- Social Section -->
			<div id="social" class="content-section" style="display: none;">
				<h4 id="author-kit-social-profile-heading">
					<?php esc_html_e('Social Profiles', 'author-kit'); ?>
				</h4>
				<?php
				// Fetch selected platforms from transient; fallback to options if not found or invalid.
				$selected_platforms_meta = get_transient('author_kit_selected_platforms_meta');
				if (! is_array($selected_platforms_meta)) {
					$selected_platforms_meta = get_option('author_kit_selected_platforms_meta', array());
					if (! is_array($selected_platforms_meta)) {
						$selected_platforms_meta = array();
					}
					set_transient('author_kit_selected_platforms_meta', $selected_platforms_meta, HOUR_IN_SECONDS);
				}

				$selected_platforms_keys = array_keys($selected_platforms_meta);

				// Retrieve saved social profiles.
				$saved_profiles = get_user_meta($user_id, 'author_kit_user_social_profiles', true);
				$saved_profiles = is_array($saved_profiles) ? $saved_profiles : array();

				// Merge saved URLs into meta.
				foreach ($selected_platforms_meta as $platform_key => &$platform_meta) {
					$platform_meta['url'] = $saved_profiles[$platform_key] ?? '';
				}
				unset($platform_meta); // Clean reference.

				// Sort platforms so filled URLs appear first.
				uasort(
					$selected_platforms_meta,
					function ($a, $b) {
						return (! empty($b['url']) ? 1 : 0) <=> (! empty($a['url']) ? 1 : 0);
					}
				);
				?>

				<div class="author-kit-container">
					<form id="author-kit-social-form" method="post" action="">
						<?php wp_nonce_field('author_kit_social_profiles_nonce'); ?>

						<input type="hidden" id="social-platforms-keys" value="<?php echo esc_attr(wp_json_encode($selected_platforms_keys)); ?>" />

						<?php foreach ($selected_platforms_meta as $platform_key => $platform) : ?>
							<div class="author-kit-social-card">
								<div class="author-kit-icon" style="background-color: <?php echo esc_attr($platform['color'] ?? '#999'); ?>;">
									<i class="<?php echo esc_attr(! empty($platform['fa_icon']) ? $platform['fa_icon'] : 'fab fa-' . esc_attr($platform_key)); ?>"></i>
								</div>
								<div class="author-kit-social-name">
									<?php echo esc_html($platform['name'] ?? ucfirst($platform_key)); ?>
								</div>
								<input
									type="url"
									id="<?php echo esc_attr($platform_key); ?>"
									name="author_kit_social_profiles[<?php echo esc_attr($platform_key); ?>][url]"
									placeholder="<?php
									printf(
										// translators: %s is the platform name (e.g., Facebook, Twitter).
										esc_html__('Enter %s URL', 'author-kit'),
										esc_html($platform['name'] ?? ucfirst($platform_key))
									);
									?>"
									class="author-kit-url-input"
									value="<?php echo esc_url($platform['url']); ?>" />
							</div>

						<?php endforeach; ?>
					</form>

					<div class="social-platform-select-notice">
						<?php
						printf(
							// translators: %1$s and %3$s are opening tags and %2$s and %4$s are closing tags.
							esc_html__('Select more platforms by going to %1$sSettings%2$s > General Settings > %3$sSocial Platforms%4$s', 'author-kit'),
							'<strong>',
							'</strong>',
							'<strong>',
							'</strong>'
						);
						?>
						<br>
						<strong><?php esc_html_e('Author Kit offers all major social Platforms', 'author-kit'); ?></strong>
					</div>

					<div class="author-kit-button-container">
						<button id="author-kit-update-button-2" type="submit" form="author-kit-social-form" class="author-kit-update-button">
							<?php esc_html_e('Update Profile', 'author-kit'); ?>
						</button>
					</div>
				</div>
			</div>

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