<?php
namespace TotalTheme\Theme_Builder;

defined( 'ABSPATH' ) || exit;

/**
 * Returns the template to use for the current post.
 *
 * @package TotalTheme
 * @subpackage Mobile
 * @version 5.5
 */
class Post_Template {

	/**
	 * Stores the current post template.
	 */
	protected static $template_id;

	/**
	 * Helper function checks if the current post has a template.
	 */
	public static function has_template() {
		return (bool) self::get_template_content();
	}

	/**
	 * Get current post template id.
	 *
	 * @todo deprecate post_type param
	 */
	public static function get_template_id( $post_type = '' ) {
		if ( ! is_null( self::$template_id ) && did_action( 'wp_loaded' ) ) {
			return self::$template_id; // once we grab the template once we save it to prevent extra checks.
		}

		if ( ! $post_type ) {
			$post_type = get_post_type();
		}

		$post_id = is_admin() ? get_the_ID() : wpex_get_current_post_id();

		// Get template based on the post meta.
		if ( $meta = get_post_meta( $post_id, 'wpex_singular_template', true ) ) {
			$template_id = $meta;
		}

		// Get template based on theme mod or PTU setting.
		else {

			if ( function_exists( 'is_product' ) && is_product() ) {
				$template_id = get_theme_mod( 'woo_singular_template' );
			} else {
				$template_id = get_theme_mod( $post_type . '_singular_template' );
				if ( WPEX_PTU_ACTIVE ) {
					$ptu_check = wpex_get_ptu_type_mod( $post_type, 'singular_template_id' );
					if ( $ptu_check ) {
						$template_id = $ptu_check;
					}
				}
			}

		}

		$template_id = (int) apply_filters( 'wpex_get_singular_template_id', $template_id, $post_type ); // legacy

		/**
		 * Filters the singular dynamic template ID.
		 *
		 * @param int $template_id
		 * @param string $post_type
		 */
		$template_id = (int) apply_filters( 'wpex_singular_template_id', $template_id, $post_type );

		// Sanitize template ID.
		self::$template_id = $template_id ? wpex_parse_obj_id( $template_id, 'page' ) : null;

		return self::$template_id;
	}

	/**
	 * Return current post template content.
	 */
	public static function get_template_content( $post_type = '' ) {
		$template_id = self::get_template_id( $post_type );

		if ( empty( $template_id ) ) {
			return;
		}

		$temp_post = get_post( $template_id );

		if ( $temp_post && 'publish' === get_post_status( $temp_post ) ) {
			return $temp_post->post_content;
		}
	}

	/**
	 * Render current post template.
	 */
	public static function render_template( $template_content = '' ) {
		$template_content_escaped = wpex_sanitize_template_content( $template_content );

		/**
		 * Filters the tag used to wrap post templates.
		 *
		 * @param string $html_tag
		 */
		$tag = (string) apply_filters( 'wpex_singular_template_html_tag', 'div' );

		$tag_escaped = tag_escape( $tag );

		echo '<' . $tag_escaped . ' class="custom-singular-template entry wpex-clr">' . $template_content_escaped . '</' . $tag_escaped . '>';

		return true;
	}

}