<?php

/**
 * Yoast SEO.
 *
 * @link    https://aiopodcasting.com
 * @since   1.0.0
 *
 * @package AiO_Podcast_Studio
 */

// Exit if accessed directly
if ( ! defined( 'WPINC' ) ) {
	die;
}

/**
 * AIOPOD_Public_Yoast class.
 *
 * @since 1.0.0
 */
class AIOPOD_Public_Yoast {

	/**
	 * Construct Yoast SEO title for our category and user podcasts pages.
	 *
	 * @since  1.0.0
	 * @param  array $title The Yoast title.
	 * @return              Filtered title.
	 */
	public function wpseo_title( $title ) {	
		global $post;

		if ( ! isset( $post ) ) {
			return $title;
		}

		$pages_settings = aiopod_get_option( 'aiopod_pages_settings' );

		if ( $post->ID !== (int) $pages_settings['category'] && $post->ID !== (int) $pages_settings['tag'] ) {
			return $title;
		}

		$wpseo_titles = get_option( 'wpseo_titles' );

		$sep_options = WPSEO_Option_Titles::get_instance()->get_separator_options();

		if ( isset( $wpseo_titles['separator'] ) && isset( $sep_options[ $wpseo_titles['separator'] ] ) ) {
			$sep = $sep_options[ $wpseo_titles['separator'] ];
		} else {
			$sep = '-'; // Setting default separator if Admin didn't set it from backed
		}

		$replacements = array(
			'%%sep%%'              => $sep,						
			'%%page%%'             => '',
			'%%primary_category%%' => '',
			'%%sitename%%'         => sanitize_text_field( get_bloginfo( 'name' ) )
		);

		$title_template = '';
		
		// Category page
		if ( $post->ID === (int) $pages_settings['category'] ) {			
			if ( $slug = get_query_var( 'aiopod_category' ) ) {
				// Get Archive SEO title
				if ( array_key_exists( 'title-tax-aiopod_categories', $wpseo_titles ) ) {
					$title_template = $wpseo_titles['title-tax-aiopod_categories'];
				}

				// Get Term SEO title
				if ( $term = get_term_by( 'slug', $slug, 'aiopod_categories' ) ) {		
					$replacements['%%term_title%%'] = $term->name;
					
					$meta = get_option( 'wpseo_taxonomy_meta' );

					if ( array_key_exists( 'aiopod_categories', $meta ) ) {
						if ( array_key_exists( $term->term_id, $meta['aiopod_categories'] ) ) {
							if ( array_key_exists( 'wpseo_title', $meta['aiopod_categories'][ $term->term_id ] ) ) {
								$title_template = $meta['aiopod_categories'][ $term->term_id ]['wpseo_title'];
							}
						}
					}
				}
			}				
		}

		// Tag page
		if ( $post->ID === (int) $pages_settings['tag'] ) {			
			if ( $slug = get_query_var( 'aiopod_tag' ) ) {
				// Get Archive SEO title
				if ( array_key_exists( 'title-tax-aiopod_tags', $wpseo_titles ) ) {
					$title_template = $wpseo_titles['title-tax-aiopod_tags'];
				}

				// Get Term SEO title
				if ( $term = get_term_by( 'slug', $slug, 'aiopod_tags' ) ) {		
					$replacements['%%term_title%%'] = $term->name;
					
					$meta = get_option( 'wpseo_taxonomy_meta' );

					if ( array_key_exists( 'aiopod_tags', $meta ) ) {
						if ( array_key_exists( $term->term_id, $meta['aiopod_tags'] ) ) {
							if ( array_key_exists( 'wpseo_title', $meta['aiopod_tags'][ $term->term_id ] ) ) {
								$title_template = $meta['aiopod_tags'][ $term->term_id ]['wpseo_title'];
							}
						}
					}
				}
			}				
		}

		// Participant page
		if ( $post->ID === (int) $pages_settings['participant'] ) {			
			if ( $slug = get_query_var( 'aiopod_participant' ) ) {
				// Get Archive SEO title
				if ( array_key_exists( 'title-tax-aiopod_participants', $wpseo_titles ) ) {
					$title_template = $wpseo_titles['title-tax-aiopod_participants'];
				}

				// Get Term SEO title
				if ( $term = get_term_by( 'slug', $slug, 'aiopod_participants' ) ) {		
					$replacements['%%term_title%%'] = $term->name;
					
					$meta = get_option( 'wpseo_taxonomy_meta' );

					if ( array_key_exists( 'aiopod_participants', $meta ) ) {
						if ( array_key_exists( $term->term_id, $meta['aiopod_participants'] ) ) {
							if ( array_key_exists( 'wpseo_title', $meta['aiopod_participants'][ $term->term_id ] ) ) {
								$title_template = $meta['aiopod_participants'][ $term->term_id ]['wpseo_title'];
							}
						}
					}
				}
			}				
		}
		
		// Return
		if ( ! empty( $title_template ) ) {
			$title = strtr( $title_template, $replacements );
		}

		return $title;	
	}

	/**
	 * Construct Yoast SEO description for our category and user podcasts pages.
	 *
	 * @since  1.0.0
	 * @param  array $desc The Yoast description.
	 * @return             Filtered description.
	 */
	public function wpseo_metadesc( $desc ) {	
		global $post;

		if ( ! isset( $post ) ) {
			return $desc;
		}

		$pages_settings = aiopod_get_option( 'aiopod_pages_settings' );
		
		if ( $post->ID != $pages_settings['category'] && $post->ID != $pages_settings['tag'] ) {
			return $desc;
		}

		$wpseo_titles = get_option( 'wpseo_titles' );

		$sep_options = WPSEO_Option_Titles::get_instance()->get_separator_options();

		if ( isset( $wpseo_titles['separator'] ) && isset( $sep_options[ $wpseo_titles['separator'] ] ) ) {
			$sep = $sep_options[ $wpseo_titles['separator'] ];
		} else {
			$sep = '-'; // Setting default separator if Admin didn't set it from backed
		}

		$replacements = array(
			'%%sep%%'              => $sep,						
			'%%page%%'             => '',
			'%%title%%'            => '',
			'%%primary_category%%' => '',
			'%%sitename%%'         => sanitize_text_field( get_bloginfo( 'name' ) )
		);

		$desc_template = '';

		// Category page
		if ( $post->ID === (int) $pages_settings['category'] ) {			
			if ( $slug = get_query_var( 'aiopod_category' ) ) {
				// Get Archive SEO desc
				if ( array_key_exists( 'metadesc-tax-aiopod_categories', $wpseo_titles ) ) {
					$desc_template = $wpseo_titles['metadesc-tax-aiopod_categories'];
				}

				// Get Term SEO desc
				if ( $term = get_term_by( 'slug', $slug, 'aiopod_categories' ) ) {
					$replacements['%%term_title%%'] = $term->name;
					
					$meta = get_option( 'wpseo_taxonomy_meta' );

					if ( array_key_exists( 'aiopod_categories', $meta ) ) {
						if ( array_key_exists( $term->term_id, $meta['aiopod_categories'] ) ) {
							if ( array_key_exists( 'wpseo_desc', $meta['aiopod_categories'][ $term->term_id ] ) ) {
								$desc_template = $meta['aiopod_categories'][ $term->term_id ]['wpseo_desc'];
							}
						}
					}
				}
			}				
		}

		// Tag page
		if ( $post->ID === (int) $pages_settings['tag'] ) {			
			if ( $slug = get_query_var( 'aiopod_tag' ) ) {
				// Get Archive SEO desc
				if ( array_key_exists( 'metadesc-tax-aiopod_tags', $wpseo_titles ) ) {
					$desc_template = $wpseo_titles['metadesc-tax-aiopod_tags'];
				}

				// Get Term SEO desc
				if ( $term = get_term_by( 'slug', $slug, 'aiopod_tags' ) ) {
					$replacements['%%term_title%%'] = $term->name;	
					
					$meta = get_option( 'wpseo_taxonomy_meta' );

					if ( array_key_exists( 'aiopod_tags', $meta ) ) {
						if ( array_key_exists( $term->term_id, $meta['aiopod_tags'] ) ) {
							if ( array_key_exists( 'wpseo_desc', $meta['aiopod_tags'][ $term->term_id ] ) ) {
								$desc_template = $meta['aiopod_tags'][ $term->term_id ]['wpseo_desc'];
							}
						}
					}
				}
			}				
		}

		// Participant page
		if ( $post->ID === (int) $pages_settings['participant'] ) {			
			if ( $slug = get_query_var( 'aiopod_participant' ) ) {
				// Get Archive SEO desc
				if ( array_key_exists( 'metadesc-tax-aiopod_participants', $wpseo_titles ) ) {
					$desc_template = $wpseo_titles['metadesc-tax-aiopod_participants'];
				}

				// Get Term SEO desc
				if ( $term = get_term_by( 'slug', $slug, 'aiopod_participants' ) ) {
					$replacements['%%term_title%%'] = $term->name;	
					
					$meta = get_option( 'wpseo_taxonomy_meta' );

					if ( array_key_exists( 'aiopod_participants', $meta ) ) {
						if ( array_key_exists( $term->term_id, $meta['aiopod_participants'] ) ) {
							if ( array_key_exists( 'wpseo_desc', $meta['aiopod_participants'][ $term->term_id ] ) ) {
								$desc_template = $meta['aiopod_participants'][ $term->term_id ]['wpseo_desc'];
							}
						}
					}
				}
			}				
		}
		
		// Return
		if ( ! empty( $desc_template ) ) {
			$desc = strtr( $desc_template, $replacements );
		}

		return $desc;	
	}

	/**
	 * Override the Yoast SEO canonical URL on our category and user podcasts pages.
	 *
	 * @since  1.0.0
	 * @param  array $url The Yoast canonical URL.
	 * @return            Filtered canonical URL.
	 */
	public function wpseo_canonical( $url ) {	
		global $post;

		if ( ! isset( $post ) ) {
			return $url;
		}
		
		$pages_settings = aiopod_get_option( 'aiopod_pages_settings' );

		// Category page
		if ( $post->ID === (int) $pages_settings['category'] ) {			
			if ( $slug = get_query_var( 'aiopod_category' ) ) {
				if ( $term = get_term_by( 'slug', $slug, 'aiopod_categories' ) ) {
					$url = aiopod_get_category_page_url( $term );
				}
			}				
		}

		// Tag page
		if ( $post->ID === (int) $pages_settings['tag'] ) {			
			if ( $slug = get_query_var( 'aiopod_tag' ) ) {
				if ( $term = get_term_by( 'slug', $slug, 'aiopod_tags' ) ) {
					$url = aiopod_get_tag_page_url( $term );
				}
			}				
		}

		// Participant page
		if ( $post->ID === (int) $pages_settings['participant'] ) {			
			if ( $slug = get_query_var( 'aiopod_participant' ) ) {
				if ( $term = get_term_by( 'slug', $slug, 'aiopod_participants' ) ) {
					$url = aiopod_get_participant_page_url( $term );
				}
			}				
		}
		
		// Return
		return $url;	
	}

	/**
	 * Override the Yoast SEO Open Graph image URLs on our plugin pages.
	 *
	 * @since  1.0.0
	 * @param  array $url The Yoast image URL.
	 * @return            Filtered image URL.
	 */
	public function wpseo_opengraph_image( $url ) {
		global $post;

		if ( ! isset( $post ) ) {
			return $url;
		}
		
		if ( is_singular( array( 'aiopod_podcasts', 'aiopod_episodes' ) ) ) {
			$image = get_post_meta( $post->ID, '_yoast_wpseo_opengraph-image', true );

			if ( empty( $image ) ) {
				$image_data = aiopod_get_image(	array(
					'post_id' => $post->ID,
					'size'    => 'large',
					'alt'     => ''
				) );

				$image = $image_data['src'];
			}
			
			if ( ! empty( $image ) ) {
				$url = $image;
			}			
		} else {
			$pages_settings = aiopod_get_option( 'aiopod_pages_settings' );

			// Category page
			if ( $post->ID === (int) $pages_settings['category'] ) {			
				if ( $slug = get_query_var( 'aiopod_category' ) ) {
					if ( $term = get_term_by( 'slug', $slug, 'aiopod_categories' ) ) {
						$meta  = get_option( 'wpseo_taxonomy_meta' );
						$image = '';

						if ( array_key_exists( 'aiopod_categories', $meta ) ) { // Get custom share image from Yoast
							if ( array_key_exists( $term->term_id, $meta['aiopod_categories'] ) ) {
								if ( array_key_exists( 'wpseo_opengraph-image', $meta['aiopod_categories'][ $term->term_id ] ) ) {
									$image = $meta['aiopod_categories'][ $term->term_id ]['wpseo_opengraph-image'];
								}
							}
						}

						if ( empty( $image ) ) {
							$image_data = aiopod_get_image(	array(
								'term_id' => $term->term_id,
								'size'    => 'large',
								'alt'     => ''
							) );

							$image = $image_data['src'];
						}

						if ( ! empty( $image ) ) {
							$url = $image;
						}
					}
				}				
			}

			// Tag page
			if ( $post->ID === (int) $pages_settings['tag'] ) {			
				if ( $slug = get_query_var( 'aiopod_tag' ) ) {
					if ( $term = get_term_by( 'slug', $slug, 'aiopod_tags' ) ) {
						$meta  = get_option( 'wpseo_taxonomy_meta' );
						$image = '';

						if ( array_key_exists( 'aiopod_tags', $meta ) ) { // Get custom share image from Yoast
							if ( array_key_exists( $term->term_id, $meta['aiopod_tags'] ) ) {
								if ( array_key_exists( 'wpseo_opengraph-image', $meta['aiopod_tags'][ $term->term_id ] ) ) {
									$image = $meta['aiopod_tags'][ $term->term_id ]['wpseo_opengraph-image'];
								}
							}
						}

						if ( ! empty( $image ) ) {
							$url = $image;
						}
					}
				}				
			}

			// Participant page
			if ( $post->ID === (int) $pages_settings['participant'] ) {			
				if ( $slug = get_query_var( 'aiopod_participant' ) ) {
					if ( $term = get_term_by( 'slug', $slug, 'aiopod_participants' ) ) {
						$meta  = get_option( 'wpseo_taxonomy_meta' );
						$image = '';

						if ( array_key_exists( 'aiopod_participants', $meta ) ) { // Get custom share image from Yoast
							if ( array_key_exists( $term->term_id, $meta['aiopod_participants'] ) ) {
								if ( array_key_exists( 'wpseo_opengraph-image', $meta['aiopod_participants'][ $term->term_id ] ) ) {
									$image = $meta['aiopod_participants'][ $term->term_id ]['wpseo_opengraph-image'];
								}
							}
						}

						if ( ! empty( $image ) ) {
							$url = $image;
						}
					}
				}				
			}
		}

		// Return
		return $url;
	}

	/**
	 * Add custom Twitter Social Share images for Yoast SEO.
	 *
	 * @since  1.0.0
	 * @param  array $url The Yoast image URL.
	 * @return            Filtered image URL.
	 */
	public function wpseo_twitter_image( $url ) {
		global $post;

		if ( ! isset( $post ) ) {
			return $url;
		}
		
		if ( is_singular( array( 'aiopod_podcasts', 'aiopod_episodes' ) ) ) {
			$image = get_post_meta( $post->ID, '_yoast_wpseo_twitter-image', true );

			if ( empty( $image ) ) {
				$image_data = aiopod_get_image(	array(
					'post_id' => $post->ID,
					'size'    => 'large',
					'alt'     => ''
				) );

				$image = $image_data['src'];
			}
			
			if ( ! empty( $image ) ) {
				$url = $image;
			}			
		} else {
			$pages_settings = aiopod_get_option( 'aiopod_pages_settings' );

			// Category page
			if ( $post->ID === (int) $pages_settings['category'] ) {			
				if ( $slug = get_query_var( 'aiopod_category' ) ) {
					if ( $term = get_term_by( 'slug', $slug, 'aiopod_categories' ) ) {
						$meta  = get_option( 'wpseo_taxonomy_meta' );
						$image = '';

						if ( array_key_exists( 'aiopod_categories', $meta ) ) { // Get custom share image from Yoast
							if ( array_key_exists( $term->term_id, $meta['aiopod_categories'] ) ) {
								if ( array_key_exists( 'wpseo_twitter-image', $meta['aiopod_categories'][ $term->term_id ] ) ) {
									$image = $meta['aiopod_categories'][ $term->term_id ]['wpseo_twitter-image'];
								}
							}
						}

						if ( empty( $image ) ) {
							$image_data = aiopod_get_image(	array(
								'term_id' => $term->term_id,
								'size'    => 'large',
								'alt'     => ''
							) );

							$image = $image_data['src'];
						}

						if ( ! empty( $image ) ) {
							$url = $image;
						}	
					}				
				}				
			}

			// Tag page
			if ( $post->ID === (int) $pages_settings['tag'] ) {			
				if ( $slug = get_query_var( 'aiopod_tag' ) ) {
					if ( $term = get_term_by( 'slug', $slug, 'aiopod_tags' ) ) {
						$meta  = get_option( 'wpseo_taxonomy_meta' );
						$image = '';

						if ( array_key_exists( 'aiopod_tags', $meta ) ) { // Get custom share image from Yoast
							if ( array_key_exists( $term->term_id, $meta['aiopod_tags'] ) ) {
								if ( array_key_exists( 'wpseo_twitter-image', $meta['aiopod_tags'][ $term->term_id ] ) ) {
									$image = $meta['aiopod_tags'][ $term->term_id ]['wpseo_twitter-image'];
								}
							}
						}

						if ( ! empty( $image ) ) {
							$url = $image;	
						}
					}				
				}				
			}

			// Participant page
			if ( $post->ID === (int) $pages_settings['participant'] ) {			
				if ( $slug = get_query_var( 'aiopod_participant' ) ) {
					if ( $term = get_term_by( 'slug', $slug, 'aiopod_participants' ) ) {
						$meta  = get_option( 'wpseo_taxonomy_meta' );
						$image = '';

						if ( array_key_exists( 'aiopod_participants', $meta ) ) { // Get custom share image from Yoast
							if ( array_key_exists( $term->term_id, $meta['aiopod_participants'] ) ) {
								if ( array_key_exists( 'wpseo_twitter-image', $meta['aiopod_participants'][ $term->term_id ] ) ) {
									$image = $meta['aiopod_participants'][ $term->term_id ]['wpseo_twitter-image'];
								}
							}
						}

						if ( ! empty( $image ) ) {
							$url = $image;	
						}
					}				
				}				
			}
		}

		// Return
		return $url;
	}

	/**
	 * Filter Yoast SEO breadcrumbs.
	 *
	 * @since  1.0.0
	 * @param  array $crumbs Array of crumbs.
	 * @return array $crumbs Filtered array of crumbs.
	 */
	public function wpseo_breadcrumb_links( $crumbs ) {
		global $post;

		if ( empty( $post ) ) {
			return $crumbs;
		}

		// Explicit CPT → option key mapping (future-proof)
		$archive_map = array(
			'aiopod_podcasts' => 'podcast',
			'aiopod_episodes' => 'episode'
		);

		$allowed_post_types = array_keys( $archive_map );

		if ( is_singular( $allowed_post_types ) ) {
			$pages_settings = aiopod_get_option( 'aiopod_pages_settings' );

			foreach ( $crumbs as $index => $crumb ) {
				// Only modify post-type archive crumbs.
				if ( empty( $crumb['ptarchive'] ) || ! in_array( $crumb['ptarchive'], $allowed_post_types ) ) {
					continue;
				}

				$option_key = $archive_map[ $crumb['ptarchive'] ];

				if ( empty( $pages_settings[ $option_key ] ) ) {
					continue;
				}

				$page_id  = (int) $pages_settings[ $option_key ];
				$page_url = get_permalink( $page_id );

				// Update breadcrumb only if the page exists.
				if ( $page_url ) {
					$obj = get_post_type_object( $crumb['ptarchive'] );

					$crumbs[ $index ] = array(
						'text' => $obj ? $obj->labels->name : $crumb['text'],
						'url'  => $page_url
					);
				}
			}
		} else {
			$pages_settings = aiopod_get_option( 'aiopod_pages_settings' );

			if ( $post->ID === (int) $pages_settings['category'] ) {
				if ( $slug = get_query_var( 'aiopod_category' ) ) {
					if ( $term = get_term_by( 'slug', $slug, 'aiopod_categories' ) ) {
						// Include the parent categories if available
						if ( $ancestors = get_ancestors( $term->term_id, 'aiopod_categories' ) ) {
							$ancestors = array_reverse( $ancestors );

							foreach ( $ancestors as $term_id ) {
								if ( $parent_term = get_term_by( 'term_id', $term_id, 'aiopod_categories' ) ) {
									$crumbs[] = array(
										'text' => $parent_term->name,
										'url'  => aiopod_get_category_page_url( $parent_term )
									);
								}
							}
						}

						// Include the current category page
						$crumbs[] = array(
							'text' => $term->name
						);	
					}		
				}
			}

			if ( $post->ID === (int) $pages_settings['tag'] ) {
				if ( $slug = get_query_var( 'aiopod_tag' ) ) {
					if ( $term = get_term_by( 'slug', $slug, 'aiopod_tags' ) ) {
						$crumbs[] = array(
							'text' => $term->name
						);	
					}		
				}
			}

			if ( $post->ID === (int) $pages_settings['participant'] ) {
				if ( $slug = get_query_var( 'aiopod_participant' ) ) {
					if ( $term = get_term_by( 'slug', $slug, 'aiopod_participants' ) ) {
						$crumbs[] = array(
							'text' => $term->name
						);	
					}		
				}
			}
		}

		return $crumbs;
	}

}
