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

/**
 * Sifency Elementor Override for EDD Single Download Pages
 */
final class Sifency_EDD_Single_Render {

    private static $instance = null;

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

        add_filter( 'template_include', [ $this, 'override_edd_single_template' ], 99 );
    }

    /**
     * Replace EDD single template with Elementor
     */
    public function override_edd_single_template( $template ) {

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

        // Check EDD exists
        if ( ! class_exists( 'Easy_Digital_Downloads' ) ) {
            return $template;
        }

        // Target single download pages
        if ( ! is_singular( 'download' ) ) {
            return $template;
        }

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

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

        // Return Elementor wrapper template
        return SIFENCY_TB_PATH . 'post-type/edd/templates/edd-single-elementor.php';
    }

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

Sifency_EDD_Single_Render::get_instance();
