<?php
/**
 * Google Reviews by Location
 * Fetches and displays Google Reviews for each location using Google Places API
 */

// Check if WooCommerce is active
if ( ! in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
	return;
}

/**
 * Add Google Place ID field to location taxonomy
 */
function wcmlim_add_location_place_id_field( $term ) {
	$place_id = get_term_meta( $term->term_id, 'google_place_id', true );
	?>
	<tr class="form-field">
		<th scope="row">
			<label for="google_place_id"><?php esc_html_e( 'Google Place ID', 'wcmlim' ); ?></label>
		</th>
		<td>
			<input type="text" name="google_place_id" id="google_place_id" value="<?php echo esc_attr( $place_id ); ?>" class="regular-text" />
			<p class="description">
				<?php 
				echo sprintf(
					__( 'Enter the Google Place ID for this location. Find it at: %s', 'wcmlim' ),
					'<a href="https://developers.google.com/maps/documentation/places/web-service/place-id#find-id" target="_blank">Google Place ID Finder</a>'
				);
				?>
			</p>
			<p class="description">
				<?php esc_html_e( 'Example: ChIJ-WBUiXm_wjsRpXViSzjI7S4', 'wcmlim' ); ?>
			</p>
		</td>
	</tr>
	<?php
}
add_action( 'locations_edit_form_fields', 'wcmlim_add_location_place_id_field', 10, 1 );

/**
 * Save Google Place ID for location
 */
function wcmlim_save_location_place_id( $term_id ) {
	if ( isset( $_POST['google_place_id'] ) ) {
		update_term_meta( $term_id, 'google_place_id', sanitize_text_field( $_POST['google_place_id'] ) );
	}
}
add_action( 'edited_locations', 'wcmlim_save_location_place_id', 10, 1 );
add_action( 'create_locations', 'wcmlim_save_location_place_id', 10, 1 );

/**
 * Add Google API Key setting to admin settings
 */
function wcmlim_add_google_api_settings() {
	add_settings_section(
		'wcmlim_google_reviews_section',
		__( 'Google Reviews Settings', 'wcmlim' ),
		'wcmlim_google_reviews_section_callback',
		'wcmlim_settings'
	);

	add_settings_field(
		'wcmlim_google_api_key',
		__( 'Google Places API Key', 'wcmlim' ),
		'wcmlim_google_api_key_callback',
		'wcmlim_settings',
		'wcmlim_google_reviews_section'
	);

	register_setting( 'wcmlim_settings_group', 'wcmlim_google_api_key' );
}
add_action( 'admin_init', 'wcmlim_add_google_api_settings' );

function wcmlim_google_reviews_section_callback() {
	echo '<p>' . esc_html__( 'Configure Google Places API settings to display location reviews.', 'wcmlim' ) . '</p>';
	echo '<p>' . sprintf(
		__( 'Get your API key from: %s', 'wcmlim' ),
		'<a href="https://developers.google.com/maps/documentation/javascript/get-api-key" target="_blank">Google Cloud Console</a>'
	) . '</p>';
}

function wcmlim_google_api_key_callback() {
	$api_key = get_option( 'wcmlim_google_api_key', '' );
	echo '<input type="text" name="wcmlim_google_api_key" value="' . esc_attr( $api_key ) . '" class="regular-text" />';
	echo '<p class="description">' . esc_html__( 'Enter your Google Places API key to fetch reviews.', 'wcmlim' ) . '</p>';
}

/**
 * Fetch Google Reviews for a location
 */
function wcmlim_get_google_reviews( $location_id, $force_refresh = false ) {
	$place_id = get_term_meta( $location_id, 'google_place_id', true );
	
	if ( empty( $place_id ) ) {
		return new WP_Error( 'no_place_id', __( 'No Google Place ID configured for this location.', 'wcmlim' ) );
	}

	$api_key = get_option( 'wcmlim_google_api_key', '' );
	
	if ( empty( $api_key ) ) {
		return new WP_Error( 'no_api_key', __( 'Google API key not configured.', 'wcmlim' ) );
	}

	// Check cache first (cache for 24 hours)
	$cache_key = 'wcmlim_reviews_' . $location_id;
	
	if ( ! $force_refresh ) {
		$cached_reviews = get_transient( $cache_key );
		if ( false !== $cached_reviews ) {
			return $cached_reviews;
		}
	}

	// Fetch from Google Places API
	$url = add_query_arg(
		array(
			'place_id' => $place_id,
			'fields'   => 'name,rating,reviews,user_ratings_total',
			'key'      => $api_key,
		),
		'https://maps.googleapis.com/maps/api/place/details/json'
	);

	$response = wp_remote_get( $url, array(
		'timeout' => 15,
	) );

	if ( is_wp_error( $response ) ) {
		return $response;
	}

	$body = wp_remote_retrieve_body( $response );
	$data = json_decode( $body, true );

	if ( empty( $data['result'] ) ) {
		return new WP_Error( 'no_results', __( 'No reviews found for this location.', 'wcmlim' ) );
	}

	$result = array(
		'name'               => isset( $data['result']['name'] ) ? $data['result']['name'] : '',
		'rating'             => isset( $data['result']['rating'] ) ? $data['result']['rating'] : 0,
		'user_ratings_total' => isset( $data['result']['user_ratings_total'] ) ? $data['result']['user_ratings_total'] : 0,
		'reviews'            => isset( $data['result']['reviews'] ) ? $data['result']['reviews'] : array(),
	);

	// Cache for 24 hours
	set_transient( $cache_key, $result, 24 * HOUR_IN_SECONDS );

	return $result;
}

/**
 * Shortcode to display Google Reviews for a location
 * Usage: [wcmlim_google_reviews location_id="123"] OR [wcmlim_google_reviews] (auto-detects selected location)
 */
function wcmlim_google_reviews_shortcode( $atts ) {
	$atts = shortcode_atts(
		array(
			'location_id' => '',
			'limit'       => 5,
			'show_rating' => 'yes',
		),
		$atts,
		'wcmlim_google_reviews'
	);

	// DEBUG: Show we're in the shortcode
	$debug_output = '';
	if ( current_user_can( 'manage_options' ) ) {
		$debug_output .= '<!-- WCMLIM Reviews Debug: Shortcode called, atts location_id=' . $atts['location_id'] . ' -->';
	}

	// Auto-detect location if not specified
	if ( empty( $atts['location_id'] ) ) {
		$location_id = null;
		$debug_info = array();
		
		// First, try to get by location name (most reliable)
		if ( isset( $_COOKIE['wcmlim_selected_location'] ) && ! empty( $_COOKIE['wcmlim_selected_location'] ) ) {
			$location_name = sanitize_text_field( $_COOKIE['wcmlim_selected_location'] );
			$debug_info['cookie_name'] = $location_name;
			
			$term_by_name = get_term_by( 'name', $location_name, 'locations' );
			$debug_info['term_by_name_result'] = $term_by_name ? 'Found: ' . $term_by_name->term_id : 'Not found';
			
			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' );
			$debug_info['getLocation_name'] = $location_name;
			
			if ( ! empty( $location_name ) ) {
				$term_by_name = get_term_by( 'name', $location_name, 'locations' );
				$debug_info['term_by_name_result2'] = $term_by_name ? 'Found: ' . $term_by_name->term_id : 'Not found';
				
				if ( $term_by_name && ! is_wp_error( $term_by_name ) ) {
					$location_id = $term_by_name->term_id;
				}
			}
		}
		
		// If name-based lookup failed, try term ID as fallback
		if ( empty( $location_id ) ) {
			if ( isset( $_COOKIE['wcmlim_selected_location_termid'] ) ) {
				$location_id = intval( $_COOKIE['wcmlim_selected_location_termid'] );
				$debug_info['cookie_termid'] = $location_id;
			} elseif ( function_exists( 'getLocation' ) ) {
				$location_id = getLocation( 'wcmlim_selected_location_termid' );
				$debug_info['getLocation_termid'] = $location_id;
			}
			
			// Validate the term ID exists
			if ( ! empty( $location_id ) ) {
				$test_term = get_term( $location_id, 'locations' );
				if ( is_wp_error( $test_term ) || ! $test_term ) {
					$debug_info['termid_validation'] = 'Invalid';
					$location_id = null;
				} else {
					$debug_info['termid_validation'] = 'Valid';
				}
			}
		}
		
		if ( empty( $location_id ) ) {
			$msg = esc_html__( 'Please select a location to view reviews.', 'wcmlim' );
			if ( current_user_can( 'manage_options' ) && ! empty( $debug_info ) ) {
				$msg .= ' (Debug: ' . print_r( $debug_info, true ) . ')';
			}
			return '<div class="wcmlim-google-reviews-notice"><p>' . $msg . '</p></div>';
		}
	} else {
		$location_id = intval( $atts['location_id'] );
	}

	$limit = intval( $atts['limit'] );
	
	// Get location term to display name
	$location_term = get_term( $location_id, 'locations' );
	
	// Debug: If admin, show what we're trying to retrieve
	if ( is_wp_error( $location_term ) || ! $location_term ) {
		$error_msg = esc_html__( 'Invalid location.', 'wcmlim' ) . ' [v2.0]';
		
		// Show debug info for admins
		if ( current_user_can( 'manage_options' ) ) {
			$error_msg .= ' (Debug: Location ID=' . $location_id;
			if ( is_wp_error( $location_term ) ) {
				$error_msg .= ', Error: ' . $location_term->get_error_message();
			} else {
				$error_msg .= ', Term not found in "locations" taxonomy';
			}
			
			// Show available locations to help debug
			$all_locations = get_terms( array( 'taxonomy' => 'locations', 'hide_empty' => false ) );
			if ( ! is_wp_error( $all_locations ) && ! empty( $all_locations ) ) {
				$error_msg .= '. Available locations: ';
				$loc_list = array();
				foreach ( $all_locations as $loc ) {
					$loc_list[] = $loc->name . ' (ID: ' . $loc->term_id . ')';
				}
				$error_msg .= implode( ', ', $loc_list );
			}
			
			$error_msg .= ')';
		}
		
		return '<div class="wcmlim-google-reviews-error"><p>' . $error_msg . '</p></div>';
	}
	
	$place_id = get_term_meta( $location_id, 'google_place_id', true );
	
	// If no Place ID, show admin-friendly message
	if ( empty( $place_id ) ) {
		$message = sprintf(
			__( 'No Google Place ID configured for this location.', 'wcmlim' )
		);
		
		// If admin, show edit link
		if ( current_user_can( 'manage_options' ) ) {
			$edit_url = admin_url( 'term.php?taxonomy=locations&tag_ID=' . $location_id );
			$message .= ' <a href="' . esc_url( $edit_url ) . '">' . esc_html__( 'Edit', 'wcmlim' ) . '</a>';
		}
		
		return '<div class="wcmlim-google-reviews-notice"><p>' . $message . '</p></div>';
	}
	
	$reviews_data = wcmlim_get_google_reviews( $location_id );

	if ( is_wp_error( $reviews_data ) ) {
		return '<div class="wcmlim-google-reviews-error"><p>' . esc_html( $reviews_data->get_error_message() ) . '</p></div>';
	}

	ob_start();
	
	// Add inline styles to ensure they load
	wcmlim_add_inline_reviews_styles();
	
	?>
	<div class="wcmlim-google-reviews" data-location-id="<?php echo esc_attr( $location_id ); ?>">
		
		<div class="wcmlim-reviews-header">
			<h3 class="wcmlim-reviews-title">
				<?php 
				printf( 
					esc_html__( 'Reviews for %s', 'wcmlim' ), 
					esc_html( $location_term->name ) 
				); 
				?>
			</h3>
		</div>
		
		<?php if ( $atts['show_rating'] === 'yes' && ! empty( $reviews_data['rating'] ) ) : ?>
			<div class="wcmlim-reviews-summary">
				<div class="wcmlim-reviews-rating">
					<span class="wcmlim-rating-number"><?php echo esc_html( number_format( $reviews_data['rating'], 1 ) ); ?></span>
					<span class="wcmlim-rating-stars"><?php echo wcmlim_get_star_rating( $reviews_data['rating'] ); ?></span>
					<span class="wcmlim-rating-count">
						<?php 
						printf( 
							_n( '%s review', '%s reviews', $reviews_data['user_ratings_total'], 'wcmlim' ),
							number_format_i18n( $reviews_data['user_ratings_total'] )
						);
						?>
					</span>
				</div>
			</div>
		<?php endif; ?>

		<?php if ( ! empty( $reviews_data['reviews'] ) ) : ?>
			<div class="wcmlim-reviews-list">
				<?php 
				$reviews_to_show = array_slice( $reviews_data['reviews'], 0, $limit );
				foreach ( $reviews_to_show as $review ) : 
				?>
					<div class="wcmlim-review-item">
						<div class="wcmlim-review-header">
							<?php if ( ! empty( $review['profile_photo_url'] ) ) : ?>
								<img src="<?php echo esc_url( $review['profile_photo_url'] ); ?>" alt="<?php echo esc_attr( $review['author_name'] ); ?>" class="wcmlim-review-avatar" />
							<?php endif; ?>
							<div class="wcmlim-review-author-info">
								<span class="wcmlim-review-author"><?php echo esc_html( $review['author_name'] ); ?></span>
								<div class="wcmlim-review-meta">
									<span class="wcmlim-review-rating"><?php echo wcmlim_get_star_rating( $review['rating'] ); ?></span>
									<span class="wcmlim-review-time"><?php echo esc_html( $review['relative_time_description'] ); ?></span>
								</div>
							</div>
						</div>
						<div class="wcmlim-review-text">
							<?php echo esc_html( $review['text'] ); ?>
						</div>
					</div>
				<?php endforeach; ?>
			</div>
		<?php else : ?>
			<p><?php esc_html_e( 'No reviews available yet.', 'wcmlim' ); ?></p>
		<?php endif; ?>

		<div class="wcmlim-reviews-footer">
			<a href="https://search.google.com/local/writereview?placeid=<?php echo esc_attr( get_term_meta( $location_id, 'google_place_id', true ) ); ?>" target="_blank" class="wcmlim-write-review-btn">
				<?php esc_html_e( 'Write a Review', 'wcmlim' ); ?>
			</a>
		</div>
	</div>
	<?php
	return ob_get_clean();
}
add_shortcode( 'wcmlim_google_reviews', 'wcmlim_google_reviews_shortcode' );

/**
 * Generate star rating HTML
 */
function wcmlim_get_star_rating( $rating ) {
	$rating = floatval( $rating );
	$full_stars = floor( $rating );
	$half_star = ( $rating - $full_stars ) >= 0.5;
	$empty_stars = 5 - $full_stars - ( $half_star ? 1 : 0 );

	$html = '<span class="wcmlim-stars">';
	
	// 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;
}

/**
 * Enqueue frontend styles for reviews
 */
function wcmlim_enqueue_reviews_styles() {
	// Always enqueue on shop and product pages
	if ( is_shop() || is_product() || is_page() || has_shortcode( get_the_content(), 'wcmlim_google_reviews' ) ) {
		wp_enqueue_style( 'wcmlim-google-reviews', false );
		wp_add_inline_style( 'wcmlim-google-reviews', wcmlim_get_reviews_css() );
	}
}
add_action( 'wp_enqueue_scripts', 'wcmlim_enqueue_reviews_styles', 999 );

// Also add styles directly to the shortcode output as fallback
function wcmlim_add_inline_reviews_styles() {
	static $styles_added = false;
	if ( ! $styles_added ) {
		echo '<style>' . wcmlim_get_reviews_css() . '</style>';
		$styles_added = true;
	}
}

/**
 * Get reviews CSS
 */
function wcmlim_get_reviews_css() {
	return '
		.wcmlim-google-reviews {
			max-width: 1200px;
			margin: 40px auto !important;
			font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, sans-serif !important;
			background: #ffffff !important;
			border-radius: 16px !important;
			box-shadow: 0 4px 20px rgba(0,0,0,0.12) !important;
			padding: 40px !important;
		}
		.wcmlim-reviews-header {
			margin-bottom: 30px !important;
			text-align: center !important;
			border-bottom: 3px solid #f0f0f0 !important;
			padding-bottom: 25px !important;
		}
		.wcmlim-reviews-title {
			font-size: 36px !important;
			font-weight: 700 !important;
			color: #1a1a1a !important;
			margin: 0 0 15px 0 !important;
			letter-spacing: -0.5px !important;
		}
		.wcmlim-reviews-summary {
			background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
			padding: 30px 40px !important;
			border-radius: 20px !important;
			margin-bottom: 35px !important;
			text-align: center !important;
			box-shadow: 0 10px 30px rgba(102, 126, 234, 0.4) !important;
			color: white !important;
		}
		.wcmlim-reviews-rating {
			display: flex !important;
			flex-direction: column !important;
			align-items: center !important;
			gap: 10px !important;
		}
		.wcmlim-rating-number {
			font-size: 64px !important;
			font-weight: 800 !important;
			color: #ffffff !important;
			line-height: 1 !important;
			text-shadow: 0 4px 8px rgba(0,0,0,0.3) !important;
		}
		.wcmlim-rating-stars {
			font-size: 32px !important;
			display: block !important;
			letter-spacing: 6px !important;
			margin: 5px 0 !important;
		}
		.wcmlim-rating-count {
			color: rgba(255,255,255,0.95) !important;
			font-size: 18px !important;
			font-weight: 500 !important;
			margin-top: 5px !important;
		}
		.wcmlim-star {
			display: inline-block !important;
			transition: transform 0.2s ease !important;
		}
		.wcmlim-star-full {
			color: #FFD700 !important;
			text-shadow: 0 0 10px rgba(255, 215, 0, 0.6), 0 0 20px rgba(255, 215, 0, 0.4) !important;
		}
		.wcmlim-star-half {
			color: #FFD700 !important;
			opacity: 0.7 !important;
			text-shadow: 0 0 8px rgba(255, 215, 0, 0.5) !important;
		}
		.wcmlim-star-empty {
			color: rgba(255,255,255,0.3) !important;
		}
		.wcmlim-reviews-list {
			margin: 35px 0 !important;
			display: grid !important;
			gap: 25px !important;
		}
		.wcmlim-review-item {
			background: #ffffff !important;
			border: 2px solid #e8e8e8 !important;
			border-radius: 16px !important;
			padding: 30px !important;
			transition: all 0.3s ease !important;
			box-shadow: 0 2px 8px rgba(0,0,0,0.08) !important;
		}
		.wcmlim-review-item:hover {
			box-shadow: 0 12px 24px rgba(102, 126, 234, 0.2) !important;
			transform: translateY(-4px) !important;
			border-color: #667eea !important;
		}
		.wcmlim-review-header {
			display: flex !important;
			align-items: flex-start !important;
			margin-bottom: 20px !important;
			gap: 20px !important;
		}
		.wcmlim-review-avatar {
			width: 64px !important;
			height: 64px !important;
			border-radius: 50% !important;
			object-fit: cover !important;
			border: 4px solid #667eea !important;
			box-shadow: 0 4px 12px rgba(102, 126, 234, 0.4) !important;
			flex-shrink: 0 !important;
		}
		.wcmlim-review-author-info {
			flex: 1 !important;
		}
		.wcmlim-review-author {
			font-weight: 700 !important;
			color: #1a1a1a !important;
			display: block !important;
			margin-bottom: 8px !important;
			font-size: 18px !important;
		}
		.wcmlim-review-meta {
			display: flex !important;
			align-items: center !important;
			gap: 15px !important;
			flex-wrap: wrap !important;
		}
		.wcmlim-review-rating {
			font-size: 20px !important;
		}
		.wcmlim-review-rating .wcmlim-star-full {
			color: #ffa500 !important;
			text-shadow: 0 0 6px rgba(255, 165, 0, 0.4) !important;
		}
		.wcmlim-review-rating .wcmlim-star-empty {
			color: #ddd !important;
		}
		.wcmlim-review-time {
			color: #999 !important;
			font-size: 14px !important;
			font-weight: 500 !important;
		}
		.wcmlim-review-text {
			color: #4a4a4a !important;
			line-height: 1.8 !important;
			font-size: 16px !important;
			padding: 20px !important;
			background: linear-gradient(135deg, #f9f9f9 0%, #f5f5f5 100%) !important;
			border-radius: 12px !important;
			border-left: 5px solid #667eea !important;
		}
		.wcmlim-reviews-footer {
			text-align: center !important;
			margin-top: 40px !important;
			padding-top: 30px !important;
			border-top: 3px solid #f0f0f0 !important;
		}
		.wcmlim-write-review-btn {
			display: inline-flex !important;
			align-items: center !important;
			gap: 12px !important;
			background: linear-gradient(135deg, #667eea 0%, #764ba2 100%) !important;
			color: #fff !important;
			padding: 18px 40px !important;
			border-radius: 50px !important;
			text-decoration: none !important;
			font-weight: 600 !important;
			font-size: 18px !important;
			transition: all 0.3s ease !important;
			box-shadow: 0 6px 20px rgba(102, 126, 234, 0.5) !important;
			border: none !important;
			cursor: pointer !important;
		}
		.wcmlim-write-review-btn:before {
			content: "✍️" !important;
			font-size: 24px !important;
		}
		.wcmlim-write-review-btn:hover {
			transform: translateY(-3px) !important;
			box-shadow: 0 10px 30px rgba(102, 126, 234, 0.6) !important;
			color: #fff !important;
			text-decoration: none !important;
		}
		.wcmlim-write-review-btn:active {
			transform: translateY(0) !important;
		}
		
		/* Responsive Design */
		@media (max-width: 768px) {
			.wcmlim-google-reviews {
				padding: 25px !important;
				margin: 20px 15px !important;
			}
			.wcmlim-reviews-title {
				font-size: 28px !important;
			}
			.wcmlim-rating-number {
				font-size: 56px !important;
			}
			.wcmlim-rating-stars {
				font-size: 28px !important;
			}
			.wcmlim-review-header {
				flex-direction: row !important;
				align-items: flex-start !important;
			}
			.wcmlim-review-avatar {
				width: 52px !important;
				height: 52px !important;
			}
			.wcmlim-review-text {
				font-size: 15px !important;
			}
		}
	';
}

/**
 * AJAX handler to refresh reviews
 */
function wcmlim_ajax_refresh_reviews() {
	check_ajax_referer( 'wcmlim_reviews_nonce', 'nonce' );
	
	$location_id = isset( $_POST['location_id'] ) ? intval( $_POST['location_id'] ) : 0;
	
	if ( ! $location_id ) {
		wp_send_json_error( array( 'message' => __( 'Invalid location ID', 'wcmlim' ) ) );
	}
	
	$reviews = wcmlim_get_google_reviews( $location_id, true );
	
	if ( is_wp_error( $reviews ) ) {
		wp_send_json_error( array( 'message' => $reviews->get_error_message() ) );
	}
	
	wp_send_json_success( array( 'reviews' => $reviews ) );
}
add_action( 'wp_ajax_wcmlim_refresh_reviews', 'wcmlim_ajax_refresh_reviews' );
add_action( 'wp_ajax_nopriv_wcmlim_refresh_reviews', 'wcmlim_ajax_refresh_reviews' );
