<?php

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

$service_id = $args['p_id'] ?? get_the_ID();

$activity_comments = get_comments(
	array(
		'type'       => 'order_activity',
		'orderby'    => 'comment_date',
		'order'      => 'DESC',
		'parent'     => 0,
		// phpcs:ignore WordPress.DB.SlowDBQuery.slow_db_query_meta_query
		'meta_query' => array(
			array(
				'key'     => '_gigneo_cm_service_id',
				'value'   => $service_id,
				'compare' => '=',
			),
			array(
				'key'     => '_gigneo_cm_activity_type',
				'value'   => 'freelancer_review',
				'compare' => '=',
			),
		),
	)
);

$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 ) {
	$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;
	$feedback            = ! empty( $review_data['feedback'] ) ? $review_data['feedback'] : '';
	$profile_id          = get_comment_meta( $activity->comment_ID, '_gigneo_cm_profile_id', true );
	$thumbnail_id        = ! empty( $profile_id ) ? get_post_thumbnail_id( $profile_id ) : '';

	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'   => $profile_id,
			'thumbnail_id' => $thumbnail_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 class="gn-section gn-reviews-section">
	<div class="gn-head">
		<h3 class="gn-title"><?php echo esc_html__( '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( 1 === $star ? __( 'Star', 'gigneo' ) : __( 'Stars', '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>
					<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>
				</div>
			</div>
		</div>
		<?php if ( ! empty( $reviews_data ) ) : ?>
			<div class="gn-reviews-list">
				<?php
				foreach ( $reviews_data as $review ) :
					$review_thumbnail_id = get_post_thumbnail_id( $review['profile_id'] );
					?>
					<div class="gn-review-card">
						<div class="gn-review-header">
							<div class="gn-review-author">
								<figure class="gn-avatar">
									<?php gigneo_attachment_image_src( $review_thumbnail_id ?? 0, 'thumbnail', 'profile' ); ?>
								</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 endif; ?>
	</div>
</div>
