<?php
namespace SabaiApps\Directories;

use SabaiApps\Framework\Application\HttpRequest;

/**
 * Request class for handling HTTP request data and AJAX/modal detection.
 * Provides methods for checking AJAX/modal requests and generating URLs without system parameters.
 */
class Request extends HttpRequest {

	/**
	 * @var mixed Stores AJAX request state.
	 */
	protected static $_isAjax;

	// Pre-defined request parameter constants
	const PARAM_AJAX = 'drts_ajax', PARAM_TOKEN = 'drts_t', PARAM_CONTENT_TYPE = 'drts_content_type';

	/**
	 * Checks if the current request is an AJAX request.
	 *
	 * @return bool|string
	 */
	public static function isAjax() {
		if ( ! isset( self::$_isAjax ) ) {
			if ( empty( $_REQUEST[ self::PARAM_AJAX ] )
				|| ( ! self::$_isAjax = preg_replace( '/[^A-Za-z0-9_\-\.# ]/', ' ', str_replace( array( '%23', '%20' ), array( '#', ' ' ), $_REQUEST[ self::PARAM_AJAX ] ) ) )
			) {
				self::$_isAjax = self::isXhr();
			}
		}

		return self::$_isAjax;
	}

	/**
	 * Checks if the current request is a modal AJAX request.
	 *
	 * @return bool
	 */
	public static function isModal() {
		return self::isAjax() && strpos( self::$_isAjax, '#drts-modal' ) === 0;
	}

	/**
	 * Gets the current URL, optionally including the query string, and removes system parameters.
	 *
	 * @param bool $withQueryStr
	 * @return string
	 */
	public static function url( $withQueryStr = true ) {
		$url = parent::url( $withQueryStr );

		if ( ! $withQueryStr ) {
			return $url;
		}

		// Attempt to parse URL and remove ajax/token system parameters
		if ( $parsed = parse_url( $url ) ) {
			if ( ! empty( $parsed['query'] ) ) {
				$params = array();
				parse_str( rawurldecode( $parsed['query'] ), $params );
				unset( $params[ self::PARAM_AJAX ], $params[ self::PARAM_TOKEN ] );
				$query_str = '?' . strtr(
					http_build_query( $params ),
					array(
						'%7E' => '~',
						'+'   => '%20',
					)
				); // http_build_query does urlencode, so need a little adjustment for RFC1738 compat
			} else {
				$query_str = '';
			}

			$url = sprintf(
				'%s://%s%s%s%s',
				$parsed['scheme'],
				! empty( $parsed['port'] ) ? $parsed['host'] . ':' . $parsed['port'] : $parsed['host'],
				$parsed['path'],
				$query_str,
				! empty( $parsed['fragment'] ) ? '#' . $parsed['fragment'] : ''
			);
		}

		return $url;
	}
}
