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

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

final class Sifency_Addons_404_Page_Render {

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

		add_filter( 'template_include', array( $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;
		}

		// Resolve the template ID first — bail immediately if none is configured/active.
		$sifency_addons_template_id = Sifency_Addons_Frontend_Helper::find_matching_template( 'error_404' );

		if ( ! $sifency_addons_template_id ) {
			return $template; // No active 404 template — let the theme handle it.
		}

		remove_filter( 'template_include', array( 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;
		}

		set_query_var( 'sifency_404_template_id', $sifency_addons_template_id );

		return $canvas_path;
	}
}

new Sifency_Addons_404_Page_Render();
