<?php
/**
 * Detects front-end contexts where social login assets may load.
 *
 * @package WP_PowerSuite\OAuth\UI
 */

namespace WP_PowerSuite\OAuth\UI;

use WP_PowerSuite\OAuth\SocialShortcodeService;

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

final class SocialAssetContext {

	/**
	 * wp-login.php and wp-register.php (when registration is open).
	 */
	public static function isLoginScreen(): bool {
		if ( function_exists( 'is_login' ) && is_login() ) {
			return true;
		}
		global $pagenow;
		return isset( $pagenow ) && in_array( $pagenow, [ 'wp-login.php', 'wp-register.php' ], true );
	}

	/**
	 * WooCommerce my-account, checkout login, or registration forms.
	 */
	public static function isWooCommerceAuthContext(): bool {
		if ( ! class_exists( 'WooCommerce' ) ) {
			return false;
		}
		if ( function_exists( 'is_account_page' ) && is_account_page() ) {
			return true;
		}
		if ( function_exists( 'is_checkout' ) && is_checkout() ) {
			return true;
		}
		return false;
	}

	/**
	 * True when a page/post contains a social login shortcode (parsed once per request).
	 */
	public static function pageHasSocialShortcode(): bool {
		static $checked = false;
		static $found   = false;
		if ( $checked ) {
			return $found;
		}
		$checked = true;
		if ( ! is_singular() ) {
			return false;
		}
		$post = get_post();
		if ( ! $post instanceof \WP_Post ) {
			return false;
		}
		$content = (string) $post->post_content;
		if ( $content === '' ) {
			return false;
		}
		$tags = [ 'social_login', 'google_sign_in', 'facebook_sign_in', 'github_sign_in', 'wpps_social_accounts' ];
		foreach ( $tags as $tag ) {
			if ( has_shortcode( $content, $tag ) ) {
				$found = true;
				return true;
			}
		}
		return false;
	}

	public static function shouldLoadFrontendStyles( bool $woo_login_enabled = false ): bool {
		if ( self::isLoginScreen() ) {
			return true;
		}
		if ( SocialShortcodeService::wasUsedThisRequest() ) {
			return true;
		}
		if ( $woo_login_enabled && self::isWooCommerceAuthContext() ) {
			return true;
		}
		if ( self::pageHasSocialShortcode() ) {
			return true;
		}
		return false;
	}
}
