<?php
if ( ! function_exists( 'wpj_is_subcategory' ) ) {
	function wpj_is_subcategory( $post_type = 'job_cat' ) {
		$term = get_term_by( 'slug', get_query_var( 'term' ), $post_type );

		return $term && $term->parent != '0';
	}
}

if ( ! function_exists( 'wpj_get_category_link' ) ) {
	function wpj_get_category_link( $category = 0, $taxonomy = 'job_cat' ) {
		// if id
		if ( ctype_digit( $category ) || is_int( $category ) ) {
			return get_category_link( $category );
		}

		// if slug
		$this_term = get_term_by( 'slug', $category, $taxonomy );

		// if name
		if ( ! $this_term ) {
			$this_term = get_term_by( 'name', $category, $taxonomy );
		}

		// avoid warnings
		if ( isset( $this_term->term_id ) && is_numeric( $this_term->term_id ) )
			$category_id = $this_term->term_id;

		else
			$category_id = 0;

		return get_category_link( $category_id );
	}
}

if ( ! function_exists( 'wpj_get_category_breadcrumbs' ) ) {
	function wpj_get_category_breadcrumbs( $post, $taxonomy ) {
		$terms = get_the_terms( $post->ID, $taxonomy );

		if ( empty( $terms) ) {
			return [];
		}

		$breadcrumbs = [];

		foreach ( $terms as $term ) {
			$term_ancestors = get_ancestors( $term->term_id, $taxonomy );
			$term_ancestors = array_reverse( $term_ancestors );

			foreach ( $term_ancestors as $ancestor_id ) {
				$ancestor = get_term( $ancestor_id, $taxonomy );

				wpj_add_breadcrumb( $breadcrumbs, $ancestor->name, get_term_link( $ancestor->term_id, $taxonomy ) );
			}

			wpj_add_breadcrumb( $breadcrumbs, $term->name, get_term_link( $term->term_id, $taxonomy ) );
		}

		return $breadcrumbs;
	}
}

if ( ! function_exists( 'wpj_add_breadcrumb' ) ) {
	function wpj_add_breadcrumb( &$breadcrumbs, $name, $link ) {
		foreach ( $breadcrumbs as $breadcrumb ) {
			if ( $breadcrumb['name'] === $name ) {
				return; // Avoid adding duplicate breadcrumbs
			}
		}

		$breadcrumbs[] = [
			'name' => $name,
			'link' => $link
		];
	}
}