<?php
if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * Sifency Elementor Override for EDD Archive Pages
 */
final class Sifency_EDD_Archive_Render {

	private static $instance = null;

	public function __construct() {
		if ( is_admin() ) {
			return;
		}

		add_filter( 'template_include', array( $this, 'override_edd_archive_template' ), 99 );
	}

	/**
	 * Replace EDD archive with Elementor template
	 */
	public function override_edd_archive_template( $template ) {

		if ( is_admin() || wp_doing_ajax() ) {
			return $template;
		}

		if ( ! function_exists( 'edd_is_checkout' ) ) {
			return $template;
		}

		if ( ! is_post_type_archive( 'download' ) && ! is_tax( array( 'download_category', 'download_tag' ) ) ) {
			return $template;
		}

		$sifency_addons_template_id = Sifency_Addons_Frontend_Helper::find_matching_template( 'edd-archive' );

		if ( empty( $sifency_addons_template_id ) || get_post_status( $sifency_addons_template_id ) !== 'publish' ) {
			return $template;
		}

		return SIFENCY_TB_PATH . 'post-type/edd/templates/edd-archive-elementor.php';
	}

	/**
	 * Singleton
	 */
	public static function get_instance() {
		if ( self::$instance === null ) {
			self::$instance = new self();
		}
		return self::$instance;
	}
}

Sifency_EDD_Archive_Render::get_instance();
