<?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);
	$folder			= $json->data->folder;
	$dvc_id			= $json->data->dvc_id;


	$uploaddir = "C:\\wamp64\\www\\".$folder."\\temp_".$dvc_id."\\";
	if (!is_dir($uploaddir)) {
		mkdir($uploaddir, 0777, true);
		mkdir($uploaddir."\\thumbnail\\", 0777, true);
	}
	
	for ($x = 1; $x <= $count; $x++) {
		
		
		$file_name_with_rowid = $_FILES['file_'.$x]['name'];		
		$parts = explode('$', $file_name_with_rowid);	
		$file_name = $parts[0]; // This will give you the actual file name
		$rowid = $parts[1];
	
		
		$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);
				
			
				
				if (count($data) > 0){
					
					$sql= "UPDATE		wko_isp 
							SET			photo_file_name  = '".$file_name."',
										photo_attachment =  0x".$data['hex']."							
							WHERE		rowid = '".$rowid."'";

					$stmt = sqlsrv_query( $conn, $sql);

					if( !$stmt ) {
						 $error_message = "Error selecting table JPG (tkn_mst)";
						 returnError($error_message);
						 die( print_r( sqlsrv_errors(), true));
					}


					
				}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);
			}
		
	}
	

$json_return['wko_ref'] = $json_return2;
	
}
		
if ($valid) {
	
	sqlsrv_free_stmt( $stmt);
	sqlsrv_close( $conn);		
	returnData($json_return);	
}



function returnData($json_return){
	$returnData = array(
	'status' => 'SUCCESS',
	'message' => 'Check List Image 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();
}


?>