<?php
/**
 * Template: Google Rating View
 * Displays Google star rating and review count under stock info on product pages
 */

// Exit if accessed directly
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

// Check if Google Rating is enabled in Display Settings
$display_settings = get_option( 'wcmlim_backend_display_feilds_settings', array() );
if ( ! is_array( $display_settings ) || ! in_array( 'google_rating', $display_settings ) ) {
	return; // Don't display if not enabled
}

/**
 * Get Google rating for current location
 */
function wcmlim_get_location_google_rating() {
	// Get selected location from cookie
	$location_id = null;
	$location_name = null;
	
	// Try to get location name first (more reliable)
	if ( isset( $_COOKIE['wcmlim_selected_location'] ) ) {
		$location_name = sanitize_text_field( $_COOKIE['wcmlim_selected_location'] );
		$term_by_name = get_term_by( 'name', $location_name, 'locations' );
		
		if ( $term_by_name && ! is_wp_error( $term_by_name ) ) {
			$location_id = $term_by_name->term_id;
		}
	} elseif ( function_exists( 'getLocation' ) ) {
		$location_name = getLocation( 'wcmlim_selected_location' );
		if ( ! empty( $location_name ) ) {
			$term_by_name = get_term_by( 'name', $location_name, 'locations' );
			if ( $term_by_name && ! is_wp_error( $term_by_name ) ) {
				$location_id = $term_by_name->term_id;
			}
		}
	}
	
	// Fallback to term ID if name-based lookup failed
	if ( empty( $location_id ) ) {
		if ( isset( $_COOKIE['wcmlim_selected_location_termid'] ) ) {
			$location_id = intval( $_COOKIE['wcmlim_selected_location_termid'] );
		} elseif ( function_exists( 'getLocation' ) ) {
			$location_id = getLocation( 'wcmlim_selected_location_termid' );
		}
	}
	
	if ( empty( $location_id ) ) {
		return null;
	}
	
	// Get Place ID for this location
	$place_id = get_term_meta( $location_id, 'google_place_id', true );
	
	if ( empty( $place_id ) ) {
		return null;
	}
	
	// Get API key
	$api_key = get_option( 'wcmlim_google_api_key', '' );
	
	if ( empty( $api_key ) ) {
		return null;
	}
	
	// Check cache first (cache for 24 hours)
	$cache_key = 'wcmlim_rating_' . md5( $location_id . '_' . $place_id );
	$cached_data = get_transient( $cache_key );
	
	if ( false !== $cached_data ) {
		return $cached_data;
	}
	
	// Fetch from Google Places API
	$url = add_query_arg(
		array(
			'place_id' => $place_id,
			'fields'   => 'name,rating,user_ratings_total',
			'key'      => $api_key,
		),
		'https://maps.googleapis.com/maps/api/place/details/json'
	);
	
	$response = wp_remote_get( $url, array(
		'timeout' => 10,
	) );
	
	if ( is_wp_error( $response ) ) {
		return null;
	}
	
	$body = wp_remote_retrieve_body( $response );
	$data = json_decode( $body, true );
	
	if ( empty( $data['result'] ) ) {
		return null;
	}
	
	$result = array(
		'rating'              => isset( $data['result']['rating'] ) ? floatval( $data['result']['rating'] ) : 0,
		'user_ratings_total'  => isset( $data['result']['user_ratings_total'] ) ? intval( $data['result']['user_ratings_total'] ) : 0,
		'place_name'          => isset( $data['result']['name'] ) ? sanitize_text_field( $data['result']['name'] ) : '',
		'location_id'         => $location_id,
		'place_id'            => $place_id,
	);
	
	// Cache the result for 24 hours
	set_transient( $cache_key, $result, 24 * HOUR_IN_SECONDS );
	
	return $result;
}

/**
 * Generate star rating HTML
 */
function wcmlim_generate_star_html( $rating ) {
	$full_stars = floor( $rating );
	$half_star = ( $rating - $full_stars ) >= 0.5 ? 1 : 0;
	$empty_stars = 5 - $full_stars - $half_star;
	
	$html = '<span class="wcmlim-rating-stars-inline">';
	
	// Full stars
	for ( $i = 0; $i < $full_stars; $i++ ) {
		$html .= '<span class="wcmlim-star wcmlim-star-full">★</span>';
	}
	
	// Half star
	if ( $half_star ) {
		$html .= '<span class="wcmlim-star wcmlim-star-half">★</span>';
	}
	
	// Empty stars
	for ( $i = 0; $i < $empty_stars; $i++ ) {
		$html .= '<span class="wcmlim-star wcmlim-star-empty">☆</span>';
	}
	
	$html .= '</span>';
	
	return $html;
}

// Get rating data
$rating_data = wcmlim_get_location_google_rating();

if ( ! empty( $rating_data ) && $rating_data['rating'] > 0 ) :
?>
<style>
.wcmlim-google-rating-inline {
	display: flex !important;
	align-items: center !important;
	gap: 10px !important;
	margin: 12px 0 !important;
	padding: 12px 15px !important;
	background: linear-gradient(135deg, #f8f9fa 0%, #ffffff 100%) !important;
	border-left: 4px solid #667eea !important;
	border-radius: 8px !important;
	box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05) !important;
	transition: all 0.3s ease !important;
}

.wcmlim-google-rating-inline:hover {
	box-shadow: 0 4px 12px rgba(102, 126, 234, 0.15) !important;
	transform: translateX(2px) !important;
}

.wcmlim-rating-stars-inline {
	display: inline-flex !important;
	gap: 2px !important;
	font-size: 18px !important;
	line-height: 1 !important;
}

.wcmlim-rating-stars-inline .wcmlim-star {
	display: inline-block !important;
	transition: transform 0.2s ease !important;
}

.wcmlim-rating-stars-inline .wcmlim-star-full {
	color: #FFD700 !important;
	text-shadow: 0 0 8px rgba(255, 215, 0, 0.5) !important;
}

.wcmlim-rating-stars-inline .wcmlim-star-half {
	color: #FFD700 !important;
	opacity: 0.7 !important;
}

.wcmlim-rating-stars-inline .wcmlim-star-empty {
	color: #ddd !important;
}

.wcmlim-rating-number-inline {
	font-size: 18px !important;
	font-weight: 700 !important;
	color: #2c3e50 !important;
	margin: 0 !important;
	line-height: 1 !important;
}

.wcmlim-rating-count-inline {
	font-size: 14px !important;
	color: #666 !important;
	font-weight: 500 !important;
	margin: 0 !important;
}

.wcmlim-google-link-inline {
	margin-left: auto !important;
	padding: 6px 14px !important;
	background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
	color: white !important;
	text-decoration: none !important;
	border-radius: 20px !important;
	font-size: 13px !important;
	font-weight: 600 !important;
	transition: all 0.3s ease !important;
	white-space: nowrap !important;
	box-shadow: 0 2px 8px rgba(102, 126, 234, 0.3) !important;
}

.wcmlim-google-link-inline:hover {
	transform: translateY(-2px) !important;
	box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4) !important;
	color: white !important;
	text-decoration: none !important;
}

.wcmlim-google-link-inline svg {
	vertical-align: middle !important;
	margin-left: 4px !important;
}

@media (max-width: 768px) {
	.wcmlim-google-rating-inline {
		flex-wrap: wrap !important;
		gap: 8px !important;
	}
	
	.wcmlim-rating-stars-inline {
		font-size: 16px !important;
	}
	
	.wcmlim-rating-number-inline {
		font-size: 16px !important;
	}
	
	.wcmlim-rating-count-inline {
		font-size: 13px !important;
	}
	
	.wcmlim-google-link-inline {
		margin-left: 0 !important;
		width: 100% !important;
		text-align: center !important;
	}
}
</style>

<div class="wcmlim-google-rating-inline">
	<?php echo wcmlim_generate_star_html( $rating_data['rating'] ); ?>
	<span class="wcmlim-rating-number-inline"><?php echo number_format( $rating_data['rating'], 1 ); ?></span>
	<span class="wcmlim-rating-count-inline">
		(<?php echo number_format_i18n( $rating_data['user_ratings_total'] ); ?> <?php esc_html_e( 'reviews', 'wcmlim' ); ?>)
	</span>
	<a href="<?php echo esc_url( 'https://www.google.com/maps/search/?api=1&query=Google&query_place_id=' . $rating_data['place_id'] ); ?>" 
	   target="_blank" 
	   rel="noopener noreferrer" 
	   class="wcmlim-google-link-inline">
		<?php esc_html_e( 'View Reviews', 'wcmlim' ); ?>
		<svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
			<path d="M18 13v6a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2h6"></path>
			<polyline points="15 3 21 3 21 9"></polyline>
			<line x1="10" y1="14" x2="21" y2="3"></line>
		</svg>
	</a>
</div>

<?php endif; ?>
