<?php /*** TEMPLATE HELPERS ***/

// Get template
if ( ! function_exists( 'wpj_get_template' ) ) {
	function wpj_get_template( $template_name, $args = [], $template_path = '', $default_path = '' ) {
		$cache_key = sanitize_key( implode( '-', [ 'template', $template_name, $template_path, $default_path, wpjobster_VERSION ] ) );
		$template  = (string) wp_cache_get( $cache_key, 'wpjobster' );

		if ( ! $template ) {
			$template = wpj_locate_template( $template_name, $template_path, $default_path );
			wp_cache_set( $cache_key, $template, 'wpjobster' );
		}

		// Allow 3rd party plugin filter template file from their plugin.
		$filter_template = apply_filters( 'wpj_get_template', $template, $template_name, $args, $template_path, $default_path );

		if ( $filter_template !== $template ) {
			if ( ! file_exists( $filter_template ) ) {
				return false;
			}

			$template = $filter_template;
		}

		$action_args = [
			'template_name' => $template_name,
			'template_path' => $template_path,
			'located'       => $template,
			'args'          => $args,
		];

		if ( ! empty( $args ) && is_array( $args ) ) {
			if ( isset( $args['action_args'] ) ) {
				unset( $args['action_args'] );
			}

			extract( $args ); // @codingStandardsIgnoreLine
		}

		do_action( 'wpj_before_template_part', $action_args['template_name'], $action_args['template_path'], $action_args['located'] );

		include $action_args['located'];

		do_action( 'wpj_after_template_part', $action_args['template_name'], $action_args['template_path'], $action_args['located'] );
	}
}

// Locate template
if ( ! function_exists( 'wpj_locate_template' ) ) {
	function wpj_locate_template( $template_name, $template_path = '', $default_path = '' ) {
		if ( ! $template_path ) {
			$template_path = 'template-parts/';
		}

		if ( ! $default_path ) {
			$default_path = get_template_directory() . '/template-parts/';
		}

		// Look within passed path within the theme - this is priority.
		$template = locate_template(
			[
				trailingslashit( $template_path ) . $template_name,
				$template_name,
			]
		);

		// Get default template/.
		if ( ! $template ) {
			$template = $default_path . $template_name;
		}

		// Return what we found.
		return apply_filters( 'wpj_locate_template', $template, $template_name, $template_path );
	}
}