<?php
/**
 * Media handler
 *
 * @package crewhrm
 */

namespace CrewHRM\Controllers;

/**
 * Media controller
 */
class MediaHandler {
	const PREREQUISITES = array(
		'loadFile' => array(
			'role' => array( 'administrator' ), // For now only administrator as only they need to review applications. Need to update later as per situation.
		),
	);

	/**
	 * Load file
	 *
	 * @param int $file_id The fiel ID to load
	 * @return void
	 */
	public static function loadFile( int $file_id ) {

		$path = get_attached_file( $file_id );

		require_once ABSPATH . 'wp-admin/includes/file.php';
		global $wp_filesystem;
		WP_Filesystem();

		if ( empty( $path ) || ! is_readable( $path ) ) {
			http_response_code( 404 );
			exit;
		}

		if ( ! $wp_filesystem ) {
			http_response_code( 500 );
			exit;
		}

		$file_contents = $wp_filesystem->get_contents( $path );
		if ( false === $file_contents ) {
			http_response_code( 404 );
			exit;
		}

		$mime_type = mime_content_type( $path );
		$file_size = strlen( $file_contents );

		$allowed_html = wp_kses_allowed_html( 'post' );
		$allowed_html['html']  = array(
			'lang' => true,
			'dir'  => true,
		);
		$allowed_html['head']  = array();
		$allowed_html['meta']  = array(
			'charset'    => true,
			'name'       => true,
			'content'    => true,
			'http-equiv' => true,
		);
		$allowed_html['title'] = array();
		$allowed_html['body']  = array(
			'class' => true,
			'id'    => true,
			'style' => true,
		);
		$allowed_html['style'] = array(
			'type' => true,
		);

		nocache_headers();
		header( 'Content-Type: ' . $mime_type . '; charset=utf-8' );
		header( 'Content-Disposition: attachment; filename=' . basename( $path ) );
		header( 'Content-Length: ' . $file_size );
		header( 'Pragma: no-cache' );
		header( 'Expires: 0' );

		echo wp_kses( $file_contents, $allowed_html );
		exit;
	}
}
