<?php

set_time_limit(600); // 10 minutes
ini_set('max_execution_time', 600);
ini_set('max_input_time', 600);
ini_set('memory_limit', '512M');



error_reporting (E_ALL & ~E_WARNING & ~E_NOTICE & ~E_DEPRECATED);



// lsm 3/12/24
function updateLog($string){

	if($_SERVER["DOCUMENT_ROOT"]==''){$_SERVER["DOCUMENT_ROOT"]='/home/medtack/public_html/documents.medtack.net';}
	
	if( $fh = fopen($_SERVER["DOCUMENT_ROOT"]."/logs/log.txt",'a+') ){
		
	
		//Append string
		fwrite( $fh, date('Y-m-d H:i:s',time())."\t" ); 
		fwrite( $fh, $string."\t" );		
		fwrite( $fh, "\n" );
	
		fclose( $fh );
	}
		
}




function stripAccents($str) {
    return strtr(utf8_decode($str), utf8_decode('àáâãäçèéêëìíîïñòóôõöùúûüýÿÀÁÂÃÄÇÈÉÊËÌÍÎÏÑÒÓÔÕÖÙÚÛÜÝ'), 'aaaaaceeeeiiiinooooouuuuyyAAAAACEEEEIIIINOOOOOUUUUY');
}


function deleteDir($dir) {
    foreach (glob($dir) as $file) {
        if (is_dir($file)) { 
            deleteDir("$file/*");
            rmdir($file);
        } else {
            unlink($file);
        }
    }
}



if($_POST['action']=="upload_document"){  

	

		$now = 				date("Y-m-d-H-i-s",time());
		$dir = 				$_SERVER['DOCUMENT_ROOT']."/uploads/".$_POST['patient_code']."/".$now;	
		$dir_to_delete = 	$_SERVER['DOCUMENT_ROOT']."/uploads/".$_POST['patient_code'];
		
		$dir_s3 = 			"uploads/".$_POST['patient_code']."/".$now;
	
				
		//create folder if it does not exist
		if(!file_exists($dir)){
			mkdir($dir, 0755,true);  
		}
		
		
		

		
	// if file is selected for upload
	// no upload allowed with php in filename
	// see htaccess /cg to prevent execution of any file with php in filename
	//&&  strpos($_FILES["profile_image"]["name"], 'php') === false
	if (isset($_FILES["file"]["name"]) && $_FILES["file"]["tmp_name"] != "" &&  strpos($_FILES["file"]["name"], 'php') === false){



	
		

		
     	
     	//get attributes   
     	

        $fileName = 			$_FILES["file"]["name"];
        $fileTmpLoc = 			$_FILES["file"]["tmp_name"];
        $fileType = 			$_FILES["file"]["type"];
        $fileSize = 			$_FILES["file"]["size"];
        $fileErrorMsg = 		$_FILES["file"]["error"];
        $kaboom = 				explode(".", $fileName);
        $fileExt = 				end($kaboom);
        list($width, $height) =	getimagesize($fileTmpLoc);

		
		$fileName = stripAccents($fileName);
		$fileName = str_replace(' ', '_', $fileName);
		$fileName = str_replace('?', '', $fileName);
		$fileName = str_replace('\'', '’', $fileName);
		$fileName = strtolower($fileName);
       
       	//save to temp user directory
        $moveResult = move_uploaded_file($fileTmpLoc, $dir."/".$fileName);
        chmod($dir."/".$fileName, 0755);
        
       
        
        
        if ($moveResult != true) {
            exit("ERROR: File upload failed");
        }else{
        
        
        


		
		
		
		

        	//SAVE RECORD TO SFDC

			
			$params = array(
				'mode' => "from_upload_form",
				'p' => $dir_s3."/".$fileName,
				's' => $dir."/".$fileName
			);
	
			$ch = curl_init();
			$http_params = http_build_query($params);
			

			
			/*
			$headers = array(
				'Content-Type:application/json',
				'Authorization: Basic '. base64_encode("admin:medtack2023#")
			);
			*/
			//$username="admin"; $password="medtack2023#";
			require_once("access_credentials_ba.php");
			
			
			
			
			curl_setopt($ch, CURLOPT_URL,  "https://documents.medtack.net/medical-records/api/uploadToS3.php");
			curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
			curl_setopt($ch, CURLOPT_POST, true);
			//curl_setopt($ch, CURLOPT_HEADER, 1);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $http_params);
			//curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
			curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:application/x-www-form-urlencoded"));
			//curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:application/octet-stream"));			
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_DEFAULT);
				// lsm 10/31/25
				curl_setopt($ch, CURLOPT_TIMEOUT, 300); // 5 minutes
				curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); // 30 seconds to connect

			$response = curl_exec($ch);
	
		
			if (curl_errno($ch)) {
				$error_msg = curl_error($ch);
			}
			curl_close($ch);

			if (isset($error_msg)) {
				// TODO - Handle cURL error accordingly
				echo $error_msg;
			}else{
				//delete temp user directory
				if($dir!=""){deleteDir($dir_to_delete);};
				echo "OK SAVED TO S3".$response." "; 
			}


			//SEND EMAIL TO DG
			// lsm 3/7/24
			$message = "FROM: https://documents.medtack.net/upload_api.php ". $dir_s3."/".$fileName;				
			//ONLY SENT TO: liquidskyweb@gmail.com
			$params = array(
				'message-credent-generic' => $message
			);
			// lsm 12/3/24
			//deactivated
			/*	
			$ch = curl_init();
			$http_params = http_build_query($params);
			curl_setopt($ch, CURLOPT_URL,  "https://service.medtack.net/api_gmail/api-gmail.php");			
			curl_setopt($ch, CURLOPT_POST, true);
			curl_setopt($ch, CURLOPT_HEADER, true);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $http_params); //DO NOT REMOVE (required from Gmail API)
			//curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:application/x-www-form-urlencoded"));
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
			curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_DEFAULT);
			$response = curl_exec($ch);
			curl_close($ch);
			*/


	
	
			//CREATE NEW MEDICAL RECORD
			
			// lsm 1/7/25
			//added &LLM=1
			
			//download2.php		display media using meta refresh
			//download.php 		display only presigned url fro SFDC
			
			// lsm 10/18/25
			$source = 'Upload';
			if (strpos($filename, "mp4") !== false) {
			$source = 'Video';
			}
			
			$params = array(
				'action' => 'save_medical_record_event',
				'Applicant_Doctor__c' => $_POST['id_cp'],
				'Applicant__c' => $_POST['id_ap'],
				'Candidate__c' => $_POST['id_rc'],				
				's3_bucket_id__c' => 'medtack-documents',
				's3_folder_id__c' => $dir_s3."/".$fileName,
				'EndPoint__c' => 'https://documents.medtack.net/medical-records/api/download.php?path='.$dir_s3."/".$fileName,
				'EndPoint_extract__c' => 'https://documents.medtack.net/medical-records/api/download_extract_upload.php?path='.$dir_s3."/".$fileName."&LLM=1",
				'File_Size__c' => $fileSize,
				'File_Extension__c' => strtolower($fileExt),
				'Source__c' => $source,
			);
			//picklist values for Source__c: Fax, Email, Manual, Upload 
			
			
			
	
			$ch = curl_init();
			$http_params = http_build_query($params);			
			curl_setopt($ch, CURLOPT_URL,  "https://documents.medtack.net/medical-records/api_sf/api2.php");
			curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
			curl_setopt($ch, CURLOPT_POST, true);
			curl_setopt($ch, CURLOPT_POSTFIELDS, $http_params);
			curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:application/x-www-form-urlencoded"));		
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_DEFAULT);
				// lsm 10/31/25
				curl_setopt($ch, CURLOPT_TIMEOUT, 300); // 5 minutes
				curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); // 30 seconds to connect
			
			$response = curl_exec($ch);
	
	
			if (curl_errno($ch)) {
				$error_msg = curl_error($ch);
			}
			curl_close($ch);

			if (isset($error_msg)) {
				// TODO - Handle cURL error accordingly
				echo $error_msg;
			}else{
				echo "OK SAVED TO SFDC ".$response." "; 
			}
			
			
			// lsm 1/7/25
			//added &LLM=1
			
			
			//RUN TEXTRACT FOR UPLOAD (WAIT FOR RESPONSE)
			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL,  "https://documents.medtack.net/medical-records/api/download_extract_upload.php?path=".$dir_s3."/".$fileName."&LLM=1");
			curl_setopt($ch, CURLOPT_USERPWD, $username . ":" . $password);
			curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:application/x-www-form-urlencoded"));
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
				// lsm 10/31/25
				//curl_setopt($ch, CURLOPT_TIMEOUT, 1); // ADD THIS - Don't wait
				//curl_setopt($ch, CURLOPT_NOSIGNAL, 1); // ADD THIS
			curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_DEFAULT);
				// lsm 10/31/25
				curl_setopt($ch, CURLOPT_TIMEOUT, 300); // 5 minutes
				curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); // 30 seconds to connect

			$response = curl_exec($ch);
			
			
			
			
			//LOG
			// lsm 3/12/24
			$message="";
			foreach ($_POST as $key => $value){
				//$message = "User Code: ".$_POST['patient_code']." ";
				//$message .= "Id Applicant: ".$_POST['id_ap']." ";
				$message .= "Field ".htmlspecialchars($key).": ".htmlspecialchars($value)." ";
			}
				$message .= "<br>";
				
				// lsm 5/1/24
				$message .= $response;
	
			updateLog("POST: ".$message);
			
			


			// lsm 2/24/26
			
			//auto extraction

			$ch = curl_init();
			curl_setopt($ch, CURLOPT_URL,  "https://documents.medtack.net/api_sf/api2.php?action=auto_extraction_upload&id_ap=".$_POST['id_ap']."&path=".$dir_s3."/".$fileName);

			curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-Type:application/x-www-form-urlencoded"));
			curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
			curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_DEFAULT);
			curl_setopt($ch, CURLOPT_TIMEOUT, 300); // 5 minutes
			curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30); // 30 seconds to connect

			$response2 = curl_exec($ch);
			
			updateLog("auto_extraction_upload (upload): ".$response2);

        }
        
 
        
        
    }



}

?> 