<?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', [ $this, 'override_edd_archive_template' ], 99 );
    }

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

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

        // Check EDD plugin
        if ( ! function_exists( 'edd_is_checkout' ) ) {
            return $template;
        }

        // Target EDD Archives
        if ( ! is_post_type_archive( 'download' ) && ! is_tax( ['download_category','download_tag'] ) ) {
            return $template;
        }

        // Find Elementor template
        $sifency_addons_template_id = Sifency_Frontend_Helper::find_matching_template( 'edd-archive' );

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

        // Return custom template file
        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();