<?php



	$token 			= 		filter_input( INPUT_GET, 'signature', FILTER_SANITIZE_STRING );


	if( $token == null ) {

		invalid_token();
		die;

	}

	else {

		$re_url 	= 	'https://faraagahi.com/wp-json/api/v1/validatetoken/';
		$response 	= 	json_decode( validate_token( $re_url, $token ) );
		$status 	= 	$response->status;

			if($status == "success"){

				$filename 		= $response->data->filename;
				$path	  	    = $response->data->path;
				send_file( $filename, $path );
				die;

			}
			else {

				invalid_token();
				die;

			}
	}


function invalid_token(){

		http_response_code(401);
		$response = array(
			"status" => "error",
			"message" => "unauthorized"
		);

		header('Content-Type: application/json');
		echo json_encode($response);

}


function validate_token( $re_url, $token, $method = 'POST' ){

	$curl = curl_init();
	curl_setopt_array($curl, array(
	CURLOPT_URL => $re_url,
	CURLOPT_RETURNTRANSFER => true,
	CURLOPT_ENCODING => '',
	CURLOPT_MAXREDIRS => 10,
	CURLOPT_TIMEOUT => 0,
	CURLOPT_FOLLOWLOCATION => true,
	CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
	CURLOPT_CUSTOMREQUEST => $method,
	CURLOPT_POSTFIELDS => json_encode(array( "token" => $token )),
	CURLOPT_HTTPHEADER => array( 'Content-Type: application/json' ),
	));
	$response = curl_exec($curl);
	curl_close($curl);

	return $response;
}


function send_file( $filename, $path ){

	$path        	=         $path . $filename;
	$mime_type 		= 		  mime_content_type($path);

	clean_buf();
	header("Content-Type: $mime_type");
	header("Content-Disposition: attachment; filename=$filename");
	header("X-Accel-Redirect: /$path");

}


function clean_buf(){
	if (ob_get_level()) {
		$levels = ob_get_level();
		for ($i = 0; $i < $levels; $i++) {
			@ob_end_clean();
		}
	} else {
		@ob_end_clean();
	}
}

?>