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


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

$mst_RowID;

$maxsize = 5242880; // 5MB


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

	$count    	   	= $_REQUEST["count"];
	$rowid			= $_REQUEST["rowid"];
	$site_cd		= $_REQUEST["site_cd"];
	$EMPID			= $_REQUEST["EMPID"];
	$folder			= $_REQUEST["folder"];
	$LOGINID		= $_REQUEST["LOGINID"];
	$dvc_id			= $_REQUEST["dvc_id"];
	
	$currentDateTime = date('YYY-mm-dd HH:mm');
	
	f_logging('', "update_asset_image.php", 'https://evantage-cmms.com.my/mobile_train', $LOGINID, '0', $currentDateTime, $site_cd);
	
	$uploaddir = "C:\\wamp64\\www\\".$folder."\\temp_".$dvc_id."\\";
	
	if (!is_dir($uploaddir)) {
		mkdir($uploaddir, 0777, true);
		mkdir($uploaddir."\\thumbnail\\", 0777, true);
	}
	
	$sql = "select total = 	count(*) from ast_mst (NOLOCK) , ast_ref (NOLOCK)  
							where ast_mst.site_cd = ast_ref.site_cd
							and ast_mst.rowid= ast_ref.mst_rowid 
							and ast_ref.type = 'P' 
							and ast_mst.RowID = '".$rowid."'";	
		
	$stmt = sqlsrv_query( $conn, $sql);	
			
	if( !$stmt ) {
		$error_message = "Error selecting table (ast_mst, ast_ref)";
		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) {
			
			
			$imageObject = $_FILES['file_'.$x]['tmp_name'];	
			$fullPathwithfileName = $uploaddir.$file_name;
			
			if(move_uploaded_file($imageObject, $fullPathwithfileName)){
				
				$datastring= file_get_contents($fullPathwithfileName);
				$data=unpack("H*hex", $datastring);
				if (count($data) > 0){
					
					$sql = "INSERT INTO ast_ref	(	site_cd, 			audit_user, 		audit_date, 		status,					column1, 
													FILE_NAME, 			type, 				mst_rowid, 			attachment,				mbl_audit_user,	
													mbl_audit_date,		column2) 
										VALUES 	(	'".$site_cd."',		'".$EMPID."', 		getdate(),			'Saved', 				'Native', 
													'".$file_name."',	'".$types."', 		".$rowid.", 		0x".$data['hex'].",	'".$LOGINID."',	
													getdate(),			'".$file_type."') SELECT SCOPE_IDENTITY() as rowid";


					$stmt = sqlsrv_query( $conn, $sql);				
									
					if( !$stmt ) {
						$error_message = "Error insert table (ast_ref)";
						returnError($error_message);
						die( print_r( sqlsrv_errors(), true));
					}else{
						unlink($fullPathwithfileName);
					}

					$json_ast_ref = array();
					do {
						while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
							$json_ast_ref['rowid'] = $row['rowid'];
							$json_ast_ref['action'] = "INSERT";
							array_push($json_return2, $json_ast_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, '.jpg') !== false){
			
			$imageObject = $_FILES['file_'.$x]['tmp_name'];			
			$fullPathwithfileName = $uploaddir.$file_name;
			f_logging('', "update_asset_image.php", 'https://evantage-cmms.com.my/mobile_train', $LOGINID, '1', $currentDateTime, $site_cd);
			if (move_uploaded_file($imageObject, $fullPathwithfileName)){
				f_logging('', "update_asset_image.php", 'https://evantage-cmms.com.my/mobile_train', $LOGINID, '2', $currentDateTime, $site_cd);
				$datastring= file_get_contents($fullPathwithfileName);
				$data=unpack("H*hex", $datastring);
				
				
					$sql = "INSERT INTO ast_ref	(	site_cd, 			audit_user, 		audit_date, 		status,							column1, 
													FILE_NAME, 			type, 				mst_rowid, 			attachment,						mbl_audit_user,	
													mbl_audit_date,		column2) 
										VALUES 	(	'".$site_cd."',		'".$EMPID."', 		getdate(),			'Saved', 						'Native', 
													'".$file_name."',	'".$types."', 		".$rowid.", 		0x".$data['hex'].",				'".$LOGINID."',
													getdate(),			'".$file_type."') SELECT SCOPE_IDENTITY() as rowid";
					
					$stmt = sqlsrv_query( $conn, $sql);				
									
					if( !$stmt ) {
						// $error_message = "Error insert table (ast_ref), image number ".$x;
						// returnError($error_message);
						// die( print_r( sqlsrv_errors(), true));
						$json_ast_ref['rowid'] = 0;
						$json_ast_ref['action'] = "Error insert table (ast_ref) for image file (".$file_name.")";
						array_push($json_return2, $json_ast_ref);
					}else{
						//unlink($fullPathwithfileName);
					}

					$json_ast_ref = array();
					do {
						while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
							$json_ast_ref['rowid'] = $row['rowid'];
							$json_ast_ref['action'] = "INSERT";
							array_push($json_return2, $json_ast_ref);
							
						}
				   } while ( sqlsrv_next_result($stmt) );
				
			}else{
				f_logging('', "update_asset_image.php", 'https://evantage-cmms.com.my/mobile_train', $LOGINID, '3', $currentDateTime, $site_cd);
				$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, '.JPEG') !== false){
			
			$imageObject = $_FILES['file_'.$x]['tmp_name'];			
			$fullPathwithfileName = $uploaddir.$file_name;
			if (move_uploaded_file($imageObject, $fullPathwithfileName)){
				
				$datastring= file_get_contents($fullPathwithfileName);
				$data=unpack("H*hex", $datastring);
				
				if (count($data) > 0){
					
					$sql = "INSERT INTO ast_ref	(	site_cd, 			audit_user, 		audit_date, 		status,							column1, 
													FILE_NAME, 			type, 				mst_rowid, 			attachment,						mbl_audit_user,
													mbl_audit_date,		column2) 
										VALUES 	(	'".$site_cd."',		'".$EMPID."', 		getdate(),			'Saved', 						'Native', 
													'".$file_name."',	'".$types."', 		".$rowid.", 		0x".$data['hex'].",				'".$LOGINID."',	
													getdate(),			'".$file_type."') SELECT SCOPE_IDENTITY() as rowid";
					
					$stmt = sqlsrv_query( $conn, $sql);				
									
					if( !$stmt ) {
						// $error_message = "Error insert table (ast_ref), image number ".$x;
						// returnError($error_message);
						// die( print_r( sqlsrv_errors(), true));
						$json_ast_ref['rowid'] = 0;
						$json_ast_ref['action'] = "Error insert table (ast_ref) for image file (".$file_name.")";
						array_push($json_return2, $json_ast_ref);
					}else{
						//unlink($fullPathwithfileName);
					}

					$json_ast_ref = array();
					do {
						while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC)) {
							$json_ast_ref['rowid'] = $row['rowid'];
							$json_ast_ref['action'] = "INSERT";
							array_push($json_return2, $json_ast_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) {
			
		}else if (strpos($file_name, '.pdf') !== false) {
			
		}
	}
	
	$json_return['ast_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();
	//echo $json_return;
	returnData($json_return);	
}

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_free_stmt( $stmt);
	sqlsrv_close( $conn);	
		
	exit();
}

?>