<?php
/**
 * Binary download response helper.
 *
 * @package DhlPolska\Download
 */

namespace DhlPolska\Download;

class BinaryDownloadResponse {

	/**
	 * @param string $file_name .
	 * @param string $mime_type .
	 * @param string $content .
	 *
	 * @return void
	 */
	public function send( string $file_name, string $mime_type, string $content ): void {
		while ( ob_get_level() ) {
			ob_end_clean();
		}

		nocache_headers();
		header( 'X-Content-Type-Options: nosniff' );
		header( 'Content-Type: ' . $mime_type );
		header( 'Content-Disposition: attachment; filename="' . $file_name . '"' );
		header( 'Content-Length: ' . (string) strlen( $content ) );

		$output = fopen( 'php://output', 'wb' );
		if ( false === $output ) {
			throw new \RuntimeException( 'Unable to open output stream.' );
		}

		fwrite( $output, $content );
		fclose( $output );
		exit;
	}

	/**
	 * @param string $file_name .
	 * @param string $fallback_file_name .
	 *
	 * @return string
	 */
	public function sanitize_file_name( string $file_name, string $fallback_file_name ): string {
		$file_name = sanitize_file_name( $file_name );
		if ( '' !== $file_name ) {
			return $file_name;
		}

		return sanitize_file_name( $fallback_file_name );
	}

	/**
	 * @param string $mime_type .
	 * @param string $fallback .
	 *
	 * @return string
	 */
	public function sanitize_mime_type( string $mime_type, string $fallback = 'application/octet-stream' ): string {
		$mime_type = strtolower( trim( $mime_type ) );
		if ( '' === $mime_type ) {
			return $fallback;
		}

		if ( 1 !== preg_match( '/^[a-z0-9!#$&^_.+-]+\/[a-z0-9!#$&^_.+-]+$/', $mime_type ) ) {
			return $fallback;
		}

		return $mime_type;
	}
}
