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

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



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;	
	
	//echo $count;
	
	 for ($x = 1; $x <= $count; $x++) {
		 
		 $file_name = $_FILES['file_'.$x]['name'];		 
			
			
		if (strpos($file_name, '.png') !== false) {				
				
				if($x == 1){
					
					$type = "P";
				}else{
					$type = "A";
				}
				
			$file_name = str_replace(".png",".jpg",$file_name);
			$image = imagecreatefrompng($uploaddir.$_FILES['file_'.$x]['name']);
			imagejpeg($image, $uploaddir.$file_name, 100);

			$sql = "INSERT INTO wko_ref(
				site_cd, 		audit_user, 		audit_date, 		status,			column1, 
				FILE_NAME, 		type, 				mst_rowid, 			attachment) 
				VALUES 
				('".$site_cd."',		'".$EMPID."', 			getdate(),			'Saved', 		'Native', 
				'".$file_name."','".$type."', 				".$rowid.", 		0x".$data['hex'].") 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) );	
			
			imagedestroy($image);
			
			unlink($uploaddir.$_FILES['file_'.$x]['name']);
				
				 
		}else{
				
				if($x == 1){
					
					$type = "P";
				}else{
					$type = "A";
				}
				
			$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 wko_ref(
					site_cd, 		audit_user, 		audit_date, 		status,			column1, 
					FILE_NAME, 		type, 				mst_rowid, 			attachment) 
					VALUES 
					('".$site_cd."',		'".$EMPID."', 			getdate(),			'Saved', 		'Native', 
					'".$file_name."','".$type."', 				".$rowid.", 		0x".$data['hex'].") 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;	
	
}


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){
	$returnData = array(
	'status' => 'SUCCESS',
	'message' => 'Work Order Attachment Upload Successfully',
	'data' => $json);
	
	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();
}
		


?>