<?php

function ru_ufpe_theme_current_user_can_comment_with_ufpe_id() {
	return is_user_logged_in() && ru_ufpe_theme_is_ufpe_id_user();
}

function ru_ufpe_theme_is_restricted_comment_post_type( $post_type ) {
	return in_array( $post_type, array( 'post', 'cardapio_semanal' ), true );
}

function ru_ufpe_theme_restrict_comment_submission_to_ufpe_id( $commentdata ) {
	$post_id = isset( $commentdata['comment_post_ID'] ) ? absint( $commentdata['comment_post_ID'] ) : 0;
	$post    = $post_id ? get_post( $post_id ) : null;

	if ( ! $post || ! ru_ufpe_theme_is_restricted_comment_post_type( $post->post_type ) ) {
		return $commentdata;
	}

	if ( ! ru_ufpe_theme_current_user_can_comment_with_ufpe_id() ) {
		wp_die(
			esc_html__( 'Entre com UFPE ID para comentar.', 'ru-ufpe-theme' ),
			esc_html__( 'Comentário restrito', 'ru-ufpe-theme' ),
			array( 'response' => 403 )
		);
	}

	$user = wp_get_current_user();

	$commentdata['user_id']              = $user->ID;
	$commentdata['comment_author']       = $user->display_name ? $user->display_name : $user->user_email;
	$commentdata['comment_author_email'] = $user->user_email;
	$commentdata['comment_author_url']   = '';

	return $commentdata;
}
add_filter( 'preprocess_comment', 'ru_ufpe_theme_restrict_comment_submission_to_ufpe_id' );

function ru_ufpe_theme_pre_approve_ufpe_id_comment( $approved, $commentdata ) {
	$post_id = isset( $commentdata['comment_post_ID'] ) ? absint( $commentdata['comment_post_ID'] ) : 0;
	$post    = $post_id ? get_post( $post_id ) : null;

	if ( ! $post || ! ru_ufpe_theme_is_restricted_comment_post_type( $post->post_type ) ) {
		return $approved;
	}

	$user_id = isset( $commentdata['user_id'] ) ? absint( $commentdata['user_id'] ) : get_current_user_id();
	$user    = $user_id ? get_user_by( 'id', $user_id ) : null;

	if ( ! $user || ! ru_ufpe_theme_is_ufpe_id_user( $user ) ) {
		return $approved;
	}

	return 1;
}
add_filter( 'pre_comment_approved', 'ru_ufpe_theme_pre_approve_ufpe_id_comment', 10, 2 );

function ru_ufpe_theme_auto_approve_ufpe_id_comment( $comment_id, $comment_approved, $commentdata ) {
	if ( ! in_array( (string) $comment_approved, array( '0', 'hold' ), true ) ) {
		return;
	}

	$post_id = isset( $commentdata['comment_post_ID'] ) ? absint( $commentdata['comment_post_ID'] ) : 0;
	$post    = $post_id ? get_post( $post_id ) : null;

	if ( ! $post || ! ru_ufpe_theme_is_restricted_comment_post_type( $post->post_type ) ) {
		return;
	}

	$user_id = isset( $commentdata['user_id'] ) ? absint( $commentdata['user_id'] ) : 0;
	$user    = $user_id ? get_user_by( 'id', $user_id ) : null;

	if ( ! $user || ! ru_ufpe_theme_is_ufpe_id_user( $user ) ) {
		return;
	}

	wp_set_comment_status( $comment_id, 'approve' );
}
add_action( 'comment_post', 'ru_ufpe_theme_auto_approve_ufpe_id_comment', 5, 3 );

function ru_ufpe_theme_open_weekly_menu_comments( $open, $post_id ) {
	$post = get_post( $post_id );

	if ( $post && 'cardapio_semanal' === $post->post_type && 'publish' === $post->post_status ) {
		return true;
	}

	return $open;
}
add_filter( 'comments_open', 'ru_ufpe_theme_open_weekly_menu_comments', 10, 2 );

function ru_ufpe_theme_redirect_after_restricted_comment( $location, $comment ) {
	$post = get_post( $comment->comment_post_ID );

	if ( ! $post || ! ru_ufpe_theme_is_restricted_comment_post_type( $post->post_type ) ) {
		return $location;
	}

	$referer = wp_get_referer();

	if ( ! $referer ) {
		return $location;
	}

	$referer = remove_query_arg( array( 'unapproved', 'moderation-hash' ), $referer );
	$referer = strtok( $referer, '#' );
	$anchor  = '0' === (string) $comment->comment_approved ? '#comments' : '#comment-' . $comment->comment_ID;

	return wp_validate_redirect( $referer . $anchor, $location );
}
add_filter( 'comment_post_redirect', 'ru_ufpe_theme_redirect_after_restricted_comment', 10, 2 );

function ru_ufpe_theme_render_comment_item( $comment, $args, $depth ) {
	$tag = 'div' === $args['style'] ? 'div' : 'li';
	?>
	<<?php echo esc_attr( $tag ); ?> id="comment-<?php echo esc_attr( $comment->comment_ID ); ?>" <?php comment_class( 'ru-comment-item', $comment ); ?>>
		<div class="ru-comment-avatar">
			<?php echo get_avatar( $comment, 40, '', '', array( 'class' => 'rounded-full' ) ); ?>
		</div>
		<div class="ru-comment-content">
			<div class="ru-comment-meta">
				<strong><?php echo esc_html( get_comment_author( $comment ) ); ?></strong>
				<span><?php echo esc_html( get_comment_date( 'd/m/Y H:i', $comment ) ); ?></span>
			</div>
			<?php if ( '0' === $comment->comment_approved ) : ?>
				<div class="notice notice-info ru-comment-awaiting"><i data-lucide="clock-3"></i><span>Comentário aguardando moderação.</span></div>
			<?php endif; ?>
			<div class="prose-ru ru-comment-text">
				<?php comment_text( $comment ); ?>
			</div>
			<?php if ( ru_ufpe_theme_current_user_can_comment_with_ufpe_id() ) : ?>
				<?php
				comment_reply_link(
					array_merge(
						$args,
						array(
							'add_below'  => 'comment',
							'depth'      => $depth,
							'max_depth'  => isset( $args['max_depth'] ) ? (int) $args['max_depth'] : 5,
							'reply_text' => '<i data-lucide="reply"></i><span>Responder</span>',
							'before'     => '<div class="ru-comment-actions">',
							'after'      => '</div>',
						)
					),
					$comment,
					$comment->comment_post_ID
				);
				?>
			<?php endif; ?>
		</div>
	<?php
}

function ru_ufpe_theme_get_comments_for_public_thread( $post_id ) {
	$comments = get_comments(
		array(
			'post_id'      => absint( $post_id ),
			'status'       => 'approve',
			'orderby'      => 'comment_date_gmt',
			'order'        => 'ASC',
			'hierarchical' => 'threaded',
		)
	);

	if ( ! ru_ufpe_theme_current_user_can_comment_with_ufpe_id() ) {
		return $comments;
	}

	$pending_comments = get_comments(
		array(
			'post_id' => absint( $post_id ),
			'status'  => 'hold',
			'user_id' => get_current_user_id(),
			'orderby' => 'comment_date_gmt',
			'order'   => 'ASC',
		)
	);

	if ( ! $pending_comments ) {
		return $comments;
	}

	$comments_by_id = array();

	foreach ( array_merge( $comments, $pending_comments ) as $comment ) {
		$comments_by_id[ $comment->comment_ID ] = $comment;
	}

	$comments = array_values( $comments_by_id );
	usort(
		$comments,
		static function ( $first, $second ) {
			return strcmp( $first->comment_date_gmt, $second->comment_date_gmt );
		}
	);

	return $comments;
}

function ru_ufpe_theme_render_comments_thread( $post_id, $args = array() ) {
	$post_id = absint( $post_id );
	$post    = $post_id ? get_post( $post_id ) : null;

	if ( ! $post ) {
		return;
	}

	$defaults = array(
		'title'       => 'Comentários',
		'description' => 'Entre com UFPE ID para participar da conversa.',
	);
	$args     = wp_parse_args( $args, $defaults );
	$comments = ru_ufpe_theme_get_comments_for_public_thread( $post_id );
	$count    = count( $comments );
	$max_depth = max( 2, absint( get_option( 'thread_comments_depth', 5 ) ) );
	?>

	<section class="ru-comments card" id="comments">
		<div class="card-body">
			<div class="ru-comments-header">
				<div>
					<span class="tag tag-outline-accent">UFPE ID</span>
					<h2 class="card-title"><?php echo esc_html( $args['title'] ); ?></h2>
					<p class="text-sm text-base-muted"><?php echo esc_html( $args['description'] ); ?></p>
				</div>
				<span class="tag tag-outline"><?php echo esc_html( sprintf( _n( '%s comentário', '%s comentários', $count, 'ru-ufpe-theme' ), number_format_i18n( $count ) ) ); ?></span>
			</div>

			<?php if ( $comments ) : ?>
				<div class="ru-comment-list">
					<?php
					wp_list_comments(
						array(
							'style'       => 'div',
							'callback'    => 'ru_ufpe_theme_render_comment_item',
							'avatar_size' => 40,
							'max_depth'   => $max_depth,
						),
						$comments
					);
					?>
				</div>
			<?php else : ?>
				<div class="notice notice-info"><i data-lucide="message-circle"></i><span>Nenhum comentário publicado ainda.</span></div>
			<?php endif; ?>

			<?php if ( comments_open( $post_id ) ) : ?>
				<?php if ( ru_ufpe_theme_current_user_can_comment_with_ufpe_id() ) : ?>
					<?php ru_ufpe_theme_render_comment_form( $post_id ); ?>
				<?php else : ?>
					<div class="ru-comment-login">
						<div>
							<h3 class="text-lg font-semibold text-base-content">Comente com UFPE ID</h3>
							<p class="text-sm text-base-muted">Somente contas institucionais @ufpe.br podem comentar.</p>
						</div>
						<?php echo ru_ufpe_theme_render_ufpe_id_button( ru_ufpe_theme_current_url_without_auth_args() . '#comments' ); ?>
					</div>
				<?php endif; ?>
			<?php else : ?>
				<div class="notice notice-warning"><i data-lucide="lock"></i><span>Comentários encerrados para este conteúdo.</span></div>
			<?php endif; ?>
		</div>
	</section>
	<?php
}

function ru_ufpe_theme_render_comment_form( $post_id ) {
	$user = wp_get_current_user();
	?>
	<div id="respond" class="comment-respond ru-comment-respond">
		<h3 id="reply-title" class="comment-reply-title text-lg font-semibold text-base-content">
			<span>Adicionar comentário</span>
			<small><?php cancel_comment_reply_link( 'Cancelar resposta' ); ?></small>
		</h3>
		<form action="<?php echo esc_url( site_url( '/wp-comments-post.php' ) ); ?>" method="post" id="commentform" class="ru-comment-form">
			<p class="ru-comment-logged-in">Comentando como <strong><?php echo esc_html( $user->display_name ? $user->display_name : $user->user_email ); ?></strong> via UFPE ID.</p>
			<p class="comment-form-comment">
				<label class="sr-only" for="comment">Comentário</label>
				<textarea id="comment" name="comment" class="input ru-comment-textarea" rows="5" required placeholder="Escreva seu comentário..."></textarea>
			</p>
			<p class="form-submit">
				<button name="submit" type="submit" id="submit" class="btn btn-primary">Enviar comentário</button>
			</p>
			<?php comment_id_fields( $post_id ); ?>
			<?php do_action( 'comment_form', $post_id ); ?>
		</form>
	</div>
	<?php
}
