<?php
namespace Kanews;
use Kanews\Helper_Wp;

class Breadcrumbs {
	
	private static $instance = null;
	private $crumb_position = 0;
	private $post = 0;
	private $crumbs = array();
	private $show_on_front = '';
	private $page_for_posts = '';

	public static function getInstance() {
		if ( ! isset( self::$instance ) && kanews_get_option('breadcrumb') != false && ! is_404()) {
			self::$instance = new self();
		}

		return self::$instance;
	}

	/**
	 * Constructor.
	 *
	 * @since  1.0.0
	 */
	private function __construct() {
		$this->post           = ( isset( $GLOBALS['post'] ) ? $GLOBALS['post'] : null );
		$this->show_on_front  = get_option( 'show_on_front' );
		$this->page_for_posts = get_option( 'page_for_posts' );
		
		add_action( 'wp_head', array( $this, 'set_crumbs' ), 10 );

	}

	/**
	 * Initialize the Schema for the breadcrumbs markup.
	 *
	 * @since  1.0.0
	 *
	 * @param  (Array) $breadcrumb Breadcrumbs array.
	 *
	 * @return (Array) $breadcrumb Breadcrumbs array.
	 */
	private function initialize_breadcrumb_schema( $breadcrumb ) {
		global $wp;
		$current_url = home_url($wp->request);

		$breadcrumb['@context'] = 'http://schema.org';
		$breadcrumb['@type']    = 'BreadcrumbList';
		$breadcrumb['id']       = $current_url.'#breadcrumb';

		return $breadcrumb;
	}

	/**
	 * Adds homepage to the breadcrumb.
	 *
	 * @since  1.0.0
	 */
	private function maybe_add_home_crumb() {
		$this->add_crumb(
			(kanews_get_option('post-breacrumb-main-title') != '' ) ? kanews_get_option('post-breacrumb-main-title')  : esc_html__( 'Haberler', 'kanews' ),
			get_site_url()
		);
	}

	/**
	 * Conditionally adds blog page to the breadcrumb.
	 *
	 * @since  1.0.0
	 */
	private function maybe_add_blog_crumb() {
		if ( ( 'page' === $this->show_on_front && 'post' === get_post_type() ) && ( ! is_home() && ! is_search() ) ) {
			if ( $this->page_for_posts ) {
				$this->add_crumb( get_the_title( $this->page_for_posts ), get_permalink( $this->page_for_posts ) );
			}
		}
	}

	/**
	 * Add crumb to the breadcrumbs array.
	 *
	 * @since  1.0.0
	 *
	 * @param String $name Name of the Breadcrumb element.
	 * @param string $url URL of the Breadcrumb element.
	 * @param string $image Image URL of the Breadcrumb element.
	 */
	private function add_crumb( $name, $url = '', $image = '' ) {
		$this->crumb_position = $this->crumb_position + 1;

		if ( '' === $image ) {
			$this->crumbs[] = array(
				'@type'    => 'ListItem',
				'position' => $this->crumb_position,
				'item'     => array(
					'@id'  => esc_url( $url ),
					'name' => esc_attr( $name ),
				),
			);
		} else {
			$this->crumbs[] = array(
				'@type'    => 'ListItem',
				'position' => $this->crumb_position,
				'item'     => array(
					'@id'   => esc_url( $url ),
					'name'  => esc_attr( $name ),
					'image' => $image,
				),
			);
		}
	}

	/**
	 * Post type archive title.
	 *
	 * @since  1.0.0
	 *
	 * @param  string $pt The name of a registered post type.
	 *
	 * @return String     Title of the post type.
	 */
	private function post_type_archive_title( $pt ) {
		$archive_title = '';

		$post_type_obj = get_post_type_object( $pt );
		if ( is_object( $post_type_obj ) ) {
			if ( isset( $post_type_obj->label ) && '' !== $post_type_obj->label ) {
				$archive_title = $post_type_obj->label;
			} elseif ( isset( $post_type_obj->labels->menu_name ) && '' !== $post_type_obj->labels->menu_name ) {
				$archive_title = $post_type_obj->labels->menu_name;
			} else {
				$archive_title = $post_type_obj->name;
			}
		}

		return $archive_title;
	}

	/**
	 * Conditionally adds the post type archive to the breadcrumb.
	 *
	 * @since  1.0.0
	 */
	private function maybe_add_pt_archive_crumb_for_post() {
		if ( 'post' === $this->post->post_type ) {
			return;
		}
		if ( isset( $this->post->post_type ) && get_post_type_archive_link( $this->post->post_type ) ) {
			$title =  $this->post_type_archive_title( $this->post->post_type );
			if('yazarlar' === $this->post->post_type)
			$title = esc_html__( 'Yazarlar', 'kanews' );
			$this->add_crumb( $title, get_post_type_archive_link( $this->post->post_type ) );
		}
	}

	/**
	 * Conditionally adds taxanomy titles to the breadcrumb.
	 *
	 * @since  1.0.0
	 */
	private function add_crumbs_for_category() {
		$category = Helper_Wp::primary_category_id($this->post->ID);

		if(!isset($category))
		return;

		$this->add_crumb( get_cat_name($category), get_category_link($category) );
	}

	/**
	 * Conditionally adds custom taxonomy titles to the breadcrumb.
	 *
	 * @since  1.0.0
	 *
	 * @param string $taxonomy Taxonomy name.
	 */
	private function add_crumbs_for_custom_taxonomy( $taxonomy ) {
		$terms = get_the_terms( $this->post->ID, $taxonomy );
		
		if ( ! $terms || is_wp_error( $terms ) || empty( $terms ) ) {
			return;
		}

		// Get primary term if available, otherwise use first term
		$primary_term = null;
		$primary_term_id = get_post_meta( $this->post->ID, 'kanews_primary_' . $taxonomy, true );
		
		if ( ! empty( $primary_term_id ) ) {
			foreach ( $terms as $term ) {
				if ( $term->term_id == $primary_term_id ) {
					$primary_term = $term;
					break;
				}
			}
		}

		// If no primary term found, use first term
		if ( ! $primary_term ) {
			$primary_term = $terms[0];
		}

		// Add ancestors if any
		if ( $primary_term->parent ) {
			$ancestors = array_reverse( get_ancestors( $primary_term->term_id, $taxonomy ) );
			foreach ( $ancestors as $ancestor_id ) {
				$ancestor_term = get_term( $ancestor_id, $taxonomy );
				if ( $ancestor_term && ! is_wp_error( $ancestor_term ) ) {
					$this->add_crumb( $ancestor_term->name, Helper_Wp::get_term_link( $ancestor_term, $taxonomy ) );
				}
			}
		}

		// Add current term
		$this->add_crumb( $primary_term->name, Helper_Wp::get_term_link( $primary_term, $taxonomy ) );
	}

	/**
	 * Adds post ancestor to the breadcrumb.
	 *
	 * @since  1.0.0
	 */
	private function add_post_ancestor_crumbs() {
		$ancestors = $this->get_post_ancestors();
		if ( is_array( $ancestors ) && array() !== $ancestors ) {
			foreach ( $ancestors as $ancestor ) {
				$this->add_crumb( get_the_title( $ancestor ), get_permalink( $ancestor ) );
			}
		}
	}

	/**
	 * Finds the post ancestors.
	 *
	 * @since  1.0.0
	 * @return Array Ancestors for the current page.
	 */
	private function get_post_ancestors() {
		$ancestors = array();

		if ( isset( $this->post->ancestors ) ) {
			if ( is_array( $this->post->ancestors ) ) {
				$ancestors = array_values( $this->post->ancestors );
			} else {
				$ancestors = array( $this->post->ancestors );
			}
		} elseif ( isset( $this->post->post_parent ) ) {
			$ancestors = array( $this->post->post_parent );
		}

		// Reverse the order so it's oldest to newest.
		$ancestors = array_reverse( $ancestors );

		return $ancestors;
	}

	/**
	 * Add Taxanomies to breadcrumb.
	 *
	 * @since  1.0.0
	 */
	private function add_crumbs_for_taxonomy() {
		$term = $GLOBALS['wp_query']->get_queried_object();
		
		if ( ! $term || ! isset( $term->taxonomy ) ) {
			return;
		}
		
		$taxonomy = $term->taxonomy;
		
		// Add ancestors if any
		if ( isset( $term->parent ) && $term->parent ) {
			$ancestors = array_reverse( get_ancestors( $term->term_id, $taxonomy ) );
			foreach ( $ancestors as $ancestor_id ) {
				$ancestor_term = get_term( $ancestor_id, $taxonomy );
				if ( $ancestor_term && ! is_wp_error( $ancestor_term ) ) {
					$this->add_crumb( $ancestor_term->name, Helper_Wp::get_term_link( $ancestor_term, $taxonomy ) );
				}
			}
		}
		
		// Add current term
		$this->add_crumb( $term->name, Helper_Wp::get_term_link( $term, $taxonomy ) );
	}

	/**
	 * Add month to the breadcrumb.
	 *
	 * @since  1.0.0
	 */
	private function add_month_crumb() {
		$this->add_crumb(
			'Archives for ' . esc_html( single_month_title( ' ', false ) ),
			get_month_link( get_query_var( 'y' ), get_query_var( 'monthnum' ) )
		);
	}

	/**
	 * Add Month and year to breadcrumb for date archive.
	 *
	 * @since  1.0.0
	 */
	private function add_linked_month_year_crumb() {
		$this->add_crumb(
			$GLOBALS['wp_locale']->get_month( get_query_var( 'monthnum' ) ) . ' ' . get_query_var( 'year' ),
			get_month_link( get_query_var( 'year' ), get_query_var( 'monthnum' ) )
		);
	}

	/**
	 * Add date to the breadcrumb.
	 *
	 * @since  1.0.0
	 */
	private function add_date_crumb() {
		$this->add_crumb(
			'Archives for ' . esc_html( single_month_title( ' ', false ) ),
			get_day_link( get_query_var( 'year' ), get_query_var( 'monthnum' ), get_query_var( 'day' ) )
		);
	}

	/**
	 * Add year to the breadcrumb.
	 *
	 * @since  1.0.0
	 */
	private function add_year_crumb() {
		$this->add_crumb(
			'Archives for ' . esc_html( get_query_var( 'year' ) ),
			get_year_link( get_query_var( 'year' ) )
		);
	}

	/**
	 * Conditionally add individual crumbs to the breadcrumb.
	 *
	 * @since  1.0.0
	 */
	private function add_breadcrumb_crumbs() {
		global $wp_query;
		
		$this->maybe_add_home_crumb();
		$this->maybe_add_blog_crumb();

		if ( 'page' === $this->show_on_front && is_home() ) {
			$this->add_crumb( get_the_title( $this->page_for_posts ), get_permalink( $this->page_for_posts ) );
		} elseif ( is_singular() ) {
			$this->maybe_add_pt_archive_crumb_for_post();

			if ( isset( $this->post->post_parent ) && 0 === $this->post->post_parent ) {
				if('post' === $this->post->post_type) {
					$this->add_crumbs_for_category();
				} elseif('firma' === $this->post->post_type) {
					$this->add_crumbs_for_custom_taxonomy('kategori');
				} elseif('ilan' === $this->post->post_type) {
					$this->add_crumbs_for_custom_taxonomy('ilan-kategori');
				}
			} else {
				$this->add_post_ancestor_crumbs();
			}

			if ( isset( $this->post->ID ) ) {
				$this->add_crumb( get_the_title( $this->post->ID ), get_permalink( $this->post->ID ) );
			}

			if( is_page_template( 'inc/currencies.php' ) ) {
				$name = isset($_GET['parite']) && !empty($_GET['parite']) ? $_GET['parite'] : get_query_var('parite');
				if( $name ) {
					$this->add_crumb(
						strtoupper($name),
						kanews_get_page_link('parite', strtolower($name), 'doviz')
					);
				}
			}elseif( is_page_template( 'inc/exchange.php' ) ) {
				$name = isset($_GET['hisse']) && !empty($_GET['hisse']) ? $_GET['hisse'] : get_query_var('hisse');
				if( $name ) {
					$this->add_crumb(
						strtoupper($name),
						kanews_get_page_link('hisse', strtoupper($name), 'exchange')
					);
				}
			}elseif( is_page_template( 'inc/exchange2.php' ) ) {
				$name = isset($_GET['hisse']) && !empty($_GET['hisse']) ? $_GET['hisse'] : get_query_var('hisse');
				if( $name ) {
					$this->add_crumb(
						explode(':', $name)[1],
						kanews_get_page_link('hisse', strtoupper($name), 'exchange2')
					);
				}
			}elseif( is_page_template( 'inc/emtia.php' ) ) {
				$name = isset($_GET['emtia']) && !empty($_GET['emtia']) ? $_GET['emtia'] : get_query_var('emtia');
				if( $name ) {
					$this->add_crumb(
						strtoupper($name),
						kanews_get_page_link('emtia', strtolower($name), 'emtia')
					);
				}
			}elseif( is_page_template( 'inc/cryptocurrencies.php' ) || is_page_template( 'inc/cryptocurrencies2.php' ) ) {
				$name = isset($_GET['coin']) && !empty($_GET['coin']) ? $_GET['coin'] : get_query_var('coin');
				if( $name ) {
					$index = isset($_GET['index']) ? $_GET['index'] : kanews_get_option('crypto-page-index', 'try');
					$this->add_crumb(
						strtoupper($name.'/'.$index),
						kanews_get_page_link('coin', strtolower($name), 'crypto')
					);
				}
			}elseif( is_page_template( 'inc/weather-2.php' ) ) {
				$name = isset($_GET['sehir']) && !empty($_GET['sehir']) ? $_GET['sehir'] : get_query_var('sehir');
				if( $name ) {
					$this->add_crumb(
						ucfirst($name),
						kanews_get_page_link('sehir', strtolower($name), 'weather')
					);
				}
			}elseif( is_page_template( 'inc/livescore.php' ) ) {
        $name = isset($_GET['lig']) && !empty($_GET['lig']) ? $_GET['lig'] : get_query_var('lig');
				global $wp;
				if( $name ) {
					$lig_title = kanews_correct_league_title2($name);

					$this->add_crumb(
						$lig_title,
						home_url(add_query_arg( array('lig' => urlencode( $name )), $wp->request))
					);
				}
			}elseif( is_page_template( 'inc/traffic.php' ) ) {
				$name = isset($_GET['sehir']) && !empty($_GET['sehir']) ? $_GET['sehir'] : get_query_var('sehir');
				if( $name ) {
					$this->add_crumb(
						ucfirst($name),
						kanews_get_page_link('sehir', ucfirst($name), 'traffic')
					);
				}
			}elseif( is_page_template( 'inc/newspaper.php' ) ) {
				$name = isset($_GET['gazete']) && !empty($_GET['gazete']) ? $_GET['gazete'] : get_query_var('gazete');
				if( $name ) {
					$newspapers = [
            'aksam' => 'Akşam',
            // 'yeni-safak' => 'Yeni Şafak',
            // 'fanatik' => 'Fanatik',
            'fotomac' => 'Fotomaç',
            'milliyet' => 'Milliyet',
            // 'sozcu' => 'Sözcü',
            'takvim-gazetesi' => 'Takvim',
            'hurriyet' => 'Hürriyet',
            'sabah' => 'Sabah',
            'milli-gazete' => 'Milli',
            'yenicag' => 'Yeni Çağ',
            'milat' => 'Milat',
            'turkiye' => 'Türkiye',
            'turkgun' => 'Türkgün',
            'dunya' => 'Dünya',
            'yenisoz' => 'Yenisöz',
            // 'harbi-gazete' => 'Harbi Gazete',
            'dogru-haber' => 'Doğru Haber',
            'yeni-birlik' => 'Yeni Birlik',
            'aydinlik' => 'Aydınlık',
					];
					$this->add_crumb(
						isset($newspapers[$name]) ? $newspapers[$name] : $name,
						kanews_get_page_link('gazete', $name, 'gazete')
					);
				}
			}elseif( is_page_template( 'inc/eczane.php' ) ) {
				$name = isset($_GET['sehir']) && !empty($_GET['sehir']) ? $_GET['sehir'] : get_query_var('sehir');
				if( $name ) {
					$this->add_crumb(
						ucfirst($name),
						kanews_get_page_link('sehir', strtolower($name), 'eczane')
					);
				}
			}elseif( is_page_template( 'inc/standings.php' ) ) {
				$name = isset($_GET['lig']) && !empty($_GET['lig']) ? $_GET['lig'] : get_query_var('lig');
				if( $name ) {
					$this->add_crumb(
						ucwords( str_replace("-", " ", $name) ),
						kanews_get_page_link('lig', strtolower($name), 'puan')
					);
				}
			}elseif( is_page_template( 'inc/prayer.php' ) ) {
				$name = isset($_GET['sehir']) && !empty($_GET['sehir']) ? $_GET['sehir'] : get_query_var('sehir');
        $region = (isset($_GET['sehir']) &&  $_GET['sehir'] != 'null' && !empty($_GET['sehir'])) ? esc_html(ucwords($_GET['sehir'])) : kanews_get_option('prayer-page-city', 'Ankara');
        $city = (isset($_GET['ilce']) && $_GET['ilce'] != 'null' && !empty($_GET['ilce'])) ? esc_html(ucwords($_GET['ilce'])) : kanews_get_option('prayer-page-city2', $region);
        if( empty($city) )
        $city = $region;

        if( $region == 'Kocaeli' && $region == $city )
        $city = 'İzmit';

				if( $name ) {
					$this->add_crumb(
						$city,
						kanews_get_page_link('sehir', $city, 'eczane')
					);
				
				}
			}
		} else {
			if ( is_post_type_archive() ) {
				$post_type = $wp_query->get( 'post_type' );

				if ( $post_type && is_string( $post_type ) ) {
					if($post_type == 'columist')
					$this->add_crumb( esc_html__( 'Yazarlarımız', 'kanews' ), get_post_type_archive_link( $post_type ) );
					else
					$this->add_crumb( $this->post_type_archive_title( $post_type ), get_post_type_archive_link( $post_type ) );
				}
			} elseif ( is_tax() || is_tag() || is_category() ) {
				$this->add_crumbs_for_taxonomy();
			} elseif ( is_date() ) {
				if ( is_day() ) {
					$this->add_linked_month_year_crumb();
					$this->add_date_crumb();
				} elseif ( is_month() ) {
					$this->add_month_crumb();
				} elseif ( is_year() ) {
					$this->add_year_crumb();
				}
			} elseif ( is_author() ) {
				$user = $wp_query->get_queried_object();
				$this->add_crumb(
					'Archives for ' . $user->display_name,
					get_author_posts_url( $user->ID, $user->nicename )
				);
			} elseif ( is_search() ) {
				$this->add_crumb(
					esc_html__('Arama Sonuçları', 'kanews') . ': ' . esc_html( get_search_query() ),
					get_search_link( get_query_var( 's' ) )
				);
			} elseif ( is_404() ) {
				$this->add_crumb(
					esc_html__( 'Sayfa bulunamadı!', 'kanews' ),
					null
				);
			}
		}

		return apply_filters( 'json_ld_breadcrumb_itemlist_array', $this->crumbs );
	}

	/**
	 * Initialize the breadcrumbs.
	 *
	 * @since  1.0.0
	 */
	public function set_crumbs() {
		$breadcrumb = array();
		$breadcrumb = $this->initialize_breadcrumb_schema( $breadcrumb );

		$breadcrumb['itemListElement'] = $this->add_breadcrumb_crumbs();

		$this->json_schema( apply_filters( 'json_ld_breadcrumb_array', $breadcrumb ) );
	}

	/**
	 * Output the ld+json schema markup.
	 *
	 * @since  1.0.0
	 *
	 * @param  Array $schema Array to be converted to json markup.
	 */
	private function json_schema( $schema ) {
		$schema_output = null;

		if ( ! empty( $schema ) && is_array( $schema ) && !$this->check_seo_plugins() ) {
			$schema_output = '<!-- Kanews: Breadcrumb Schema Meta -->'."\n";
			$schema_output .= '<script id="kanews-schema-breadcrumb" type="application/ld+json">'."\n";
			$schema_output .= wp_json_encode( $schema)."\n";
			$schema_output .= '</script>'."\n";
			$schema_output .= '<!-- /Kanews: Breadcrumb Schema Meta -->'."\n";
		}

		echo kan_minify_js($schema_output); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
	}

	/**
	* Check Seo Plugins
	*/
	function check_seo_plugins(){

		$is_active = false;

		// Yoast SEO
		if( class_exists( 'WPSEO_Frontend' ) ){
				$yoast = get_option( 'wpseo_titles' );
				if( isset($yoast['breadcrumbs-enable'] ) && ! empty( $yoast['breadcrumbs-enable'] ) ) {
					$is_active = true;
				}
		}

		// Rank Math SEO
		elseif( function_exists('rank_math') ) {
			$rank_math = get_option('rank-math-options-general');
			if(!empty($rank_math) && isset($rank_math['breadcrumbs']) && $rank_math['breadcrumbs'] == 'on') {
				$is_active = true;
			}
		}

		return $is_active;
	}

}
