<?PHP
include("loginCheckPoint.php");
include_once("authorizations.php");
require_once("demosettings.php");
include_once 'write_log.php';
require_once 'sqlUtils.php';
require_once 'parseUtils.php';
require_once 'pdfTools.php';
$pdfClass = new PDFTools();

$userdetails = fetchUserDetails($_SESSION['username']);

global $folderSeparator;
global $CURRENT_SOURCE_FOLDER;
// Define the path to file
 //$filename = $_REQUEST["filename"];

$id = $_REQUEST["dcid"] ?? $_REQUEST["docId"];
 $directory = getDocMetadataFolder($id);

 $id = intval($_REQUEST["dcid"] ?? $_REQUEST["docId"]);
 //check if user is authorized to access document
 if (!getUserPermission(CAN_SHOW_ALL_USER))
 {
 	$mysqli = sqlCreateConnection("download");
 	$res = sqlQuery($mysqli, "SELECT id FROM files where id = $id AND username='" . $mysqli->real_escape_string($userdetails["Username"]) . "'");
 	if (empty($res))
 	{
 		die("User is not authorized to access document");
 		sqlClose($mysqli, 'download');
 	}
 }
 

 if (!empty($_REQUEST["AsRedactedImage"]))
 {
 	$fullPath = getDocRedactedImageName($mysqli, $id, $_REQUEST["pageNum"]);
 	if (file_exists($fullPath))
 	{
 		$responseAsString = "data:image/png;base64," . base64_encode(file_get_contents($fullPath));
 	}
 	else{
 		echo json_encode(array("status"=>"not-found"));
 	}
 } elseif ($_REQUEST["origFile"])
 {
 	$fullPath = docIdToFilePath($id);
 	//check if file exists in path - if not check folder+filename in uploads folder
 	if(!file_exists($fullPath)){
 	    global $UPLOADS_PATH;
 	    $file_name = basename($fullPath);
 	    $folder_name = basename(dirname($fullPath));
 	    
 	    $fullPath = $UPLOADS_PATH.DIRECTORY_SEPARATOR.$folder_name.DIRECTORY_SEPARATOR.$file_name;
 	    if(!file_exists($fullPath)){
 	        write_to_log('ERROR', "file $file_name doesnt exists ivprojects or uploads");
 	    }
 	}
 	
	//convert to PDF
 	
	if (($_REQUEST["inBrowser"] || $_REQUEST["AsImage"]) && $pdfClass->shouldConvertToPdf($fullPath))
 	{
 	    $fullPath = $pdfClass->convertToPdf($fullPath, $id);
 	    if (!$fullPath){
 			die();
 		}
 	}
 }
 else {
    $chartName = $_REQUEST["chartName"];
    if(strlen($chartName)>1) {
        $filename = "$chartName.csv";
        write_to_log("INFO", "download file - $filename");
    } else {
        $filename = "result_$id.xml";
    }
    $fullPath = $directory . $folderSeparator . $filename;
}

if (!empty($_REQUEST["AsImage"]))
{
	$extension = pathinfo($fullPath, PATHINFO_EXTENSION);
	if ($extension == "pdf")
	{
		$pageNum = $_REQUEST["pageNum"];
		if (!$pageNum)
			$pageNum = 1;
			$imagesCount = $pdfClass->pdfToImage($fullPath, $id);
		if ($imagesCount < $pageNum)
		{
			$error = "Image file $pageNum not found for doc $id";
			write_to_log("ERROR", $error);
			die($error);
		}
		$fullPath = getImageFileName($id, $pageNum);
	}
	else
		write_to_log("ERROR", "download AsImage option not supported for extension $extension");
}

$contentLength = empty($responseAsString)? filesize($fullPath) : strlen($responseAsString);

 if ($_REQUEST["inBrowser"])
 {
    $ext = pathinfo($fullPath, PATHINFO_EXTENSION);
    if (strtolower($ext) == "pdf")
        header('Content-type: application/pdf');
    if (strtolower($ext) == "png")
    	header('Content-type: image/png');
    
    header('Content-Disposition: inline; filename="' . basename($fullPath) . '"');
    header('Content-Transfer-Encoding: binary');
    header('Content-Length: ' . $contentLength);
    header('Accept-Ranges: bytes');
 } else {
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($fullPath));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate');
    header('Pragma: public');
    header('Content-Length: ' . $contentLength);
 }
    
ob_clean();
flush();
if (!empty($responseAsString))
	echo $responseAsString;
else
readfile($fullPath);
?>