<?php
namespace HTMega_Pro_Builder\Elementor;
use Elementor\Plugin as Elementor;

if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly

class HTMegaBuilder_Custom_Template_Layout{
    
    private static $_instance = null;
    public static function instance() {
        if ( is_null( self::$_instance ) ) {
            self::$_instance = new self();
        }
        return self::$_instance;
    }

    function __construct(){
        add_action('init', array( $this, 'init' ) );
    }

    public function init(){
        add_filter( 'template_include', array( $this, 'change_template' ), 9999 );
        add_action( 'htmegabuilder_search_content', array( $this, 'search_content_elementor' ), 999 );
        add_action( 'htmegabuilder_error_content', array( $this, 'error_content_elementor' ), 999 );
        add_action( 'htmegabuilder_comingsoon_content', array( $this, 'comingsoon_content_elementor' ), 999 );

        // Elementor only generates atomic-widget CSS for the main queried post; register
        // the active Search/404/Coming-Soon builder template before that one-shot pass so
        // its atomic styles aren't skipped.
        add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_atomic_styles_for_content_templates' ), 15 );
    }

    /**
     * Register the currently-active Search/404/Coming-Soon builder template with
     * Elementor's atomic-widget CSS pipeline before its own single per-request enqueue
     * pass runs (Frontend::enqueue_styles(), hooked at wp_enqueue_scripts priority 20).
     * That pass only registers the main queried post via is_singular(), which is false on
     * 404/search/coming-soon views, so the builder template's own atomic CSS never gets
     * generated unless we register it here first. We only register the id (priority 15,
     * before Elementor's own priority 20 pass); we don't force-run enqueue_styles()
     * ourselves, since that would trip its internal static one-shot guard and race with
     * any other extension (e.g. the header/footer builder) doing the same.
     */
    public function enqueue_atomic_styles_for_content_templates() {
        if ( is_admin() || ! class_exists( '\Elementor\Plugin' ) ) {
            return;
        }

        $template_ids = [];

        if ( is_404() ) {
            $error_tm_id = $this->custom_template_id( 'error_page' );
            if ( ! empty( $error_tm_id ) ) {
                $template_ids[] = absint( $error_tm_id );
            }
        }

        if ( is_search() ) {
            $search_tm_id = $this->custom_template_id( 'search_page' );
            if ( ! empty( $search_tm_id ) ) {
                $template_ids[] = absint( $search_tm_id );
            }
        }

        if ( ! is_user_logged_in() ) {
            $comingsoon_tm_id = $this->custom_template_id( 'coming_soon_page' );
            if ( ! empty( $comingsoon_tm_id ) ) {
                $template_ids[] = absint( $comingsoon_tm_id );
            }
        }

        $template_ids = array_unique( array_filter( $template_ids ) );
        if ( empty( $template_ids ) ) {
            return;
        }

        foreach ( $template_ids as $template_id ) {
            do_action( 'elementor/post/render', $template_id );
        }
    }

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

        // Get template IDs
        $search_tm_id = $this->custom_template_id( 'search_page' );
        $error_tm_id = $this->custom_template_id( 'error_page' );
        $comingsoon_tm_id = $this->custom_template_id( 'coming_soon_page' );

        // 404 Error Page
        if( is_404() && !empty( $error_tm_id ) ){
            $custom_template = $this->get_elementor_template($error_tm_id, 'error');
            if($custom_template) {
                return $custom_template;
            }
        }

        // Search Page
        if( is_search() && !empty( $search_tm_id ) ){
            $custom_template = $this->get_elementor_template($search_tm_id, 'search');
            if($custom_template) {
                return $custom_template;
            }
        }

        // Coming Soon Page
        if( !is_user_logged_in() && !empty( $comingsoon_tm_id ) ){
            $custom_template = $this->get_elementor_template($comingsoon_tm_id, 'comingsoon');
            if($custom_template) {
                return $custom_template;
            }
        }

        return $template;
    }

    private function get_elementor_template($template_id, $type = 'error') {
        // Check if this is an Elementor template
        $is_elementor_template = get_post_meta($template_id, '_elementor_edit_mode', true);
        
        if($is_elementor_template) {
            // Get template type
            $page_template = get_post_meta($template_id, '_wp_page_template', true);
            
            // Determine template type
            $template_type = 'fullwidth';
            if($page_template === 'elementor_canvas') {
                $template_type = 'canvas';
            }
            
            // Get template path based on type
            return $this->get_template_file($type, $template_type);
        }
        
        return false;
    }

    private function get_template_file($type = 'error', $template_type = 'fullwidth') {
        $template_path = HTMEGA_ADDONS_PL_PATH_PRO . 'extensions/ht-builder/templates/';
        $template_file = $type . '-' . ($template_type === 'canvas' ? 'canvas.php' : 'fullwidth.php');
        
        if(file_exists($template_path . $template_file)) {
            return $template_path . $template_file;
        }
        
        // Fallback to fullwidth if canvas doesn't exist
        if($template_type === 'canvas' && file_exists($template_path . $type . '-fullwidth.php')) {
            return $template_path . $type . '-fullwidth.php';
        }
        
        return false;
    }

    public function custom_template_id( $option_key ){
        $template_id = htmega_get_module_option( 'htmega_themebuilder_module_settings', 'themebuilder', $option_key );
        if(!$template_id) {
            $template_id = htmega_get_option_pro( $option_key, 'htmegabuilder_templatebuilder_tabs', '0' );
        }

        // Verify template exists and is valid
        if(!empty($template_id)) {
            $post = get_post($template_id);
            if($post && 'publish' === $post->post_status) {
                return $template_id;
            }
        }

        return false;
    }

    public function search_content_elementor( $post ) {
        $templateid = $this->custom_template_id( 'search_page' );
        if( !empty( $templateid ) ){
            echo htmega_get_template_content_by_id( $templateid ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        }else{
            the_content();
        }
    }

    public function error_content_elementor( $post ) {
        $templateid = $this->custom_template_id( 'error_page' );
        if( !empty( $templateid ) ){
            echo htmega_get_template_content_by_id( $templateid ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        }else{
            the_content();
        }
    }

    public function comingsoon_content_elementor( $post ) {
        $templateid = $this->custom_template_id( 'coming_soon_page' );
        if( !empty( $templateid ) ){
            echo htmega_get_template_content_by_id( $templateid ); // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
        }else{
            the_content();
        }
    }
}

HTMegaBuilder_Custom_Template_Layout::instance();