<?php
require_once('config.php');
require_once('utility_image.php');

$uploaddir;
$error_message;
$valid = true;
$json_return = array();
$json_return2 = array();
$json_return = [];

$maxsize = 5242880; // 5MB


if ($_SERVER["REQUEST_METHOD"] == "POST") { 

	$count    	   	= $_REQUEST["count"];
	$json 			= $_REQUEST["json"];
	$json 			= json_decode($json);
	$rowid			= $json->data->rowid;
	$site_cd		= $json->data->site_cd;
	$EMPID			= $json->data->EMPID;
	$folder			= $json->data->folder;
	$LOGINID		= $json->data->LOGINID;
	$dvc_id			= $json->data->dvc_id;

	$uploaddir = "C:\\wamp64\\www\\".$folder."\\temp_".$dvc_id."\\";
	
/* 	if (file_exists($uploaddir)) {
    	echo 'The file $filename exists';
	} else {
	    echo 'The file $filename does not exist';
	} */
	if (!is_dir($uploaddir)) {
		mkdir($uploaddir, 0777, true);
		mkdir($uploaddir."\\thumbnail\\", 0777, true);
	}
	
	//echo $uploaddir;
	
$sql = "select total = count(*) from wkr_mst, wkr_ref 
		where wkr_mst.site_cd = wkr_ref.site_cd
		and wkr_mst.rowid= wkr_ref.mst_rowid
		and wkr_ref.type = 'P' 
		and wkr_ref.mst_rowid = '".$rowid."'";	
		
$stmt = sqlsrv_query( $conn, $sql);	
		
if( !$stmt ) {
	$error_message = "Error update table (itm_mst)";
	returnError($error_message);
	die( print_r( sqlsrv_errors(), true));
}
do {
     while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
	 
	 $total = $row['total'];	 
	 	 
   }
} while ( sqlsrv_next_result($stmt));
	
	if($total == 0){
		
		$types = "P";
		
	}else{
		
		$types = "A";
	}
		
		for ($x = 1; $x <= $count; $x++) {
		 
		 $file_name = $_FILES['file_'.$x]['name'];	
		 $file_type = $_FILES['file_'.$x]['type'];	
			
			
		if (strpos($file_name, '.png') == true) {		
				
							
			$file_name = str_replace(".png",".jpeg",$file_name);
			$imageObject = $_FILES['file_'.$x]['tmp_name'];	
			$fullPathwithfileName = $uploaddir.$file_name;
			
			if(move_uploaded_file($imageObject, $fullPathwithfileName)){
				
				//Check if file exist
				if (file_exists($fullPathwithfileName)) {
					// list($width, $height, $type) = getimagesize($fullPathwithfileName);
					// $imageObject = load_image($fullPathwithfileName, $type);
					// # Get exif information
					// $exif = exif_read_data($fullPathwithfileName);
				} else {
					echo "File not exist";
				}
				$datastring= file_get_contents($fullPathwithfileName);
				$data=unpack("H*hex", $datastring);
				
				$sql = "INSERT INTO wkr_ref	(	site_cd, 			audit_user, 		audit_date, 		status,					column1, 
												FILE_NAME, 			type, 				mst_rowid, 			attachment,				mbl_audit_user,		
												mbl_audit_date) 
									VALUES	(	'".$site_cd."',		'".$EMPID."', 		getdate(),			'Saved', 				'Native', 
												'".$file_name."',	'".$types."', 		".$rowid.", 		0x".$data['hex'].",		'".$LOGINID."',		
												getdate()) SELECT SCOPE_IDENTITY() as rowid";
								
				$stmt = sqlsrv_query( $conn, $sql);				
								
				if( !$stmt ) {
					$error_message = "Error insert table (PNG_wkr_ref)";
					returnError($error_message);
					die( print_r( sqlsrv_errors(), true));
				}else{
					unlink($fullPathwithfileName);
				}

				$json_wkr_ref = array();
				do {
					while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
						$json_wkr_ref['rowid'] = $row['rowid'];
						$json_wkr_ref['action'] = "INSERT";
						array_push($json_return2, $json_wkr_ref);
						
					}
				} while ( sqlsrv_next_result($stmt) );	
				
			}
				
			
				
				
				
			
				
				 
		}else if (strpos($file_name, '.jpg') !== false){	
				
				
			$imageObject = $_FILES['file_'.$x]['tmp_name'];
			$fullPathwithfileName = $uploaddir.$file_name;
			//echo $fullPathwithfileName;
			if (move_uploaded_file($imageObject, $fullPathwithfileName)){
				
				//Check if file exist
				if (file_exists($fullPathwithfileName)) {
					// list($width, $height, $type) = getimagesize($fullPathwithfileName);
					// $imageObject = load_image($fullPathwithfileName, $type);
					// # Get exif information
					// $exif = exif_read_data($fullPathwithfileName);
				} else {
					echo "File not exist";
				}
			
			
				$datastring= file_get_contents($fullPathwithfileName);
				$data=unpack("H*hex", $datastring);
				
				if (count($data) > 0){
					
					$sql = "INSERT INTO wkr_ref	(	site_cd, 			audit_user, 		audit_date, 		status,					column1, 
													FILE_NAME, 			type, 				mst_rowid, 			attachment,				mbl_audit_user,		
													mbl_audit_date) 
										VALUES 	(	'".$site_cd."',		'".$EMPID."', 		getdate(),			'Saved', 				'Native', 
													'".$file_name."',	'".$types."', 		".$rowid.", 		0x".$data['hex'].",		'".$LOGINID."',		
													getdate()) SELECT SCOPE_IDENTITY() as rowid";
		
		
						$stmt = sqlsrv_query( $conn, $sql);				
										
						if( !$stmt ) {
							$error_message = "Error insert table JPG_wkr_ref)";
							returnError($error_message);
							die( print_r( sqlsrv_errors(), true));
						}else{
							unlink($fullPathwithfileName);
						}

						$json_wkr_ref = array();
						do {
							while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
								$json_wkr_ref['rowid'] = $row['rowid'];
								$json_wkr_ref['action'] = "INSERT";
								array_push($json_return2, $json_wkr_ref);
								
							}
					   } while ( sqlsrv_next_result($stmt) );
					
					
				}else{
					$json_ast_ref['rowid'] = 0;
					$json_ast_ref['action'] = "Unpack failed for image file (".$file_name.")";
					array_push($json_return2, $json_ast_ref);
				}
			}else{
				$json_ast_ref['rowid'] = 0;
				$json_ast_ref['action'] = "move_uploaded_file failed for image file (".$file_name.")";
				array_push($json_return2, $json_ast_ref);
			}
					
				
		}else if (strpos($file_name, '.mp4') !== false) {		
				
				
				
				$videoObject = $_FILES['file_'.$x]['tmp_name'];
				$fullPathwithfileName = $uploaddir.$file_name;
				
				$substr = substr(md5(time()), 0, 3);
				$file_name = $x.'_'.$substr.'_video.mp4';

				$extension = strtolower(pathinfo($file_name,PATHINFO_EXTENSION));
				// Valid file extensions
				$extensions_arr = array("mp4","avi","3gp","mov","mpeg");
				
				// Check extension
			   if( in_array($extension,$extensions_arr) ){
				   
					/* // Check file size
					if(($_FILES['file_'.$x]['size'] >= $maxsize) || ($_FILES['file_'.$x]["size"] == 0)) {
						
						$error_message = "File too large. File must be less than 5MB.";
						returnError($error_message);
						die( print_r( sqlsrv_errors(), true));
					}else{
						
						
						
					} */
					
					
					if (move_uploaded_file($videoObject, $fullPathwithfileName)){
					
							$datastring= file_get_contents($fullPathwithfileName);
							$data=unpack("H*hex", $datastring);
							
							$sql = "INSERT INTO wkr_ref	(	site_cd, 			audit_user, 		audit_date, 		status,					column1, 
															FILE_NAME, 			type, 				mst_rowid, 			attachment,				mbl_audit_user,		
															mbl_audit_date) 
												VALUES 	(	'".$site_cd."',		'".$EMPID."', 		getdate(),			'Saved', 				'Native', 
															'".$file_name."',	'".$types."', 		".$rowid.", 		0x".$data['hex'].",		'".$LOGINID."',		
															getdate()) SELECT SCOPE_IDENTITY() as rowid";
						
						
										$stmt = sqlsrv_query( $conn, $sql);				
														
										if( !$stmt ) {
											$error_message = "Error insert table (Mp4_wkr_ref)";
											returnError($error_message);
											die( print_r( sqlsrv_errors(), true));
										}else{
											unlink($fullPathwithfileName);
										}

										$json_wkr_ref = array();
										do {
											while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
												$json_wkr_ref['rowid'] = $row['rowid'];
												$json_wkr_ref['action'] = "INSERT";
												array_push($json_return2, $json_wkr_ref);
												
											}
									   } while ( sqlsrv_next_result($stmt) );
						
							
						}
				   
			   }else{
				   
				   $error_message = "Invalid file extension.";
					returnError($error_message);
					die( print_r( sqlsrv_errors(), true));
					
			   }			

			
			
		}else if (strpos($file_name, '.pdf') !== false) {	
		
			$image = $_FILES['file_'.$x]['tmp_name'];
			$fullPathwithfileName = $uploaddir.$file_name;
			move_uploaded_file($image, $fullPathwithfileName);			
			$datastring= file_get_contents($uploaddir.$file_name);
			$data=unpack("H*hex", $datastring);		
			
			$sql = "INSERT INTO wkr_ref	(	site_cd, 			audit_user, 		audit_date, 		status,					column1, 		 
											FILE_NAME, 			type, 				mst_rowid, 			attachment,				mbl_audit_user,	mbl_audit_date) 
								VALUES (	'".$site_cd."',		'".$EMPID."', 		getdate(),			'Saved', 		'		Native', 		
											'".$file_name."',	'A', 				".$rowid.", 		0x".$data['hex'].",		'".$LOGINID."',	getdate()) SELECT SCOPE_IDENTITY() as rowid";
				
	
			$stmt = sqlsrv_query( $conn, $sql);				
							
			if( !$stmt ) {
				$error_message = "Error insert table (wkr_ref)";
				returnError($error_message);
				die( print_r( sqlsrv_errors(), true));
			}else{
				unlink($fullPathwithfileName);
			}

			$json_wkr_ref = array();
			do {
				while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
					$json_wkr_ref['rowid'] = $row['rowid'];
					$json_wkr_ref['action'] = "INSERT";
					array_push($json_return2, $json_wkr_ref);
					
				}
			} while ( sqlsrv_next_result($stmt) );		
		
		
		}
	}
		
	$json_return['wkr_ref'] = $json_return2;	
	
}
		
if ($valid) {
	//sqlsrv_free_stmt( $stmt);
	sqlsrv_close( $conn);	
	
	//Declare NULL Array since no records inserted, in future will insert as wko_ref
	//$json = array();
	
	returnData($json_return);	
}

function insertImage($image){

}

function returnData($json_return){
	$returnData = array(
	'status' => 'SUCCESS',
	'message' => 'Work Request Attachment Upload Successfully',
	'data' => $json_return);
	
	echo json_encode($returnData);
}

function returnError($error_message){
	$json = array();
	
	$returnData = array(
	'status' => 'ERROR',
	'message' => $error_message,
	'data' => $json);
	
	echo json_encode($returnData);
	
	sqlsrv_free_stmt( $stmt);
	sqlsrv_close( $conn);	
		
	exit();
}


//Upload MultipleFile
//https://www.php.net/manual/en/features.file-upload.post-method.php
// foreach ($_FILES["pictures"]["error"] as $key => $error) {
    // if ($error == UPLOAD_ERR_OK) {
        // $tmp_name = $_FILES["pictures"]["tmp_name"][$key];
        // // basename() may prevent filesystem traversal attacks;
        // // further validation/sanitation of the filename may be appropriate
        // $name = basename($_FILES["pictures"]["name"][$key]);
        // move_uploaded_file($tmp_name, "data/$name");
    // }
// }

?>