<?php
/**
 * Softech Addons – Canvas Override Template
 *
 * Serves as the full-page template when a custom 404_page, single_post,
 * archive, or single_page template is active for the current request.
 *
 * wp_body_open() triggers the plugin's custom header injection (if a header
 * template is active) because inject_header_at_body_open() is hooked at
 * priority 1. wp_footer() likewise triggers the custom footer.
 *
 * The global $sits_hf_canvas_id   is set by SITS_Header_Footer_Builder::maybe_override_page_template().
 * The global $sits_hf_canvas_type is the template type: 'archive', 'single_post', etc.
 *
 * ARCHIVE LOOP:
 * For archive pages (category, tag, author, date, search, posts index) the
 * canvas iterates over the main WP_Query loop and renders the Elementor
 * template once per post — exactly as Elementor Pro's Loop template behaves.
 * Design your archive template as a "post card" that shows data for ONE post
 * (Post Title, Post Excerpt, Featured Image, etc.), and the canvas will repeat
 * it for every post in the current archive query.
 *
 * @package Softech_Addons_for_Elementor
 */

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

global $sits_hf_canvas_id, $sits_hf_canvas_type, $wp_query;
?><!DOCTYPE html>
<html <?php language_attributes(); ?>>
<head>
<meta charset="<?php bloginfo( 'charset' ); ?>">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="profile" href="https://gmpg.org/xfn/11">
<?php wp_head(); ?>
</head>
<body <?php body_class( 'sits-hf-canvas-page' ); ?>>
<?php wp_body_open(); /* triggers custom header if one is active */ ?>
<div class="sits-hf-canvas-content">
<?php
if ( $sits_hf_canvas_id && class_exists( '\Elementor\Plugin' ) ) :

	$sits_is_archive_page = ( 'archive' === ( $sits_hf_canvas_type ?? '' ) )
	                   || is_archive()
	                   || ( is_home() && ! is_front_page() );

	if ( $sits_is_archive_page && $wp_query->have_posts() ) :
		/*
		 * ARCHIVE LOOP ─────────────────────────────────────────────────────
		 * Render the Elementor template once per post so dynamic-data widgets
		 * (Post Title, Post Content, Featured Image, etc.) reflect each post.
		 *
		 * CSS is output on the first iteration only; subsequent renders skip
		 * inline styles to avoid duplicate CSS on the page.
		 */
		$sits_first_post = true;
		echo '<div class="sits-archive-loop">';

		while ( $wp_query->have_posts() ) :
			$wp_query->the_post(); // sets global $post + calls setup_postdata()

			echo '<div class="sits-archive-item">';
			// phpcs:disable WordPress.Security.EscapeOutput.OutputNotEscaped -- Elementor builder output is trusted, sanitized HTML.
            echo \Elementor\Plugin::$instance->frontend->get_builder_content_for_display(
            (int) $sits_hf_canvas_id,
            $sits_first_post   // $with_css = true on first post only
            );
            // phpcs:enable WordPress.Security.EscapeOutput.OutputNotEscaped
			echo '</div>';

			$sits_first_post = false;
		endwhile;

		echo '</div><!-- .sits-archive-loop -->';
		wp_reset_postdata();

	else :
		/*
		 * NON-ARCHIVE (single_post, single_page, 404_page) ─────────────────
		 * Render the Elementor template once in the current post context.
		 *
		 * Fix 2: Preserve the ACTUAL queried post as the global $post so
		 * Elementor dynamic tags (Post Title, Post Content, Featured Image, etc.)
		 * return the VIEWED post data, not the template post data.
		 * Elementor's get_builder_content_for_display() may internally change
		 * $post to the template post; we reset it before each widget renders
		 * via the elementor/widget/before_render action hook.
		 */
		global $post, $wp_query;

		// Store the actual queried post BEFORE Elementor may change $post.
		$sits_actual_post = null;
		if ( is_singular() && isset( $wp_query->post ) ) {
                $sits_actual_post = $wp_query->post;
		} elseif ( in_array( (string) ( $sits_hf_canvas_type ?? '' ), [ 'single_post', 'single_page' ], true ) ) {
			$sits_queried_id = get_queried_object_id();
                if ( $sits_queried_id ) {
                $sits_actual_post = get_post( $sits_queried_id );
			}
		}

		if ( $sits_actual_post ) {
			$post = $sits_actual_post;
			setup_postdata( $post );
		}

		// Hook: reset $post to the viewed post before each widget renders.
		$sits_restore_post_hook = null;
            if ( $sits_actual_post ) {
                $sits_restore_post_hook = static function() use ( $sits_actual_post ) {
				global $post;
				$post = $sits_actual_post;
			};
			add_action( 'elementor/widget/before_render',         $sits_restore_post_hook, 1 );
			add_action( 'elementor/widget/before_render_content', $sits_restore_post_hook, 1 );
		}

		// phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
		echo \Elementor\Plugin::$instance->frontend->get_builder_content_for_display(
			(int) $sits_hf_canvas_id,
			true
		);

		// Clean up hooks and restore post data.
		if ( $sits_restore_post_hook ) {
			remove_action( 'elementor/widget/before_render',         $sits_restore_post_hook, 1 );
			remove_action( 'elementor/widget/before_render_content', $sits_restore_post_hook, 1 );
		}
		if ( $sits_actual_post ) {
			$post = $sits_actual_post;
			setup_postdata( $post );
		}
		wp_reset_postdata();

	endif;

endif;
?>
</div>
<?php wp_footer(); /* triggers custom footer if one is active */ ?>
</body>
</html>
