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

/**
 * Sifency 404 Page Render
 * Dynamically replaces the default 404 template with an Elementor one.
 */

final class Sifency_404_Render {

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

        add_filter( 'template_include', [ $this, 'override_404_template' ], 999 );
    }

    /**
     * Replace the default 404 template if an Elementor template exists.
     */
    public function override_404_template( $template ) {

        if ( ! is_404() ) {
            return $template;
        }
        remove_filter( 'template_include', [ Sifency_Addons_Theme_Builder_Master::$sifency_addons_frontend_render, 'load_canvas_template' ], 9999 );
        $canvas_path = SIFENCY_TB_PATH . 'builder-item/templates/sifency-404-canvas.php';
        if ( ! file_exists( $canvas_path ) ) {
            return $template;
        }

        $sifency_addons_template_id = Sifency_Frontend_Helper::find_matching_template( 'error_404' );

        set_query_var( 'sifency_404_template_id', $sifency_addons_template_id );

        return $canvas_path;
    }
}

new Sifency_404_Render();
