<?php

namespace WPProofShield\Support;

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

final class RequestInput {

	public static function postText( string $key ): string {
		if ( $key === '' ) {
			return '';
		}

		$value = self::rawInput( INPUT_POST, $key );

		return self::sanitizeScalarText( $value );
	}

	public static function getText( string $key ): string {
		if ( $key === '' ) {
			return '';
		}

		$value = self::rawInput( INPUT_GET, $key );

		return self::sanitizeScalarText( $value );
	}

	public static function getKey( string $key ): string {
		if ( $key === '' ) {
			return '';
		}

		$value = self::rawInput( INPUT_GET, $key );

		return is_scalar( $value ) ? sanitize_key( (string) $value ) : '';
	}

	public static function requestText( string $key ): string {
		$post_value = self::postText( $key );
		if ( $post_value !== '' ) {
			return $post_value;
		}

		return self::getText( $key );
	}
	private static function sanitizeScalarText( mixed $value ): string {
		if ( ! is_scalar( $value ) ) {
			return '';
		}

		return trim( sanitize_text_field( (string) $value ) );
	}

	private static function rawInput( int $type, string $key ): mixed {
		$value = filter_input( $type, $key, FILTER_UNSAFE_RAW );
		if ( $value !== null && $value !== false ) {
			return $value;
		}

		if ( PHP_SAPI !== 'cli' ) {
			return null;
		}

		$source = $type === INPUT_POST ? '_POST' : '_GET';
		if ( ! isset( $GLOBALS[ $source ] ) || ! is_array( $GLOBALS[ $source ] ) ) {
			return null;
		}

		$input = $GLOBALS[ $source ];

		return array_key_exists( $key, $input ) ? wp_unslash( $input[ $key ] ) : null;
	}
}
