<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

$profile_id   = $args['profile_id'] ?? '';
$profile_type = $args['profile_type'] ?? '';

if ( empty( $profile_id ) || empty( $profile_type ) ) {
	return;
}

$comments_args = array(
	'type'       => 'order_activity',
	'orderby'    => 'comment_date',
	'order'      => 'DESC',
	'parent'     => 0,
	// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
	'meta_query' => array(
		'relation' => 'AND',
	),
);

if ( 'freelancer' === $profile_type ) {
	// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
	$comments_args['meta_query'][] = array(
		'key'     => '_gigneo_cm_activity_type',
		'value'   => 'freelancer_review',
		'compare' => '=',
	);
	// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
	$comments_args['meta_query'][] = array(
		'key'     => '_gigneo_cm_freelancer_profile_id',
		'value'   => $profile_id,
		'compare' => '=',
	);
} elseif ( 'employer' === $profile_type ) {
	// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
	$comments_args['meta_query'][] = array(
		'key'     => '_gigneo_cm_activity_type',
		'value'   => 'employer_review',
		'compare' => '=',
	);
	// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
	$comments_args['meta_query'][] = array(
		'key'     => '_gigneo_cm_employer_profile_id',
		'value'   => $profile_id,
		'compare' => '=',
	);
}

$activity_comments = get_comments( $comments_args );

$total_rating        = 0;
$total_reviews       = 0;
$star_counts         = array(
	5 => 0,
	4 => 0,
	3 => 0,
	2 => 0,
	1 => 0,
);
$total_communication = 0;
$total_quality_work  = 0;
$total_understanding = 0;
$reviews_data        = array();

$date_format      = get_option( 'date_format' );
$time_format      = get_option( 'time_format' );
$date_time_format = $date_format . ' ' . $time_format;

foreach ( $activity_comments as $activity ) {
	if ( 'freelancer' === $profile_type ) {
		$review_data         = get_comment_meta( $activity->comment_ID, '_gigneo_cm_review_info', true );
		$communication_level = ! empty( $review_data['communication_level'] ) ? intval( $review_data['communication_level'] ) : 0;
		$quality_work        = ! empty( $review_data['quality_work'] ) ? intval( $review_data['quality_work'] ) : 0;
		$understanding       = ! empty( $review_data['understanding'] ) ? intval( $review_data['understanding'] ) : 0;
	} else {
		$review_data         = get_comment_meta( $activity->comment_ID, '_gigneo_cm_employer_review_info', true );
		$communication_level = ! empty( $review_data['communication_level'] ) ? intval( $review_data['communication_level'] ) : 0;
		$quality_work        = ! empty( $review_data['clarity_of_requirements'] ) ? intval( $review_data['clarity_of_requirements'] ) : 0;
		$understanding       = ! empty( $review_data['professionalism'] ) ? intval( $review_data['professionalism'] ) : 0;
	}

	$feedback            = ! empty( $review_data['feedback'] ) ? $review_data['feedback'] : '';
	$reviewer_profile_id = get_comment_meta( $activity->comment_ID, '_gigneo_cm_profile_id', true );

	if ( $communication_level || $quality_work || $understanding ) {
		$review_avg           = ( $communication_level + $quality_work + $understanding ) / 3;
		$total_rating        += $review_avg;
		$total_communication += $communication_level;
		$total_quality_work  += $quality_work;
		$total_understanding += $understanding;
		++$total_reviews;

		$rounded_star = (int) round( $review_avg );
		if ( $rounded_star >= 1 && $rounded_star <= 5 ) {
			++$star_counts[ $rounded_star ];
		}

		$reviews_data[] = array(
			'profile_id' => $reviewer_profile_id,
			'rating'     => number_format( $review_avg, 1 ),
			'feedback'   => $feedback,
			'date_gmt'   => $activity->comment_date_gmt,
		);
	}
}


$average_rating      = $total_reviews > 0 ? round( $total_rating / $total_reviews, 1 ) : 0;
$avg_communication   = $total_reviews > 0 ? round( $total_communication / $total_reviews, 1 ) : 0;
$avg_quality_work    = $total_reviews > 0 ? round( $total_quality_work / $total_reviews, 1 ) : 0;
$avg_understanding   = $total_reviews > 0 ? round( $total_understanding / $total_reviews, 1 ) : 0;
$total_ratings_count = array_sum( $star_counts );
?>
<div id="gn-reviews" class="gn-section gn-reviews-section">
	<div class="gn-head">
		<h3 class="gn-title"><?php esc_html_e( 'Reviews', 'gigneo' ); ?></h3>
	</div>
	<div class="gn-body">
		<div class="gn-reviews-summary">
			<div class="gn-reviews-overall">
				<div class="gn-reviews-overall-stars">
					<?php
					for ( $i = 1; $i <= 5; $i++ ) {
						if ( $average_rating >= $i ) {
							echo '<i class="hi hi-star-alt gn-filled" aria-hidden="true"></i>';
						} elseif ( $average_rating >= ( $i - 0.5 ) ) {
							echo '<i class="hi hi-star-half-alt gn-filled" aria-hidden="true"></i>';
						} else {
							echo '<i class="hi hi-star-alt" aria-hidden="true"></i>';
						}
					}
					?>
					<span class="gn-overall-value"><?php echo esc_html( $average_rating ); ?></span>
					<span class="gn-overall-count">(<?php echo esc_html( $total_reviews ); ?>)</span>
				</div>
			</div>

			<div class="gn-reviews-stats">
				<div class="gn-reviews-distribution">
					<?php foreach ( $star_counts as $star => $count ) : ?>
						<?php $percentage = $total_ratings_count > 0 ? ( $count / $total_ratings_count ) * 100 : 0; ?>
						<div class="gn-distribution-row">
							<span class="gn-star-label"><?php echo esc_html( $star ); ?> <?php echo esc_html( _n( 'Star', 'Stars', $star, 'gigneo' ) ); ?></span>
							<div class="gn-bar-track">
								<div class="gn-bar-fill" style="width: <?php echo esc_attr( $percentage ); ?>%"></div>
							</div>
							<span class="gn-bar-count">(<?php echo esc_html( number_format( $count ) ); ?>)</span>
						</div>
					<?php endforeach; ?>
				</div>

				<div class="gn-reviews-breakdown">
					<h4 class="gn-breakdown-title"><?php echo esc_html__( 'Rating breakdown', 'gigneo' ); ?></h4>
					<div class="gn-breakdown-item">
						<span class="gn-breakdown-label"><?php echo esc_html__( 'Communication level', 'gigneo' ); ?></span>
						<span class="gn-breakdown-value"><i class="hi hi-star-alt gn-filled" aria-hidden="true"></i><?php echo esc_html( $avg_communication ); ?></span>
					</div>
					<?php if ( 'employer' === $profile_type ) : ?>
						<div class="gn-breakdown-item">
							<span class="gn-breakdown-label"><?php echo esc_html__( 'Clarity of requirements', 'gigneo' ); ?></span>
							<span class="gn-breakdown-value"><i class="hi hi-star-alt gn-filled" aria-hidden="true"></i><?php echo esc_html( $avg_quality_work ); ?></span>
						</div>
						<div class="gn-breakdown-item">
							<span class="gn-breakdown-label"><?php echo esc_html__( 'Professionalism', 'gigneo' ); ?></span>
							<span class="gn-breakdown-value"><i class="hi hi-star-alt gn-filled" aria-hidden="true"></i><?php echo esc_html( $avg_understanding ); ?></span>
						</div>
					<?php else : ?>
						<div class="gn-breakdown-item">
							<span class="gn-breakdown-label"><?php echo esc_html__( 'Quality of delivery', 'gigneo' ); ?></span>
							<span class="gn-breakdown-value"><i class="hi hi-star-alt gn-filled" aria-hidden="true"></i><?php echo esc_html( $avg_quality_work ); ?></span>
						</div>
						<div class="gn-breakdown-item">
							<span class="gn-breakdown-label"><?php echo esc_html__( 'Quality of service', 'gigneo' ); ?></span>
							<span class="gn-breakdown-value"><i class="hi hi-star-alt gn-filled" aria-hidden="true"></i><?php echo esc_html( $avg_understanding ); ?></span>
						</div>
					<?php endif; ?>
				</div>
			</div>
		</div>
		<?php
		if ( ! empty( $reviews_data ) ) :
			$total_reviews_count = count( $reviews_data );
			$review_index        = 0;
			?>
			<div class="gn-reviews-list">
				<?php
				foreach ( $reviews_data as $review ) :
					++$review_index;
					$review_thumbnail_id = get_post_thumbnail_id( $review['profile_id'] );
					$hidden_class        = ( $review_index > 3 ) ? 'gn-review-item-hidden' : '';
					$style               = ( $review_index > 3 ) ? 'display: none;' : '';
					?>
					<div class="gn-review-card <?php echo esc_attr( $hidden_class ); ?>" style="<?php echo esc_attr( $style ); ?>">
						<div class="gn-review-header">
							<div class="gn-review-author">
								<figure class="gn-avatar">
									<?php gigneo_attachment_image_src( $review_thumbnail_id, 'thumbnail', 'profile', '', '', $reviewer_profile_id ); ?>
								</figure>
								<div class="gn-review-author-info">
									<div class="gn-name-wrapper">
										<h4 class="gn-name"><?php echo esc_html( gigneo_profile_name( $review['profile_id'] ) ); ?></h4>
										<?php gigneo_verification_badge( $review['profile_id'], true ); ?>
									</div>
									<div class="gn-review-stars">
										<?php
										$rating = floatval( $review['rating'] );
										for ( $i = 1; $i <= 5; $i++ ) {
											if ( $rating >= $i ) {
												echo '<i class="hi hi-star-alt gn-filled" aria-hidden="true"></i>';
											} elseif ( $rating >= ( $i - 0.5 ) ) {
												echo '<i class="hi hi-star-half-alt gn-filled" aria-hidden="true"></i>';
											} else {
												echo '<i class="hi hi-star-alt" aria-hidden="true"></i>';
											}
										}
										?>
									</div>
								</div>
							</div>
							<span class="gn-review-date"><?php echo esc_html( gigneo_datetime( $review['date_gmt'], $date_time_format ) ); ?></span>
						</div>
						<?php if ( ! empty( $review['feedback'] ) ) : ?>
							<div class="gn-review-content">
								<p><?php echo wp_kses_post( $review['feedback'] ); ?></p>
							</div>
						<?php endif; ?>
					</div>
				<?php endforeach; ?>
			</div>

			<?php if ( $total_reviews_count > 3 ) : ?>
				<div class="gn-reviews-show-more-wrapper">
					<button class="gn-show-more-reviews" type="button" data-less="<?php esc_attr_e( 'Show Less', 'gigneo' ); ?>">
						+<?php echo esc_html( $total_reviews_count - 3 ); ?> <?php esc_html_e( 'more', 'gigneo' ); ?> <i class="hi hi-chevron-down"></i>
					</button>
				</div>
			<?php endif; ?>

		<?php endif; ?>
	</div>
</div>
