<?php
/**
 * PostGate Access Redirect Handler Class
 *
 * This file contains the redirect handling logic for post-payment
 * redirects and access granting after successful payments.
 *
 * @package PostGate
 * @subpackage AccessControl
 * @since 1.0.0
 * @author QodeSphere
 * @license GPL-2.0+
 */

defined( 'ABSPATH' ) || exit;

/**
 * PostGate Access Redirect Handler Class
 *
 * Handles redirects after successful payments and subscription
 * activations. Manages the flow from payment completion back
 * to the protected content with appropriate access granted.
 *
 * This class processes payment success callbacks and ensures
 * users are properly redirected with access permissions updated.
 *
 * @since 1.0.0
 */
class PostGate_Access_Redirect_Handler {

	/**
	 * Initialize the redirect handler.
	 *
	 * Sets up WordPress hooks for handling payment success redirects
	 * and subscription activation callbacks.
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public static function init(): void {
		add_action( 'template_redirect', [ __CLASS__, 'handle_purchase_success' ] );
	}

	/**
	 * Handle unified purchase success redirect.
	 *
	 * Processes successful one-time and subscription payment completion.
	 * Redirects users based on the "After Purchase Behavior" setting to either
	 * a custom page or back to the purchased content.
	 *
	 * Note: With webhook-based order creation (Issue #24), orders are created after
	 * this redirect completes. We use the current page context (where Stripe redirected)
	 * as the origin post when determining redirect targets.
	 *
	 * Security:
	 * - Requires valid nonce to prevent CSRF attacks
	 * - Requires authenticated user session
	 *
	 * @since 1.0.0
	 * @return void
	 */
	public static function handle_purchase_success(): void {
		// Early exit: require success parameter and logged-in user
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce verification done below.
		if ( ! isset( $_GET['postgate_purchase_success'] ) || ! is_user_logged_in() ) {
			return;
		}

		// Validate success flag
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce verification done below.
		$success_flag = sanitize_text_field( wp_unslash( $_GET['postgate_purchase_success'] ) );
		if ( '1' !== $success_flag ) {
			return;
		}

		// Verify nonce to prevent CSRF attacks
		// phpcs:ignore WordPress.Security.NonceVerification.Recommended -- Nonce verification done below with wp_verify_nonce.
		$nonce = isset( $_GET['postgate_purchase_success_nonce'] )
			? sanitize_text_field( wp_unslash( $_GET['postgate_purchase_success_nonce'] ) )
			: '';

		if ( ! wp_verify_nonce( $nonce, 'postgate_purchase_success' ) ) {
			return;
		}

		// Determine target URL based on configured behavior
		$behavior = get_option( 'postgate_after_purchase_behavior', 'return-to-post' );
		$target_url = null;

		// Behavior 1: Redirect to custom thank-you page
		if ( 'redirect-page' === $behavior ) {
			$redirect_slug = get_option( 'postgate_after_purchase_page', '' );
			if ( ! empty( $redirect_slug ) ) {
				$target_url = home_url( '/' . trailingslashit( $redirect_slug ) );
			}
		}
		// Behavior 2: Return to purchased post (use current page as origin)
		elseif ( 'return-to-post' === $behavior && is_singular() ) {
			$origin_post_id = get_queried_object_id();
			if ( $origin_post_id > 0 ) {
				$target_url = get_permalink( $origin_post_id );
			}
		}

		// No valid target? Let page load normally with success parameters
		if ( ! $target_url ) {
			return;
		}

		// Already on target page? No redirect needed
		$current_url = home_url( add_query_arg( null, null ) );
		$current_path = wp_parse_url( $current_url, PHP_URL_PATH );
		$target_path = wp_parse_url( $target_url, PHP_URL_PATH );

		$current_path = is_string( $current_path ) ? rtrim( $current_path, '/' ) : '';
		$target_path = is_string( $target_path ) ? rtrim( $target_path, '/' ) : '';

		if ( $current_path === $target_path ) {
			return;
		}

		// Redirect to target page with parameters preserved
		$redirect_url = add_query_arg(
			[
				'postgate_purchase_success' => 1,
				'postgate_purchase_success_nonce' => wp_create_nonce( 'postgate_purchase_success' ),
			],
			$target_url
		);

		wp_safe_redirect( $redirect_url );
		exit;
	}
}