<?php

namespace Prodigy\Includes\Helpers;

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

/**
 * Ensure WordPress auth cookies are iframe-safe in cross-site contexts
 * such as SAP Ariba PunchOut embedding.
 */
class Prodigy_Wp_Cookie_Compatibility {

	/**
	 * Register hooks.
	 */
	public function __construct() {
		add_action( 'send_headers', array( $this, 'normalize_wp_cookie_headers_for_iframe' ), PHP_INT_MAX );
	}

	/**
	 * Rewrite Set-Cookie headers for WordPress auth cookies to:
	 * - SameSite=None
	 * - Secure
	 *
	 * @return void
	 */
	public function normalize_wp_cookie_headers_for_iframe(): void {
		if ( ! Prodigy_Cookies::request_uses_https() || ! function_exists( 'headers_list' ) ) {
			return;
		}

		$headers = headers_list();
		if ( empty( $headers ) ) {
			return;
		}

		$set_cookie_headers = array();
		foreach ( $headers as $header ) {
			if ( stripos( $header, 'Set-Cookie:' ) === 0 ) {
				$set_cookie_headers[] = $header;
			}
		}

		if ( empty( $set_cookie_headers ) ) {
			return;
		}

		$final_set_cookie_headers = array();
		$was_rewritten            = false;
		foreach ( $set_cookie_headers as $header ) {
			$cookie_header = trim( substr( $header, strlen( 'Set-Cookie:' ) ) );
			$final_header  = $this->rewrite_cookie_header_if_needed( $cookie_header );
			if ( $final_header !== $cookie_header ) {
				$was_rewritten = true;
			}
			$final_set_cookie_headers[] = 'Set-Cookie: ' . $final_header;
		}

		if ( ! $was_rewritten ) {
			return;
		}

		header_remove( 'Set-Cookie' );
		foreach ( $final_set_cookie_headers as $header ) {
			header( $header, false );
		}
	}

	/**
	 * @param string $cookie_header Raw header content without "Set-Cookie:".
	 *
	 * @return string
	 */
	private function rewrite_cookie_header_if_needed( string $cookie_header ): string {
		$parts = array_map( 'trim', explode( ';', $cookie_header ) );
		if ( empty( $parts ) || empty( $parts[0] ) ) {
			return $cookie_header;
		}

		$cookie_name_value = explode( '=', $parts[0], 2 );
		$cookie_name       = trim( $cookie_name_value[0] ?? '' );
		if ( $cookie_name === '' || ! $this->should_rewrite_cookie( $cookie_name ) ) {
			return $cookie_header;
		}

		$normalized_parts = array();
		foreach ( $parts as $part ) {
			$lower_part = strtolower( $part );
			if ( $lower_part === 'secure' || strpos( $lower_part, 'samesite=' ) === 0 ) {
				continue;
			}
			$normalized_parts[] = $part;
		}

		$normalized_parts[] = 'Secure';
		$normalized_parts[] = 'SameSite=None';

		return implode( '; ', $normalized_parts );
	}

	/**
	 * @param string $cookie_name
	 *
	 * @return bool
	 */
	private function should_rewrite_cookie( string $cookie_name ): bool {
		$cookie_prefixes = apply_filters(
			'prodigy_iframe_wp_cookie_prefixes',
			array(
				'wordpress_logged_in_',
				'wordpress_sec_',
				'wordpress_',
			)
		);

		foreach ( $cookie_prefixes as $prefix ) {
			if ( str_starts_with( $cookie_name, (string) $prefix ) ) {
				return true;
			}
		}

		return false;
	}
}
