<?php
/**
 * Post context helpers for global Elementor widgets.
 *
 * @package IMPACT_WIDGETS_ELEMENTOR
 */

namespace ImpactAddons\ImpactWidgetsForElementor\Widgets;

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

trait Post_Context {
	protected function iaew_get_blog_context_post(): ?\WP_Post {
		$post_id = get_queried_object_id();

		if ( $post_id > 0 && 'post' === get_post_type( $post_id ) ) {
			return get_post( $post_id );
		}

		$current_post_id = get_the_ID();

		if ( $current_post_id > 0 && 'post' === get_post_type( $current_post_id ) ) {
			return get_post( $current_post_id );
		}

		if ( $this->iaew_is_elementor_editor() ) {
			$posts = get_posts(
				array(
					'post_type'      => 'post',
					'post_status'    => 'publish',
					'posts_per_page' => 1,
					'orderby'        => 'date',
					'order'          => 'DESC',
				)
			);

			if ( ! empty( $posts ) && $posts[0] instanceof \WP_Post ) {
				return $posts[0];
			}
		}

		return null;
	}

	protected function iaew_is_elementor_editor(): bool {
		if ( ! did_action( 'elementor/loaded' ) || ! class_exists( '\Elementor\Plugin' ) ) {
			return false;
		}

		return \Elementor\Plugin::$instance->editor->is_edit_mode();
	}

}
