<?php
namespace UM_Elementor\Helpers;

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

class UM_Logged_In_Login {

	/**
	 * @param array<string, mixed> $settings Widget settings.
	 */
	public static function handle_frontend( array $settings ): bool {
		$mode = isset( $settings['logged_in_login_mode'] )
			? sanitize_key( (string) $settings['logged_in_login_mode'] )
			: '';

		if ( '' === $mode ) {
			if ( ! empty( $settings['redirect_after_login']['url'] ) ) {
				$mode = 'redirect';
			} else {
				$mode = 'message';
			}
		}

		if ( 'redirect' === $mode ) {
			return self::maybe_redirect( $settings );
		}

		if ( 'welcome' === $mode ) {
			self::render_welcome( $settings );
			return true;
		}

		$message = isset( $settings['logged_in_simple_message'] )
			? (string) $settings['logged_in_simple_message']
			: __( 'You are already logged in.', 'ultimate-member-widgets-for-elementor' );

		if ( '' === trim( $message ) ) {
			$message = __( 'You are already logged in.', 'ultimate-member-widgets-for-elementor' );
		}

		echo '<p class="umep-form-logged-in-notice">' . esc_html( $message ) . '</p>';
		return true;
	}

	/**
	 * @param array<string, mixed> $settings
	 */
	private static function maybe_redirect( array $settings ): bool {
		$url = '';

		if ( ! empty( $settings['logged_in_login_redirect']['url'] ) ) {
			$url = (string) $settings['logged_in_login_redirect']['url'];
		} elseif ( ! empty( $settings['redirect_after_login']['url'] ) ) {
			$url = (string) $settings['redirect_after_login']['url'];
		}

		if ( '' === $url ) {
			$url = self::get_profile_url();
		}

		if ( '' === $url ) {
			return false;
		}

		$scheme      = is_ssl() ? 'https' : 'http';
		$host        = isset( $_SERVER['HTTP_HOST'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_HOST'] ) ) : '';
		$request_uri = isset( $_SERVER['REQUEST_URI'] ) ? (string) wp_unslash( $_SERVER['REQUEST_URI'] ) : '/';
		$current_url = '' !== $host ? esc_url_raw( $scheme . '://' . $host . $request_uri ) : '';

		$normalize_path = static function ( array $parts ): string {
			$h = isset( $parts['host'] ) ? strtolower( (string) $parts['host'] ) : '';
			$p = isset( $parts['path'] ) ? untrailingslashit( (string) $parts['path'] ) : '';
			return $h . $p;
		};

		$dest = wp_parse_url( esc_url_raw( $url ) );
		$here = $current_url !== '' ? wp_parse_url( $current_url ) : false;
		if ( is_array( $dest ) && is_array( $here ) && $normalize_path( $dest ) === $normalize_path( $here ) ) {
			self::render_welcome( $settings );
			return true;
		}

		wp_safe_redirect( esc_url_raw( $url ) );
		exit;
	}

	/**
	 * @param array<string, mixed> $settings
	 */
	public static function render_welcome( array $settings ): void {
		$user_id = get_current_user_id();
		$message = isset( $settings['logged_in_welcome_message'] )
			? (string) $settings['logged_in_welcome_message']
			: __( 'Welcome back, {display_name}!', 'ultimate-member-widgets-for-elementor' );

		if ( '' === trim( $message ) ) {
			$message = __( 'Welcome back, {display_name}!', 'ultimate-member-widgets-for-elementor' );
		}

		$message     = self::replace_tokens( $message, $user_id );
		$show_avatar = ! isset( $settings['logged_in_show_avatar'] ) || 'yes' === $settings['logged_in_show_avatar'];

		echo '<div class="umep-logged-in-welcome">';

		if ( $show_avatar && $user_id > 0 ) {
			echo '<div class="umep-logged-in-welcome-avatar">';
			echo get_avatar( $user_id, 96 );
			echo '</div>';
		}

		echo '<div class="umep-logged-in-welcome-body">';
		echo '<div class="umep-logged-in-welcome-message">' . wp_kses_post( wpautop( $message ) ) . '</div>';

		$links = self::get_action_links( $settings );
		if ( ! empty( $links ) ) {
			echo '<ul class="umep-logged-in-welcome-links">';
			foreach ( $links as $link ) {
				printf(
					'<li><a href="%1$s">%2$s</a></li>',
					esc_url( $link['url'] ),
					esc_html( $link['label'] )
				);
			}
			echo '</ul>';
		}

		echo '</div></div>';
	}

	/**
	 * @param array<string, mixed> $settings
	 * @return array<int, array{url: string, label: string}>
	 */
	private static function get_action_links( array $settings ): array {
		$links = [];

		if ( ! isset( $settings['logged_in_show_profile_link'] ) || 'yes' === $settings['logged_in_show_profile_link'] ) {
			$profile_url = self::get_profile_url();
			if ( '' !== $profile_url ) {
				$links[] = [
					'url'   => $profile_url,
					'label' => ! empty( $settings['logged_in_profile_label'] )
						? (string) $settings['logged_in_profile_label']
						: __( 'View profile', 'ultimate-member-widgets-for-elementor' ),
				];
			}
		}

		if ( ! isset( $settings['logged_in_show_account_link'] ) || 'yes' === $settings['logged_in_show_account_link'] ) {
			$account_url = self::get_account_url();
			if ( '' !== $account_url ) {
				$links[] = [
					'url'   => $account_url,
					'label' => ! empty( $settings['logged_in_account_label'] )
						? (string) $settings['logged_in_account_label']
						: __( 'Manage account', 'ultimate-member-widgets-for-elementor' ),
				];
			}
		}

		if ( ! isset( $settings['logged_in_show_logout_link'] ) || 'yes' === $settings['logged_in_show_logout_link'] ) {
			$logout_url = self::get_logout_url();
			if ( '' !== $logout_url ) {
				$links[] = [
					'url'   => $logout_url,
					'label' => ! empty( $settings['logged_in_logout_label'] )
						? (string) $settings['logged_in_logout_label']
						: __( 'Logout', 'ultimate-member-widgets-for-elementor' ),
				];
			}
		}

		return $links;
	}

	public static function replace_tokens( string $text, int $user_id ): string {
		$user = $user_id > 0 ? get_userdata( $user_id ) : false;
		$name = $user ? $user->display_name : '';

		if ( function_exists( 'um_user' ) && function_exists( 'um_fetch_user' ) && $user_id > 0 ) {
			um_fetch_user( $user_id );
			$um_name = um_user( 'display_name' );
			if ( is_string( $um_name ) && '' !== $um_name ) {
				$name = $um_name;
			}
			um_reset_user();
		}

		return str_replace( '{display_name}', $name, $text );
	}

	public static function get_profile_url(): string {
		if ( function_exists( 'um_user_profile_url' ) && is_user_logged_in() ) {
			$url = um_user_profile_url();
			if ( is_string( $url ) && '' !== $url ) {
				return $url;
			}
		}
		if ( function_exists( 'um_get_core_page' ) ) {
			return (string) um_get_core_page( 'user' );
		}
		return '';
	}

	public static function get_account_url(): string {
		if ( function_exists( 'um_get_core_page' ) ) {
			return (string) um_get_core_page( 'account' );
		}
		return '';
	}

	public static function get_logout_url(): string {
		if ( ! function_exists( 'um_get_core_page' ) ) {
			return '';
		}

		$logout_page = um_get_core_page( 'logout' );
		if ( '' === $logout_page ) {
			return wp_logout_url( home_url( '/' ) );
		}

		$redirect_to = home_url( '/' );
		if ( function_exists( 'UM' ) && is_object( UM()->permalinks() ) && method_exists( UM()->permalinks(), 'get_current_url' ) ) {
			$redirect_to = UM()->permalinks()->get_current_url( true );
		}

		return add_query_arg( 'redirect_to', $redirect_to, $logout_page );
	}
}
