<?php
/**
 * Ansico WP Theme functions.
 *
 * @package Ansico_WP_Theme
 */

if ( ! function_exists( 'ansico_wp_theme_setup' ) ) {
	function ansico_wp_theme_setup() {
		add_editor_style( 'style.css' );
	}
}
add_action( 'after_setup_theme', 'ansico_wp_theme_setup' );

function ansico_wp_theme_enqueue_assets() {
	wp_enqueue_style(
		'ansico-wp-theme-style',
		get_stylesheet_uri(),
		array(),
		wp_get_theme()->get( 'Version' )
	);
}
add_action( 'wp_enqueue_scripts', 'ansico_wp_theme_enqueue_assets' );


if ( ! function_exists( 'ansico_author_intro_shortcode' ) ) {
	function ansico_author_intro_shortcode() {
		if ( ! is_author() ) {
			return '';
		}

		$author = get_queried_object();
		if ( ! $author || empty( $author->ID ) ) {
			return '';
		}

		$author_id   = (int) $author->ID;
		$name        = get_the_author_meta( 'display_name', $author_id );
		$description = get_the_author_meta( 'description', $author_id );
		$user_url    = get_the_author_meta( 'user_url', $author_id );
		$avatar      = function_exists( 'ansico_get_author_avatar_html' ) ? ansico_get_author_avatar_html( $author_id, 120, esc_attr( $name ) ) : get_avatar( $author_id, 120, '', esc_attr( $name ), array( 'class' => 'ansico-author-intro__avatar-image' ) );

		$output  = '<div class="ansico-author-intro">';
		$output .= '<div class="ansico-author-intro__avatar">' . $avatar . '</div>';
		$output .= '<div class="ansico-author-intro__content">';
		$output .= '<h1 class="ansico-author-intro__name">' . esc_html( $name ) . '</h1>';

		if ( ! empty( $description ) ) {
			$output .= '<div class="ansico-author-intro__bio">' . wpautop( wp_kses_post( $description ) ) . '</div>';
		}

		if ( ! empty( $user_url ) ) {
			$output .= '<p class="ansico-author-intro__website"><a href="' . esc_url( $user_url ) . '" rel="me noopener noreferrer">' . esc_html( $user_url ) . '</a></p>';
		}

		$output .= '</div></div>';

		return $output;
	}
}
add_shortcode( 'ansico_author_intro', 'ansico_author_intro_shortcode' );


if ( ! function_exists( 'ansico_get_social_networks_v2' ) ) {
	function ansico_get_social_networks_v2() {
		return array(
			'facebook'  => array( 'label' => 'Facebook',  'icon' => 'f' ),
			'linkedin'  => array( 'label' => 'LinkedIn',  'icon' => 'in' ),
			'instagram' => array( 'label' => 'Instagram', 'icon' => '◎' ),
			'bluesky'   => array( 'label' => 'Bluesky',   'icon' => '☁' ),
			'twitter'   => array( 'label' => 'Twitter/X', 'icon' => '𝕏' ),
			'mastodon'  => array( 'label' => 'Mastodon',  'icon' => 'm' ),
			'friendica' => array( 'label' => 'Friendica', 'icon' => 'F' ),
			'reddit'    => array( 'label' => 'Reddit',    'icon' => 'r' ),
		);
	}
}





if ( ! function_exists( 'ansico_format_profile_url_for_display_v2' ) ) {
	function ansico_format_profile_url_for_display_v2( $url ) {
		$url = trim( (string) $url );
		$url = preg_replace( '#^https?://#i', '', $url );
		return untrailingslashit( $url );
	}
}

if ( ! function_exists( 'ansico_get_author_social_links_v2' ) ) {
	function ansico_get_author_social_links_v2( $author_id ) {
		$networks = ansico_get_social_networks_v2();
		$output   = '';

		foreach ( $networks as $key => $network ) {
			$url  = get_user_meta( $author_id, 'ansico_' . $key, true );
			$show = get_user_meta( $author_id, 'ansico_show_' . $key, true );

			if ( empty( $url ) || '1' !== (string) $show ) {
				continue;
			}

			$output .= '<a class="ansico-author-intro__social" href="' . esc_url( $url ) . '" rel="me noopener noreferrer" target="_blank" title="' . esc_attr( $network['label'] ) . '" aria-label="' . esc_attr( $network['label'] ) . '">';
			$output .= '<span aria-hidden="true">' . esc_html( $network['icon'] ) . '</span>';
			$output .= '<span class="ansico-author-intro__social-label">' . esc_html( $network['label'] ) . '</span>';
			$output .= '</a>';
		}

		if ( empty( $output ) ) {
			return '';
		}

		return '<div class="ansico-author-intro__socials">' . $output . '</div>';
	}
}

if ( ! function_exists( 'ansico_author_intro_shortcode_v2' ) ) {
	function ansico_author_intro_shortcode_v2() {
		if ( ! is_author() ) {
			return '';
		}

		$author = get_queried_object();
		if ( ! $author || empty( $author->ID ) ) {
			return '';
		}

		$author_id   = (int) $author->ID;
		$name        = get_the_author_meta( 'display_name', $author_id );
		$description = get_the_author_meta( 'description', $author_id );
		$user_url    = get_the_author_meta( 'user_url', $author_id );
		$avatar      = function_exists( 'ansico_get_author_avatar_html' ) ? ansico_get_author_avatar_html( $author_id, 120, esc_attr( $name ) ) : get_avatar( $author_id, 120, '', esc_attr( $name ), array( 'class' => 'ansico-author-intro__avatar-image' ) );
		$socials     = ansico_get_author_social_links_v2( $author_id );

		$output  = '<div class="ansico-author-intro">';
		$output .= '<div class="ansico-author-intro__avatar">' . $avatar . '</div>';
		$output .= '<div class="ansico-author-intro__content">';
		$output .= '<h1 class="ansico-author-intro__name">' . esc_html( $name ) . '</h1>';

		if ( ! empty( $description ) ) {
			$output .= '<div class="ansico-author-intro__bio">' . wpautop( wp_kses_post( $description ) ) . '</div>';
		}

		if ( ! empty( $user_url ) ) {
			$output .= '<p class="ansico-author-intro__website"><a href="' . esc_url( $user_url ) . '" rel="me noopener noreferrer">' . esc_html( ansico_format_profile_url_for_display_v2( $user_url ) ) . '</a></p>';
		}

		$output .= $socials;
		$output .= '</div></div>';

		return $output;
	}
	add_shortcode( 'ansico_author_intro_v2', 'ansico_author_intro_shortcode_v2' );
}


if ( ! function_exists( 'ansico_get_author_avatar_html' ) ) {
	function ansico_get_author_avatar_html( $author_id, $size = 120, $alt = '' ) {
		$custom_avatar_id = (int) get_user_meta( $author_id, 'ansico_custom_avatar_id', true );

		if ( $custom_avatar_id ) {
			$image = wp_get_attachment_image(
				$custom_avatar_id,
				array( $size, $size ),
				false,
				array(
					'class' => 'ansico-author-intro__avatar-image',
					'alt'   => $alt,
				)
			);

			if ( $image ) {
				return $image;
			}
		}

		return get_avatar(
			$author_id,
			$size,
			'',
			$alt,
			array(
				'class' => 'ansico-author-intro__avatar-image',
			)
		);
	}
}

if ( ! function_exists( 'ansico_enqueue_profile_media' ) ) {
	function ansico_enqueue_profile_media( $hook_suffix ) {
		if ( 'profile.php' !== $hook_suffix && 'user-edit.php' !== $hook_suffix ) {
			return;
		}

		wp_enqueue_media();

		$handle = 'ansico-profile-media';
		wp_register_script( $handle, '', array( 'jquery' ), null, true );
		wp_enqueue_script( $handle );

		$script = "
			jQuery(function($){
				var frame;
				$(document).on('click', '.ansico-upload-avatar-button', function(e){
					e.preventDefault();
					var button = $(this);
					var container = button.closest('.ansico-custom-avatar-field');

					if (frame) {
						frame.open();
						return;
					}

					frame = wp.media({
						title: '" . esc_js( __( 'Select profile image', 'ansico' ) ) . "',
						button: { text: '" . esc_js( __( 'Use this image', 'ansico' ) ) . "' },
						multiple: false
					});

					frame.on('select', function(){
						var attachment = frame.state().get('selection').first().toJSON();
						container.find('.ansico-custom-avatar-id').val(attachment.id);
						container.find('.ansico-custom-avatar-preview').html('<img src=\"' + attachment.url + '\" alt=\"\" style=\"width:96px;height:96px;border-radius:999px;object-fit:cover;display:block;\" />');
					});

					frame.open();
				});

				$(document).on('click', '.ansico-remove-avatar-button', function(e){
					e.preventDefault();
					var container = $(this).closest('.ansico-custom-avatar-field');
					container.find('.ansico-custom-avatar-id').val('');
					container.find('.ansico-custom-avatar-preview').empty();
				});
			});
		";
		wp_add_inline_script( $handle, $script );
	}
	add_action( 'admin_enqueue_scripts', 'ansico_enqueue_profile_media' );
}

if ( ! function_exists( 'ansico_render_profile_extensions' ) ) {
	function ansico_render_profile_extensions( $user ) {
		$networks          = function_exists( 'ansico_get_social_networks_v2' ) ? ansico_get_social_networks_v2() : array();
		$custom_avatar_id  = (int) get_user_meta( $user->ID, 'ansico_custom_avatar_id', true );
		$preview_image     = $custom_avatar_id ? wp_get_attachment_image( $custom_avatar_id, array( 96, 96 ), false, array( 'style' => 'width:96px;height:96px;border-radius:999px;object-fit:cover;display:block;' ) ) : '';
		?>
		<table class="form-table" role="presentation">
			<tbody>
				<tr class="ansico-custom-avatar-field">
					<th><?php esc_html_e( 'Custom profile image', 'ansico' ); ?></th>
					<td>
						<p class="description"><?php esc_html_e( 'Upload your own profile image if you do not want to use Gravatar.', 'ansico' ); ?></p>
						<div class="ansico-custom-avatar-preview" style="margin:10px 0;"><?php echo $preview_image; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped ?></div>
						<input type="hidden" class="ansico-custom-avatar-id" name="ansico_custom_avatar_id" value="<?php echo esc_attr( $custom_avatar_id ); ?>" />
						<button type="button" class="button ansico-upload-avatar-button"><?php esc_html_e( 'Upload image', 'ansico' ); ?></button>
						<button type="button" class="button ansico-remove-avatar-button"><?php esc_html_e( 'Remove image', 'ansico' ); ?></button>
					</td>
				</tr>
				<tr>
					<th colspan="2" style="padding-top:18px;"><?php esc_html_e( 'Social profiles', 'ansico' ); ?></th>
				</tr>
				<?php foreach ( $networks as $key => $network ) : ?>
					<tr>
						<th><label for="<?php echo esc_attr( 'ansico_' . $key ); ?>"><?php echo esc_html( $network['label'] ); ?></label></th>
						<td>
							<input type="url" name="<?php echo esc_attr( 'ansico_' . $key ); ?>" id="<?php echo esc_attr( 'ansico_' . $key ); ?>" value="<?php echo esc_attr( get_user_meta( $user->ID, 'ansico_' . $key, true ) ); ?>" class="regular-text" />
							<br />
							<label for="<?php echo esc_attr( 'ansico_show_' . $key ); ?>">
								<input type="checkbox" name="<?php echo esc_attr( 'ansico_show_' . $key ); ?>" id="<?php echo esc_attr( 'ansico_show_' . $key ); ?>" value="1" <?php checked( get_user_meta( $user->ID, 'ansico_show_' . $key, true ), '1' ); ?> />
								<?php esc_html_e( 'Show on profile', 'ansico' ); ?>
							</label>
						</td>
					</tr>
				<?php endforeach; ?>
			</tbody>
		</table>
		<?php
	}
	add_action( 'show_user_profile', 'ansico_render_profile_extensions', 99 );
	add_action( 'edit_user_profile', 'ansico_render_profile_extensions', 99 );
}

if ( ! function_exists( 'ansico_save_profile_extensions' ) ) {
	function ansico_save_profile_extensions( $user_id ) {
		if ( ! current_user_can( 'edit_user', $user_id ) ) {
			return false;
		}

		if ( isset( $_POST['ansico_custom_avatar_id'] ) ) {
			update_user_meta( $user_id, 'ansico_custom_avatar_id', absint( $_POST['ansico_custom_avatar_id'] ) );
		}

		$networks = function_exists( 'ansico_get_social_networks_v2' ) ? ansico_get_social_networks_v2() : array();

		foreach ( $networks as $key => $network ) {
			$url_key  = 'ansico_' . $key;
			$show_key = 'ansico_show_' . $key;

			if ( isset( $_POST[ $url_key ] ) ) {
				update_user_meta( $user_id, $url_key, esc_url_raw( wp_unslash( $_POST[ $url_key ] ) ) );
			}

			update_user_meta( $user_id, $show_key, isset( $_POST[ $show_key ] ) ? '1' : '0' );
		}
	}
	add_action( 'personal_options_update', 'ansico_save_profile_extensions', 99 );
	add_action( 'edit_user_profile_update', 'ansico_save_profile_extensions', 99 );
}

if ( ! function_exists( 'ansico_filter_author_avatar_shortcode_v2' ) ) {
	function ansico_filter_author_avatar_shortcode_v2( $output ) {
		if ( ! is_author() ) {
			return $output;
		}

		$author = get_queried_object();
		if ( ! $author || empty( $author->ID ) ) {
			return $output;
		}

		$name   = get_the_author_meta( 'display_name', (int) $author->ID );
		$avatar = ansico_get_author_avatar_html( (int) $author->ID, 120, $name );

		$output = preg_replace(
			'#<div class="ansico-author-intro__avatar">.*?</div>#s',
			'<div class="ansico-author-intro__avatar">' . $avatar . '</div>',
			$output,
			1
		);

		return $output;
	}
	add_filter( 'do_shortcode_tag', function( $output, $tag, $attr ) {
		if ( 'ansico_author_intro_v2' === $tag && function_exists( 'ansico_filter_author_avatar_shortcode_v2' ) ) {
			return ansico_filter_author_avatar_shortcode_v2( $output );
		}
		return $output;
	}, 10, 3 );
}


if ( ! function_exists( 'ansico_hide_legacy_contact_methods' ) ) {
	function ansico_hide_legacy_contact_methods( $methods ) {
		$legacy_keys = array(
			'facebook',
			'linkedin',
			'instagram',
			'bluesky',
			'twitter',
			'mastodon',
			'friendica',
			'reddit',
		);

		foreach ( $legacy_keys as $key ) {
			if ( isset( $methods[ $key ] ) ) {
				unset( $methods[ $key ] );
			}
		}

		return $methods;
	}
}
add_filter( 'user_contactmethods', 'ansico_hide_legacy_contact_methods', 9999 );



if ( ! function_exists( 'ansico_get_post_taxonomies_markup' ) ) {
	function ansico_get_post_taxonomies_markup( $post_id = 0, $include_default_taxonomies = true ) {
		$post_id = $post_id ? (int) $post_id : (int) get_queried_object_id();

		if ( ! $post_id ) {
			return '';
		}

		$post_type = get_post_type( $post_id );
		if ( empty( $post_type ) ) {
			return '';
		}

		$rows          = array();
		$tax_order     = array( 'category', 'post_tag' );
		$taxonomy_keys = get_object_taxonomies( $post_type, 'names' );
		$excluded_keys = array( 'post_format', 'nav_menu', 'link_category' );
		$sorted_keys   = array();

		if ( empty( $taxonomy_keys ) || ! is_array( $taxonomy_keys ) ) {
			return '';
		}

		$taxonomy_keys = array_values( array_filter( $taxonomy_keys, function( $taxonomy_name ) use ( $excluded_keys ) {
			return ! in_array( $taxonomy_name, $excluded_keys, true ) && 0 !== strpos( $taxonomy_name, 'nav_' );
		} ) );

		foreach ( $tax_order as $taxonomy_name ) {
			if ( in_array( $taxonomy_name, $taxonomy_keys, true ) ) {
				$sorted_keys[] = $taxonomy_name;
			}
		}

		foreach ( $taxonomy_keys as $taxonomy_name ) {
			if ( ! in_array( $taxonomy_name, $sorted_keys, true ) ) {
				$sorted_keys[] = $taxonomy_name;
			}
		}

		foreach ( $sorted_keys as $taxonomy_name ) {
			if ( ! $include_default_taxonomies && in_array( $taxonomy_name, $tax_order, true ) ) {
				continue;
			}

			$taxonomy = get_taxonomy( $taxonomy_name );

			if ( ! $taxonomy ) {
				continue;
			}

			$terms = wp_get_post_terms( $post_id, $taxonomy_name );

			if ( empty( $terms ) || is_wp_error( $terms ) ) {
				continue;
			}

			$links = array();

			foreach ( $terms as $term ) {
				$term_link = get_term_link( $term, $taxonomy_name );

				if ( is_wp_error( $term_link ) || empty( $term_link ) ) {
					$links[] = esc_html( $term->name );
					continue;
				}

				$links[] = '<a href="' . esc_url( $term_link ) . '">' . esc_html( $term->name ) . '</a>';
			}

			if ( empty( $links ) ) {
				continue;
			}

			if ( 'category' === $taxonomy_name ) {
				$label = __( 'Categories', 'ansico-wp-theme' );
			} elseif ( 'post_tag' === $taxonomy_name ) {
				$label = __( 'Tags', 'ansico-wp-theme' );
			} else {
				$label = ! empty( $taxonomy->labels->singular_name ) ? $taxonomy->labels->singular_name : ( ! empty( $taxonomy->labels->name ) ? $taxonomy->labels->name : $taxonomy->label );
			}

			$rows[] = '<div class="ansico-post-taxonomy-row ansico-post-taxonomy-row-' . sanitize_html_class( $taxonomy_name ) . '"><span class="ansico-post-taxonomy-label"><strong>' . esc_html( $label ) . ':</strong></span> <span class="ansico-post-taxonomy-terms">' . implode( ', ', $links ) . '</span></div>';
		}

		if ( empty( $rows ) ) {
			return '';
		}

		return '<div class="wp-block-group ansico-post-taxonomy" data-post-type="' . esc_attr( $post_type ) . '">' . implode( '', $rows ) . '</div>';
	}
}

if ( ! function_exists( 'ansico_post_taxonomies_shortcode' ) ) {
	function ansico_post_taxonomies_shortcode() {
		if ( ! is_singular() ) {
			return '';
		}

		return ansico_get_post_taxonomies_markup( get_queried_object_id() );
	}
}
add_shortcode( 'ansico_post_taxonomies', 'ansico_post_taxonomies_shortcode' );

if ( ! function_exists( 'ansico_append_post_taxonomies_to_post_content' ) ) {
	function ansico_append_post_taxonomies_to_post_content( $block_content, $block ) {
		if ( is_admin() || ! is_singular() || empty( $block['blockName'] ) || 'core/post-content' !== $block['blockName'] ) {
			return $block_content;
		}

		if ( ! in_the_loop() || ! is_main_query() ) {
			return $block_content;
		}

		$post_id = get_queried_object_id();
		if ( ! $post_id ) {
			return $block_content;
		}

		$taxonomy_markup = ansico_get_post_taxonomies_markup( $post_id, false );
		if ( empty( $taxonomy_markup ) ) {
			return $block_content;
		}

		return $block_content . $taxonomy_markup;
	}
}
add_filter( 'render_block', 'ansico_append_post_taxonomies_to_post_content', 10, 2 );
