<?php 
defined( 'ABSPATH' ) || exit; // Exit if accessed directly
add_action( 'comment_form_logged_in_after', 'ci_comment_rating_rating_field' );
// add_action( 'comment_form_after_fields', 'ci_comment_rating_rating_field' );
function ci_comment_rating_rating_field () {
	global $post;
	if( get_post_type() != 'firma' || get_user_meta(get_current_user_id(), 'kanews-post-rating-star-'.$post->ID, true) != '' )
	return;
	?>
	<label for="rating" class="mb-2"><?php esc_html_e( 'Firmaya Puanınız', 'kanews' ); ?></label>
	<fieldset class="kanews-comments-rating">
		<span class="kanews-rating-container">
			<?php for ( $i = 5; $i >= 1; $i-- ) : ?>
				<input type="radio" id="rating-<?php echo esc_attr( $i ); ?>" name="rating" value="<?php echo esc_attr( $i ); ?>" /><label for="rating-<?php echo esc_attr( $i ); ?>"><?php echo esc_html( $i ); ?></label>
			<?php endfor; ?>
			<input type="radio" id="rating-0" class="star-cb-clear" name="rating" value="0" /><label for="rating-0">0</label>
		</span>
	</fieldset>
	<?php
}

//Save the rating submitted by the user.
add_action( 'comment_post', 'ci_comment_rating_save_comment_rating' );
function ci_comment_rating_save_comment_rating( $comment_id ) {
	$user_id = get_comment($comment_id)->user_id;
	$post_id = get_comment($comment_id)->comment_post_ID;
	$total_user = '';
	$overall = '';
	if ( ( isset( $_POST['rating'] ) ) && ( '' !== $_POST['rating'] ) && get_user_meta($user_id, 'kanews-post-rating-star-'.$post_id, true) == '' ) {
		$rating = intval( $_POST['rating'] );
		add_comment_meta( $comment_id, 'kanews-post-rating', $rating );

		update_user_meta( $user_id, 'kanews-post-rating-star-'.$post_id, $rating );

		$total_user = get_post_meta($post_id, '_kanews_post_rating_users', true) ? get_post_meta($post_id, '_kanews_post_rating_users', true)+1 : 1;
		update_post_meta( $post_id, '_kanews_post_rating_users', $total_user );
		
		$total_rating = get_post_meta($post_id, '_kanews_post_rating_total', true) ? get_post_meta($post_id, '_kanews_post_rating_total', true)+$rating : $rating;
		update_post_meta( $post_id, '_kanews_post_rating_total', $total_rating );

		$overall = round( $total_rating / $total_user, 1 );
		update_post_meta( $post_id, '_kanews_post_rating_overall', $overall );
	}
}

add_action('delete_comment', 'kanews_comment_rating_delete_comment', 1);
function kanews_comment_rating_delete_comment($comment_id) {
	$user_id = get_comment($comment_id)->user_id;
	$post_id = get_comment($comment_id)->comment_post_ID;
	$rating = get_comment_meta($comment_id, 'kanews-post-rating', true) ? get_comment_meta($comment_id, 'kanews-post-rating', true) : 0;
	$total_user = get_post_meta($post_id, '_kanews_post_rating_users', true) ? get_post_meta($post_id, '_kanews_post_rating_users', true)-1 : 0;

	
	if ($total_user > 0) {
		update_post_meta($post_id, '_kanews_post_rating_users', $total_user);
		$total_rating = get_post_meta($post_id, '_kanews_post_rating_total', true) ? get_post_meta($post_id, '_kanews_post_rating_total', true) - $rating : 0;
		update_post_meta($post_id, '_kanews_post_rating_total', $total_rating);
		$overall = round($total_rating / $total_user, 1);
		update_post_meta($post_id, '_kanews_post_rating_overall', $overall);
	}
	
	delete_user_meta( $user_id, 'kanews-post-rating-star-'.$post_id );
}

//Display the rating on a submitted comment.
add_filter( 'comment_text', 'ci_comment_rating_display_rating');
function ci_comment_rating_display_rating( $comment_text ){

	if ( $rating = get_comment_meta( get_comment_ID(), 'kanews-post-rating', true ) ) {
		$stars = '<p class="stars">';
		for ( $i = 1; $i <= $rating; $i++ ) {
			$stars .= '<span class="icon-star"></span>';
		}
		$stars .= '</p>';
		$comment_text = $comment_text . $stars;
		return $comment_text;
	} else {
		return $comment_text;
	}
}

//Get the average rating of a post.
function ci_comment_rating_get_average_ratings( $id ) {
	$comments = get_approved_comments( $id );

	if ( $comments ) {
		$i = 0;
		$total = 0;
		foreach( $comments as $comment ){
			$rate = get_comment_meta( $comment->comment_ID, 'kanews-post-rating', true );
			if( isset( $rate ) && '' !== $rate ) {
				$i++;
				$total += $rate;
			}
		}

		if ( 0 === $i ) {
			return false;
		} else {
			return round( $total / $i, 1 );
		}
	} else {
		return 0;
	}
}



add_action( 'pre_get_posts', 'lit_category_filter' );
function lit_category_filter($query) {
    if ( ! is_admin() && $query->is_main_query() ) {
        if( $query->is_archive('firma')) {
					$metaquery = array();
					$meta_order = '';
					if($query->get('comp_name') !== '') {
						$metaquery[] = array(
							'key' => 'comp_name',
							'value' => $query->get('comp_name'),
							'compare' => 'LIKE'
						);
					}
					// İl/Ülke filtresi (il veya ulke parametresi)
					$il_param = $query->get('il') ? $query->get('il') : ($query->get('ulke') ? $query->get('ulke') : '');
					$ilce_param = $query->get('ilce') ? $query->get('ilce') : ($query->get('sehir') ? $query->get('sehir') : '');
					
					if($il_param !== '' || $ilce_param !== '') {
						$sehir_name = '';
						$ilce_name = '';
						
						// İl/Ülke değerini al
						if($il_param !== '') {
							$il_value = sanitize_text_field($il_param);
							// Numeric ise (plaka numarası)
							if(is_numeric($il_value) && ($il_value > 0 && $il_value <= 81)) {
								$sehir_name = kanews_get_sehir($il_value);
							} 
							// String ise (şehir/ülke ismi)
							else if(!is_numeric($il_value)) {
								$sehir_name = $il_value;
							}
						}
						
						// İlçe/Şehir değerini al
						if($ilce_param !== '') {
							$ilce_name = sanitize_text_field($ilce_param);
						}
						
						// Filtre oluştur
						if(!empty($ilce_name) && !empty($sehir_name)) {
							// Hem il hem ilçe seçilmişse - "İl - İlçe" formatında ara
							$metaquery[] = array(
								'key' => 'comp_city',
								'value' => $ilce_name,
								'compare' => 'LIKE'
							);
						} else if(!empty($sehir_name)) {
							// Sadece il seçilmişse
							$metaquery[] = array(
								'key' => 'comp_city',
								'value' => $sehir_name,
								'compare' => 'LIKE'
							);
						} else if(!empty($ilce_name)) {
							// Sadece ilçe seçilmişse
							$metaquery[] = array(
								'key' => 'comp_city',
								'value' => $ilce_name,
								'compare' => 'LIKE'
							);
						}
					}
					// Eski comp_city parametresi (geriye dönük uyumluluk)
					else if($query->get('comp_city') !== '') {
						$metaquery[] = array(
							'key' => 'comp_city',
							'value' => $query->get('comp_city'),
							'compare' => 'LIKE'
						);
					}
					if($query->get('comp_rating_min') !== '' && $query->get('comp_rating_max') !== '') {
						$metaquery[] = array(
							'key' => '_kanews_post_rating_overall',
							'type' => 'numeric',
							'value'     => array( $query->get('comp_rating_min'), $query->get('comp_rating_max') ),
            	'compare'   => 'BETWEEN',
						);
						$meta_order = 'meta_value_num';
					}elseif($query->get('comp_rating_max') != '') {
						$metaquery[] = array(
							'key' => '_kanews_post_rating_overall',
							'type' => 'numeric',
							'value'     => $query->get('comp_rating_max'),
            	'compare'   => '<=',
						);
						$meta_order = 'meta_value_num';
					}elseif($query->get('comp_rating_min') != '') {
						$metaquery[] = array(
							'key' => '_kanews_post_rating_overall',
							'value'     => $query->get('comp_rating_min'),
							'type' => 'numeric',
            	'compare'   => '>=',
						);
						$meta_order = 'meta_value_num';
					}
					$tax_query = array();
					if($query->get('comp_cat') !== '') {
						$comp_cat_value = $query->get('comp_cat');
						// Term ID ise
						if (is_numeric($comp_cat_value)) {
							$tax_query[] = array(
								'taxonomy' => 'kategori',
								'field'    => 'term_id',
								'terms'    => intval($comp_cat_value),
							);
						} else {
							// Slug ise
							$tax_query[] = array(
								'taxonomy' => 'kategori',
								'field'    => 'slug',
								'terms'    => $comp_cat_value,
							);
						}
					}
					if (!empty($tax_query)) {
						$query->set('tax_query', $tax_query);
					}
          $query->set('meta_query', $metaquery);
          $query->set('orderby', $meta_order);
        }
    }
}

add_filter('query_vars', function ($qv) {
	$qv[] = 'comp_name';
	$qv[] = 'comp_city';
	$qv[] = 'comp_rating_min';
	$qv[] = 'comp_rating_max';
	$qv[] = 'comp_cat';
	$qv[] = 'il';
	$qv[] = 'ulke';
	$qv[] = 'ilce';
	$qv[] = 'sehir';
	return $qv;
});