<?php
namespace  AcademyProCourseBundle\Frontend\Template;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}


class Loader {
	public static function init() {
		$self = new self();
		add_filter( 'template_include', array( $self, 'template_loader' ) );
	}

	public function template_loader( $template ) {
		if ( is_embed() ) {
			return $template;
		}

		$default_file = $this->get_template_loader_default_file();

		if ( $default_file ) {
			/**
			 * Filter hook to choose which files to find before Academy does it's own logic.
			 *
			 * @var array
			 */
			$search_files = $this->get_template_loader_files( $default_file );
			$template     = locate_template( $search_files );

			if ( ! $template ) {
				$template = \AcademyPro\Helper::plugin_path() . 'templates/course-bundle/' . $default_file;
			}
		}
		return $template;
	}

	/**
	 * Get the default filename for a template.
	 *
	 * @return string
	 */
	private function get_template_loader_default_file() {
		if ( is_singular( 'alms_course_bundle' ) ) {
			$default_file = 'single-bundle.php';
		} else {
			$default_file = '';
		}
		return $default_file;
	}

	private function get_template_loader_files( $default_file ) {
		$templates   = apply_filters( 'academy_pro_course_bundle/frontend/template/loader_files', array(), $default_file );
		$templates[] = 'academy-pro.php';

		if ( is_page_template() ) {
			$page_template = get_page_template_slug();

			if ( $page_template ) {
				$validated_file = validate_file( $page_template );
				if ( 0 === $validated_file ) {
					$templates[] = $page_template;
				} else {
					// phpcs:ignore WordPress.PHP.DevelopmentFunctions.error_log_error_log
					error_log( "Academy Pro Course Bundle: Unable to validate template path: \"$page_template\". Error Code: $validated_file." );
				}
			}
		}

		if ( is_singular( 'alms_course_bundle' ) ) {
			$object       = get_queried_object();
			$name_decoded = urldecode( $object->post_name );
			if ( $name_decoded !== $object->post_name ) {
				$templates[] = "single-bundle-{$name_decoded}.php";
			}
			$templates[] = "single-bundle-{$object->post_name}.php";
		}

		$templates[] = $default_file;
		if ( isset( $cs_default ) ) {
			$templates[] = \AcademyPro\Helper::template_path() . $cs_default;
		}
		$templates[] = \AcademyPro\Helper::template_path() . $default_file;

		return array_unique( $templates );
	}
}
