<?php

namespace ElementPack\Includes\Builder;

use Elementor\Widget_Base;

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

abstract class Builder_Widget_Base extends Widget_Base {

	public $__temp_query = null;
	public $__product_data = false;

	public function in_elementor() {
		$result = false;

		if ( wp_doing_ajax() ) {
			$result = $this->is_elementor_ajax;
		} elseif (
			\Elementor\Plugin::instance()->editor->is_edit_mode()
			|| \Elementor\Plugin::instance()->preview->is_preview_mode()
		) {
			$result = true;
		}

		return apply_filters( 'bdthemes-templates-builder/in-elementor', $result );
	}

	protected function is_ultimate_builder_editor() {
		if ( ! wp_doing_ajax() ) {
			return false;
		}

		if ( get_post_type() !== Meta::POST_TYPE ) {
			return false;
		}

		return true;
	}

	/**
	 * The real post/page shown on the frontend while a Theme Builder single template renders.
	 *
	 * Elementor switches $post to the template post during get_builder_content(); widgets must
	 * read the queried singular ID instead (Elementor Pro parity).
	 *
	 * @return int
	 */
	protected function get_theme_builder_queried_post_id() {
		$post_id = Builder_Integration::instance()->get_queried_singular_post_id();
		if ( $post_id ) {
			return $post_id;
		}

		return (int) get_queried_object_id();
	}

	/**
	 * @return \WP_Post|null
	 */
	protected function get_theme_builder_queried_post() {
		$post_id = $this->get_theme_builder_queried_post_id();

		return $post_id ? get_post( $post_id ) : null;
	}

	/**
	 * Swap to the sample post while editing a Theme Builder single template in Elementor.
	 */
	public function bdt_set_single_post_preview_data() {
		if ( ! Builder_Template_Helper::isTemplateEditMode() && ! $this->is_ultimate_builder_editor() ) {
			return;
		}

		global $post;

		$template_id = isset( $post->ID ) ? (int) $post->ID : 0;
		if ( ! $template_id || Meta::POST_TYPE !== get_post_type( $template_id ) ) {
			return;
		}

		$stored_template_id = (int) get_transient( 'bdthemes_builder_template_id_' . get_current_user_id() );
		$sample_query       = get_transient( 'bdthemes_builder_template_sample_post_' . get_current_user_id() );

		if ( $sample_query instanceof \WP_Query && $sample_query->have_posts() && $stored_template_id === $template_id ) {
			$sample_post = $sample_query->posts[0];
			$GLOBALS['post'] = $sample_post;
			setup_postdata( $sample_post );
		}
	}
}
