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

//$uploaddir = "C:\\wamp64\\www\\CMMS_Standard\\temp\\";
$uploaddir;
$error_message;
$valid = true;
$json_return = array();
$json_return2 = array();
$json_return = [];

$mst_RowID;


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;
	$LOGINID		= $json->data->LOGINID;
	$folder			= $json->data->folder;
	$dvc_id			= $json->data->dvc_id;
	
	
	$uploaddir = "C:\\wamp64\\www\\".$folder."\\mobile_image_temp\\temp_" .$LOGINID."_".$dvc_id ."\\";

    if (!is_dir($uploaddir)) {
        mkdir($uploaddir, 0777, true);
        mkdir($uploaddir . "\\thumbnail\\", 0777, true);
    }
	
	
$sql = "SELECT mst_RowID From wko_ref WHERE site_cd = '".$site_cd."' AND mst_RowID = ".$rowid." AND type = 'A' AND column2 = 'SIGN'";	

$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)) {
	 
	 $mst_RowID = $row['mst_RowID'];	 
	 	 
   }
} while ( sqlsrv_next_result($stmt));
	
	if(empty($mst_RowID)){
		
		//echo 'insert';
		
		for ($x = 1; $x <= $count; $x++) {
		
		$file_name = $_FILES['file_'.$x]['name'];
		
		if (strpos($file_name, '.png') !== false) {
			
			
			$file_name = str_replace(".png",".jpg",$file_name);
			$imageObject = $_FILES['file_'.$x]['tmp_name'];	
			$imageObject = imagecreatefrompng($imageObject);
			imagejpeg($imageObject, $uploaddir.$file_name, 100);
			$fullPathwithfileName = $uploaddir.$file_name;
			
				//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 wko_ref	(	site_cd, 				audit_user, 			audit_date, 		status,					column1, 		column2, 
											FILE_NAME, 				type, 					mst_rowid, 			attachment,				mbl_audit_user,	mbl_audit_date) 
								VALUES 	(	'".$site_cd."',			'".$LOGINID."', 			getdate(),			'Saved', 				'Native', 		'SIGN', 
											'".$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 (wko_ref)";
				returnError($error_message);
				die( print_r( sqlsrv_errors(), true));
			}else{
				unlink($fullPathwithfileName);
			}

			$json_wko_ref = array();
			do {
				while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
					$json_wko_ref['rowid'] = $row['rowid'];
					$json_wko_ref['action'] = "INSERT";
					array_push($json_return2, $json_wko_ref);
					
				}
			} while ( sqlsrv_next_result($stmt) );	
			
			
		}else{
			
			
			
			$imageObject = $_FILES['file_'.$x]['tmp_name'];			
			$fullPathwithfileName = $uploaddir.$file_name;
			
			
			//$imageObject = imagecreatefromjpeg($exportFullPathFileName);
			//Check if file upload successfully
			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";
				}
			# Add some error handling

			if (!empty($exif['Orientation'])) {
				# Get orientation
				
				$orientation = $exif['Orientation'];          
				//echo $orientation;
			}else{
				$orientation = 0 ;
				//echo "0";
			}
		
			# Manipulate image
			switch ($orientation) {
				case 2:
					imageflip($imageObject, IMG_FLIP_HORIZONTAL);
					break;
				case 3:
					$imageObject = imagerotate($imageObject, 180, 0);
					break;
				case 4:
					imageflip($imageObject, IMG_FLIP_VERTICAL);
					break;
				case 5:
					$imageObject = imagerotate($imageObject, -90, 0);
					imageflip($imageObject, IMG_FLIP_HORIZONTAL);
					break;
				case 6:
					$imageObject = imagerotate(load_image($fullPathwithfileName, $type), -90, 0);
					break;
				case 7:
					$imageObject = imagerotate($imageObject, 90, 0);
					imageflip($imageObject, IMG_FLIP_HORIZONTAL);
					break;
				case 8:
					$imageObject = imagerotate($imageObject, 90, 0); 
					break;
			}
			
			save_image($imageObject, $fullPathwithfileName, 'jpeg', 100);
			# Write image
			//imagejpeg($imageObject, $fullPathwithfileName, 100);
			
				$datastring= file_get_contents($fullPathwithfileName);
				$data=unpack("H*hex", $datastring);
		
			$sql = "INSERT INTO wko_ref	(	site_cd, 				audit_user, 			audit_date, 		status,					column1, 		column2, 
											FILE_NAME, 				type, 					mst_rowid, 			attachment,				mbl_audit_user,	mbl_audit_date) 
								VALUES 	(	'".$site_cd."',			'".$EMPID."', 			getdate(),			'Saved', 				'Native', 		'SIGN', 
											'".$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 (wko_ref)";
				returnError($error_message);
				die( print_r( sqlsrv_errors(), true));
			}else{
				unlink($fullPathwithfileName);
			}

			$json_wko_ref = array();
			do {
				while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
					$json_wko_ref['rowid'] = $row['rowid'];
					$json_wko_ref['action'] = "INSERT";
					array_push($json_return2, $json_wko_ref);
				 	
				}
		   } while ( sqlsrv_next_result($stmt) );		
		   
		}
	}

		$json_return['wko_ref'] = $json_return2;
		
		
}
		
	}else{
		//update
		
		for ($x = 1; $x <= $count; $x++) {
			
			$file_name = $_FILES['file_'.$x]['name'];
			
			$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);
			
			//echo $$data ."<br>";
			
			$image_path ="0x".$data['hex']."";
				//echo $image_path;
				
			

			
			$sql ="UPDATE 	wko_ref 
					SET  		
							attachment=0x".$data['hex'].",
							audit_user=?,
							audit_date=getdate(),	
							mbl_audit_user=?,	
							mbl_audit_date=getdate() 														
					where 	site_cd=? 
					and  	mst_rowid =? 
					and 	column2 =?  
					and 	type =? "; 
			
			$params = array($LOGINID,$LOGINID,$site_cd,$rowid,'SIGN','A');					
			
		
			$stmt_wko_ref = sqlsrv_query( $conn, $sql,$params);			
		
			if( !$stmt_wko_ref ) {
				print_r( sqlsrv_errors(), true);
				
				$error_message = "Error update table (UPDATE wko_ref 123)";
				returnError($error_message);
				die( print_r( sqlsrv_errors(), true));
			}
			
			$json_wko_ref = array();
			do {
				while ($row = sqlsrv_fetch_array($stmt_wko_ref, SQLSRV_FETCH_ASSOC)) {
					$json_wko_ref['rowid'] = $row['rowid'];
					$json_wko_ref['action'] = "INSERT";
					array_push($json_return2, $json_wko_ref);
				 	
				}
		   } while ( sqlsrv_next_result($stmt_wko_ref) );	
			
			
		
			
			
			
		
		}
		
	}	
	
}
		
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' => '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_close( $conn);	
		
	exit();
}


?>