<?php
/**
 * PostGate Login Handler Class
 *
 * This file contains the login handling functionality that manages
 * user redirects after login and payment intent processing. Handles
 * the complete flow from user authentication to content access or
 * payment initiation based on user intent parameters.
 *
 * @package PostGate
 * @subpackage Authentication
 * @since 1.0.0
 * @author QodeSphere
 * @license GPL-2.0+
 */

defined( 'ABSPATH' ) || exit;

/**
 * PostGate Login Handler Class
 *
 * Handles login-related functionality for the PostGate plugin, including
 * redirecting users after login based on their intent and cleaning up
 * URL parameters. Manages the flow from login to content access and
 * payment processing for both one-time purchases and subscriptions.
 *
 * This class ensures users are properly redirected to their intended
 * content after authentication, especially in paywall contexts. It
 * processes payment intents, validates access permissions, and initiates
 * Stripe checkout sessions when needed.
 *
 * Key Features:
 * - Login redirect handling based on user access permissions
 * - Payment intent processing from URL parameters
 * - Automatic checkout session creation for content access
 * - Support for both one-time and subscription payments
 * - URL cleanup to remove sensitive parameters
 * - Comprehensive error logging and validation
 *
 * @since 1.0.0
 */
class PostGate_Login_Handler {

	/**
	 * Initialize the login handler.
	 *
	 * Sets up WordPress hooks for login redirects and URL cleanup
	 * to manage the user experience after authentication. Registers
	 * filters and actions for handling login flow and intent processing.
	 *
	 * Hooks registered:
	 * - login_redirect: Handles post-login redirects based on user access
	 * - template_redirect: Processes payment intents from URL parameters
	 * - allowed_redirect_hosts: Adds Stripe domains to allowed redirect hosts
	 * - wp_footer: Cleans up sensitive parameters from browser URL
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public static function init() {
		add_filter( 'login_redirect', array( __CLASS__, 'handle_login_redirect' ), 10, 3 );
		add_action( 'template_redirect', array( __CLASS__, 'maybe_redirect_after_login_intent' ), 1 );
		add_filter( 'allowed_redirect_hosts', array( __CLASS__, 'add_stripe_to_allowed_redirect_hosts' ) );
		add_action( 'wp_footer', array( __CLASS__, 'clean_postgate_intent_from_url' ) );
	}

	/**
	 * Handle login redirection based on user access.
	 *
	 * @since 1.0.0
	 * @param string  $redirect_to           The redirect destination URL.
	 * @param string  $requested_redirect_to The requested redirect destination URL passed as a parameter.
	 * @param WP_User $user                  The WP_User object for the user being logged in.
	 * @return string The modified redirect URL.
	 */
	public static function handle_login_redirect( $redirect_to, $requested_redirect_to, $user ): string {
		if ( is_wp_error( $user ) || ! $user instanceof WP_User ) {
			return $redirect_to;
		}

		$post_id = url_to_postid( $requested_redirect_to );

		// If user has access to the requested post (via subscription or one-time purchase), redirect there.
		if ( $post_id && PostGate_Access_Manager::user_has_access( $user->ID, $post_id ) ) {
			return get_permalink( $post_id );
		}

		return $redirect_to ?: home_url();
	}

	/**
	 * Redirects users after login based on their intent.
	 *
	 * TEMPORARILY DISABLED to satisfy WordPress.org security requirements.
	 * 
	 * This function previously processed the `postgate_intent` parameter from the URL
	 * without nonce verification, which was flagged as a CSRF vulnerability by WordPress.org
	 * plugin directory revision. While the risk was minimal (no authenticated session for logged-out users,
	 * and actual payment requires Stripe authentication), we have disabled to satisfy WordPress.org security requirements.
	 *
	 * A state token system will be implemented in a future version (GitHub Issue #32)
	 * to restore single-click checkout while maintaining security according to the WordPress.org guidelines. 
	 * This will allow us to preserve user intent across the login process without exposing any vulnerabilities.
	 *
	 * Current behavior: Users must click the purchase button again after logging in.
	 * Future behavior: Intent will be preserved using secure state tokens.
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public static function maybe_redirect_after_login_intent(): void {
		// TEMPORARILY DISABLED - See function docblock for explanation
		// This will be re-enabled with proper state token validation (GitHub Issue #32)
		return;
	}

	/**
	 * Adds Stripe to the list of allowed redirect hosts.
	 *
	 * This ensures that redirects to Stripe domains are permitted
	 * during the checkout process initiated by PostGate.
	 *
	 * @since 1.0.0
	 * @param array $hosts The existing array of allowed redirect hosts.
	 * @return array The modified array including Stripe domains.
	 */

	public static function add_stripe_to_allowed_redirect_hosts( array $hosts ): array {
		$allowed_hosts = array(
			'checkout.stripe.com',
			'buy.stripe.com',
			'pay.stripe.com',
			'stripe.com'
		);

		return array_merge( $allowed_hosts, $hosts );
	}

	/**
	 * Cleans the `postgate_intent` parameter from the URL after login.
	 *
	 * Outputs a JavaScript snippet to remove the `postgate_intent` parameter
	 * from the browser's address bar without reloading the page.
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public static function clean_postgate_intent_from_url(): void {
		if ( ! is_user_logged_in() ) {
			return;
		}

		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Parameter presence check only.
		$intent_raw = (string) filter_input( INPUT_GET, 'postgate_intent', FILTER_UNSAFE_RAW );
		if ( '' === $intent_raw ) {
			return;
		}

		$script = 'const url = new URL(window.location.href);
			url.searchParams.delete("postgate_intent");
			window.history.replaceState({}, document.title, url);';

		wp_print_inline_script_tag( $script );

	}
}
