<?php
namespace UM_Elementor\Helpers;

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

/**
 * Resolves the correct user ID for the profile being viewed.
 * Handles editor mode, frontend profile pages, and AJAX requests.
 */
class UM_Profile_Context {

	/**
	 * Get the user ID of the profile currently being rendered.
	 * Returns 0 if context cannot be resolved.
	 */
	public static function get_profile_user_id(): int {

		if ( self::is_elementor_edit_mode() ) {
			return (int) get_current_user_id();
		}

		if ( function_exists( 'um_profile_id' ) ) {
			$id = (int) um_profile_id();
			if ( $id > 0 ) {
				return $id;
			}
		}

		if ( defined( 'DOING_AJAX' ) && DOING_AJAX ) {
			// phpcs:ignore WordPress.Security.NonceVerification.Missing -- Elementor/editor context; value validated below.
			$id = isset( $_POST['profile_user_id'] ) ? (int) wp_unslash( $_POST['profile_user_id'] ) : 0;
			if ( $id > 0 && get_user_by( 'id', $id ) ) {
				return $id;
			}
		}

		return 0;
	}

	/**
	 * First available member for editor preview when no profile context exists.
	 */
	public static function get_sample_member_user_id(): int {
		$users = get_users(
			[
				'number'  => 1,
				'orderby' => 'ID',
				'order'   => 'ASC',
				'fields'  => 'ID',
			]
		);

		if ( empty( $users[0] ) ) {
			return 0;
		}

		return (int) $users[0];
	}

	/**
	 * Set UM's global user context to this user ID.
	 */
	public static function setup( int $user_id ): bool {
		if ( ! $user_id ) {
			return false;
		}
		if ( ! function_exists( 'um_fetch_user' ) ) {
			return false;
		}
		if ( ! get_user_by( 'id', $user_id ) ) {
			return false;
		}

		um_fetch_user( $user_id );
		return true;
	}

	/**
	 * Reset UM global user context after rendering.
	 */
	public static function teardown(): void {
		if ( function_exists( 'um_reset_user' ) ) {
			um_reset_user();
		}
	}

	/**
	 * Whether we are inside the Elementor editor canvas (not live preview iframe semantics).
	 */
	public static function is_elementor_edit_mode(): bool {
		if ( ! class_exists( '\Elementor\Plugin' ) ) {
			return false;
		}
		$plugin = \Elementor\Plugin::$instance;
		if ( ! isset( $plugin->editor ) ) {
			return false;
		}
		return $plugin->editor->is_edit_mode();
	}

	/**
	 * Elementor preview iframe — treat like frontend for data.
	 */
	public static function is_elementor_preview_mode(): bool {
		if ( ! class_exists( '\Elementor\Plugin' ) ) {
			return false;
		}
		$plugin = \Elementor\Plugin::$instance;
		if ( ! isset( $plugin->preview ) ) {
			return false;
		}
		return $plugin->preview->is_preview_mode();
	}
}
