<?php
/**
 * Helper functions for incoming HTTP requests.
 *
 * @package northmill-online-shared
 */

declare(strict_types=1);

namespace Northmill_Online_Shared\Helpers;

defined( 'ABSPATH' ) || exit;

/**
 * HTTP_Request_Helper class.
 */
class HTTP_Request_Helpers {

	/**
	 * Get a sanitized $_POST value.
	 *
	 * @param string $key The key to get.
	 * @return string|array|null The sanitized value.
	 */
	public static function sanitize_post_key( string $key ): string|array|null {
		$data = $_POST[ $key ] ?? null; // phpcs:ignore WordPress.Security.NonceVerification.Missing

		if ( is_array( $data ) ) {
			return self::sanitize_post_array( $data );
		}

		return sanitize_text_field( $data );
	}

	/**
	 * Recursively sanitize a $_POST array.
	 *
	 * @param array $data The data to sanitize.
	 * @return array The sanitized data.
	 */
	public static function sanitize_post_array( array $data ): array {
		foreach ( $data as $key => $value ) {
			$data[ $key ] = is_array( $value ) ?
				self::sanitize_post_array( $value ) :
				sanitize_text_field( $value );
		}
		return $data;
	}

	/**
	 * Get a specific header from the request.
	 *
	 * @param string $header_name The name of the header to get.
	 *
	 * @return string|null
	 */
	public static function get_header( string $header_name ): ?string {
		$headers = array_change_key_case( getallheaders() );
		return $headers[ strtolower( $header_name ) ] ?? null;
	}

	/**
	 * Generate a Basic Auth header value.
	 *
	 * @param string $username The username.
	 * @param string $password The password.
	 *
	 * @return string The Basic Auth header value.
	 */
	public static function basic_auth( string $username, string $password ): string {
		return 'Basic ' . base64_encode( "$username:$password" ); // phpcs:ignore WordPress.PHP.DiscouragedPHPFunctions.obfuscation_base64_encode
	}
}
