<?php
/**
 * Helper for resolving the vehicle / dealer being edited in Elementor.
 *
 * In the Elementor editor or preview frame, `get_the_ID()` returns the
 * Elementor *document* ID, not the underlying post the template is being
 * built for. This helper falls back to `preview_id` (template builder),
 * then to the most recent published vehicle/dealer so the editor canvas
 * isn't empty when the widget is dropped onto a fresh document.
 *
 * @package ThemeREX\AutoDealer
 */

declare(strict_types=1);

namespace ThemeREX\AutoDealer\Elementor\Widgets;

if ( ! class_exists( '\Elementor\Plugin' ) ) {
	return;
}

use ThemeREX\AutoDealer\PostTypes\DealerPostType;
use ThemeREX\AutoDealer\PostTypes\VehiclePostType;

class ElementorPreviewContext {

	public static function isEditor(): bool {
		return \Elementor\Plugin::$instance->editor->is_edit_mode()
			|| \Elementor\Plugin::$instance->preview->is_preview_mode();
	}

	public static function resolveVehicleId(): int {
		return self::resolvePostId( VehiclePostType::POST_TYPE );
	}

	public static function resolveDealerId(): int {
		$id = self::resolvePostId( DealerPostType::POST_TYPE );
		if ( $id > 0 && DealerPostType::POST_TYPE === get_post_type( $id ) ) {
			return $id;
		}

		// No dealer in context — e.g. a Dealer Info/Map widget dropped on a
		// generic page. On a single-dealership site the dealer is unambiguous,
		// so fall back to the sole published dealer instead of rendering blank
		// (UAT #42). Multi-dealer sites must pick a dealer in the widget.
		$dealers = get_posts(
			array(
				'post_type'      => DealerPostType::POST_TYPE,
				'posts_per_page' => 2,
				'post_status'    => 'publish',
				'fields'         => 'ids',
				'no_found_rows'  => true,
			)
		);
		return 1 === count( $dealers ) ? (int) $dealers[0] : 0;
	}

	private static function resolvePostId( string $postType ): int {
		// Frontend — trust the global post.
		if ( ! self::isEditor() ) {
			$id = (int) get_the_ID();
			if ( $id > 0 && get_post_type( $id ) === $postType ) {
				return $id;
			}
			return $id; // Block resolves to global post; let it decide.
		}

		// Template builder — `preview_id` is the post the template targets.
		$current = \Elementor\Plugin::$instance->documents->get_current();
		if ( $current ) {
			$preview_id = (int) ( $current->get_settings( 'preview_id' ) ?? 0 );
			if ( $preview_id > 0 && get_post_type( $preview_id ) === $postType ) {
				return $preview_id;
			}
		}

		// Fall back to the most recent published post of the right type so
		// the editor canvas isn't blank when previewing a fresh document.
		$posts = get_posts(
			array(
				'post_type'      => $postType,
				'posts_per_page' => 1,
				'post_status'    => 'publish',
				'fields'         => 'ids',
			)
		);

		return ! empty( $posts ) ? (int) $posts[0] : 0;
	}
}
