<?php
/**
 * @package Softech_Addons_for_Elementor
 * @since   1.2.0
 * @updated 1.2.3
 */

namespace Softech_Addons_for_Elementor\Includes;

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

/**
 * Use Elementor's Page document as the base so that we inherit the full
 * Page Settings panel (layout, title visibility, background, padding…).
 * Fall back to the base Document class for very old Elementor installs.
 */
if ( class_exists( '\Elementor\Core\Documents\Page' ) ) {
	class SITS_HF_Elementor_Document extends \Elementor\Core\Documents\Page {

		/** Document type key — matches the key used in register_document_type(). */
		public function get_name() {
			return 'sits-hf-template';
		}

		/** Label shown in Elementor's admin bar and finder. */
		public static function get_title() {
			$type  = static::get_requested_hf_type();
			$label = static::get_hf_type_label( is_string( $type ) ? $type : '' );
			if ( '' !== $label ) {
				return $label;
			}

			return esc_html__( 'Header/Footer Template', 'softech-addons-for-elementor' );
		}

		/**
		 * Resolve the current HF template type from request/query context.
		 *
		 * @return string|false
		 */
		private static function get_requested_hf_type() {
			$post_id = 0;

			// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only context detection for editor/admin bar labels.
			if ( isset( $_GET['post'] ) ) {
				// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only context detection for editor/admin bar labels.
				$post_id = absint( wp_unslash( $_GET['post'] ) );
			}

			// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only context detection for editor/admin bar labels.
			if ( ! $post_id && isset( $_GET['elementor-preview'] ) ) {
				// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only context detection for editor/admin bar labels.
				$post_id = absint( wp_unslash( $_GET['elementor-preview'] ) );
			}

			if ( ! $post_id ) {
				$post_id = absint( get_queried_object_id() );
			}

			if ( ! $post_id ) {
				$post = get_post();
				if ( $post instanceof \WP_Post ) {
					$post_id = (int) $post->ID;
				}
			}

			if ( ! $post_id || 'sits_hf_template' !== get_post_type( $post_id ) ) {
				return false;
			}

			$type = sanitize_key( (string) get_post_meta( $post_id, '_sits_hf_type', true ) );
			return '' !== $type ? $type : false;
		}

		/**
		 * Human-readable labels for Theme Builder template types.
		 */
		private static function get_hf_type_label( string $type ): string {
			$labels = [
				'header'      => esc_html__( 'Header', 'softech-addons-for-elementor' ),
				'footer'      => esc_html__( 'Footer', 'softech-addons-for-elementor' ),
				'single_post' => esc_html__( 'Single Post', 'softech-addons-for-elementor' ),
				'single_page' => esc_html__( 'Single Page', 'softech-addons-for-elementor' ),
				'archive'     => esc_html__( 'Archive', 'softech-addons-for-elementor' ),
				'404_page'    => esc_html__( '404 Page', 'softech-addons-for-elementor' ),
			];

			return $labels[ $type ] ?? '';
		}

		/**
		 * Per-instance cache for the _sits_hf_type post meta value.
		 * Both get_post_type_title() and filter_print_content() read this meta;
		 * caching it avoids a duplicate DB round-trip on every Elementor panel load.
		 *
		 * @var string|false|null  null = not yet fetched; false = meta is empty.
		 */
		private $hf_type_cache = null;

		/**
		 * Return the template type ('header', 'footer', etc.), fetching from the DB
		 * only on the first call and caching the result for the lifetime of this instance.
		 *
		 * @return string|false
		 */
		private function get_hf_type() {
			if ( null === $this->hf_type_cache ) {
				$value = get_post_meta( $this->get_main_id(), '_sits_hf_type', true );
				// Normalize empty string (no meta saved) to false so callers can do a simple boolean check.
				$this->hf_type_cache = ( '' !== $value ) ? $value : false;
			}
			return $this->hf_type_cache;
		}

		/**
		 * Dynamic title based on template-type meta.
		 */
		public function get_post_type_title() {
			$type = $this->get_hf_type();
			$label = static::get_hf_type_label( is_string( $type ) ? $type : '' );
			if ( '' !== $label ) {
				return $label;
			}

			return static::get_title();
		}

		/**
		 * Document properties.
		 * - support_kit: allow Global Settings / Site Identity controls.
		 * - support_wp_page_templates: show the WP template selector in Page Settings.
		 * - support_page_layout: show the "Page Layout" control (canvas / full-width / default).
		 * - support_elementor_post_meta: enable Hide Title toggle and custom padding/margin.
		 */
		public static function get_properties() {
			$props = parent::get_properties();
			$props['support_kit']                  = true;
			$props['support_wp_page_templates']    = true;
			$props['support_page_layout']          = true;
			$props['support_elementor_post_meta']  = true;
			$props['show_in_finder']               = false; // Don't show in Elementor Finder (creates confusion)
			return $props;
		}

		/**
		 * Controls whether Elementor renders this document's content via the_content() filter.
		 *
		 * Header and Footer templates are injected via our own wp_body_open / wp_footer
		 * hooks using get_builder_content_for_display(), so we must return false here to
		 * prevent double-rendering on those types.
		 *
		 * All other template types (404_page, single_post, archive, single_page) rely on
		 * Elementor's standard the_content() rendering pipeline for the editor canvas,
		 * preview, and frontend — returning false for these types causes a completely
		 * blank canvas and blank frontend. Return true so Elementor renders them normally.
		 */
		protected function filter_print_content() {
			$type = $this->get_hf_type();
			// header & footer: injected via our own hooks — don't let Elementor double-render.
			if ( in_array( $type, [ 'header', 'footer' ], true ) ) {
				return false;
			}
			// 404_page, single_post, archive, single_page: use Elementor's normal rendering.
			return true;
		}
		protected function register_controls() {
    parent::register_controls();

    // Force-register Hide Title if Pro stripped it out
    if ( ! $this->get_controls( 'hide_title' ) ) {
        $this->add_control(
            'hide_title',
            [
                'label'     => esc_html__( 'Hide Title', 'softech-addons-for-elementor' ),
                'type'      => \Elementor\Controls_Manager::SWITCHER,
                'default'   => '',
                'separator' => 'before',
            ]
        );
    }

    // Force-register Page Layout (template) if Pro stripped it out
    if ( ! $this->get_controls( 'template' ) ) {
        $templates = [];
        foreach ( get_page_templates() as $label => $value ) {
            $templates[ $value ] = $label;
        }
        $templates = array_merge(
            [ 'default' => esc_html__( 'Default', 'softech-addons-for-elementor' ) ],
            $templates
        );

        $this->add_control(
            'template',
            [
                'label'   => esc_html__( 'Page Layout', 'softech-addons-for-elementor' ),
                'type'    => \Elementor\Controls_Manager::SELECT,
                'default' => 'elementor_canvas',
                'options' => $templates,
            ]
        );
    }
}
	}
} else {
	// Fallback for very old Elementor (< 3.0) — minimal document with no page settings.
	class SITS_HF_Elementor_Document extends \Elementor\Core\Base\Document {

		public static function get_properties() {
			$props = parent::get_properties();
			$props['support_kit']                 = true;
			$props['support_wp_page_templates']   = false;
			$props['support_elementor_post_meta'] = true;
			return $props;
		}

		public function get_name() {
			return 'sits-hf-template';
		}

		public static function get_title() {
			$type  = static::get_requested_hf_type();
			$label = static::get_hf_type_label( is_string( $type ) ? $type : '' );
			if ( '' !== $label ) {
				return $label;
			}

			return esc_html__( 'Header/Footer Template', 'softech-addons-for-elementor' );
		}

		/**
		 * @return string|false
		 */
		private static function get_requested_hf_type() {
			$post_id = 0;

			// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only context detection for editor/admin bar labels.
			if ( isset( $_GET['post'] ) ) {
				// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only context detection for editor/admin bar labels.
				$post_id = absint( wp_unslash( $_GET['post'] ) );
			}

			// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only context detection for editor/admin bar labels.
			if ( ! $post_id && isset( $_GET['elementor-preview'] ) ) {
				// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only context detection for editor/admin bar labels.
				$post_id = absint( wp_unslash( $_GET['elementor-preview'] ) );
			}

			if ( ! $post_id ) {
				$post_id = absint( get_queried_object_id() );
			}

			if ( ! $post_id ) {
				$post = get_post();
				if ( $post instanceof \WP_Post ) {
					$post_id = (int) $post->ID;
				}
			}

			if ( ! $post_id || 'sits_hf_template' !== get_post_type( $post_id ) ) {
				return false;
			}

			$type = sanitize_key( (string) get_post_meta( $post_id, '_sits_hf_type', true ) );
			return '' !== $type ? $type : false;
		}

		private static function get_hf_type_label( string $type ): string {
			$labels = [
				'header'      => esc_html__( 'Header', 'softech-addons-for-elementor' ),
				'footer'      => esc_html__( 'Footer', 'softech-addons-for-elementor' ),
				'single_post' => esc_html__( 'Single Post', 'softech-addons-for-elementor' ),
				'single_page' => esc_html__( 'Single Page', 'softech-addons-for-elementor' ),
				'archive'     => esc_html__( 'Archive', 'softech-addons-for-elementor' ),
				'404_page'    => esc_html__( '404 Page', 'softech-addons-for-elementor' ),
			];

			return $labels[ $type ] ?? '';
		}

		/** @var string|false|null */
		private $hf_type_cache = null;

		private function get_hf_type() {
			if ( null === $this->hf_type_cache ) {
				$value = get_post_meta( $this->get_main_id(), '_sits_hf_type', true );
				$this->hf_type_cache = ( '' !== $value ) ? $value : false;
			}
			return $this->hf_type_cache;
		}

		public function get_post_type_title() {
			$type = $this->get_hf_type();
			$label = static::get_hf_type_label( is_string( $type ) ? $type : '' );
			return '' !== $label ? $label : static::get_title();
		}

		protected function filter_print_content() {
			$type = $this->get_hf_type();
			return ! in_array( $type, [ 'header', 'footer' ], true );
		}
	}
}
