<?php
ini_set("display_errors", 1);
ini_set("error_reporting", 1);

$supplierInventory = isset($_POST['supplierInventory']) ? $_POST['supplierInventory'] : "";
$encData = isset($_POST['encData']) ? $_POST['encData'] : "";
$empNo = isset($_POST['empNo']) ? $_POST['empNo'] : "";
$file_name = isset($_POST['file_name']) ? $_POST['file_name'] : "";
	
$dsn = "sqlsrv:server=localhost;Database=tok;";
$username = "SYSDBA";
$password = "masterkey";
$pdo = new PDO($dsn, $username, $password);

//產生 UUID
function createUUID(){
	return sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
		mt_rand(0, 0xffff), mt_rand(0, 0xffff),
		mt_rand(0, 0xffff),
		mt_rand(0, 0x0fff) | 0x4000,
		mt_rand(0, 0x3fff) | 0x8000,
		mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff)
	);
}

//寫入傳送紀錄
function saveUpload($file_name="", $encData="", $supplierInventory="", $empNo="", $pdo=null){
	try{
		$sql = "
			SET ANSI_WARNINGS OFF;
			INSERT INTO [tok].[dbo].[UPLOADDATA]([ERI], [FILE_NAME], [ENCDATA], [SUPPLIERINVENTORY], [USER_ID], [CREATE_TIME])
			VALUES(dbo.SOPHIAERI('UPLOADDATA'), '".$file_name."', '".$encData."', '".$supplierInventory."', '".$empNo."', '".date("Y-m-d H:i:s")."')
		";
		$query = $pdo->prepare($sql);
		$query->execute();
	}catch(PDOException $e){
		echo json_encode(array("msg"=>$e->getMessage()));
	}
	/*
	$uploadFolder = "./files/json/";
	$contentJSON = file_get_contents($uploadFolder."uploadData.json");
	$exportJSON = $uploadFolder."uploadData.json";
	
	$array = array();
	foreach($contentJSON as $value){
		$array[] = array(
			"id" => $value->id,
			"encData" => $value->encData,
			"supplierInventory" => $value->supplierInventory,
			"create_time" => $value->create_time
		);
	}
	
	$newArray = array(
		"id" => createUUID(),
		"encData" => $encData,
		"supplierInventory" => $supplierInventory,
		"create_time" => date("Y-m-d H:i:s")
	);
	array_push($array, $newArray);
	
	//複製一份備份
	copy($exportJSON, $uploadFolder."uploadDataBk.json");
	
	//寫回檔案中
	$exportFile = fopen($exportJSON, "w");
	$result = fwrite($exportFile, json_encode($array, JSON_UNESCAPED_UNICODE));
	fclose($exportFile);
	*/
}

//寫入回傳訊息
function saveResponse($file_name="", $response="", $empNo="", $pdo=null){
	try{
		$sql = "
			SET ANSI_WARNINGS OFF;
			INSERT INTO [tok].[dbo].[RESPONSEDATA]([ERI], [FILE_NAME], [CONTENTS], [USER_ID], [CREATE_TIME])
			VALUES(dbo.SOPHIAERI('RESPONSEDATA'), '".$file_name."', '".$response."', '".$empNo."', '".date("Y-m-d H:i:s")."')
		";
		$query = $pdo->prepare($sql);
		$query->execute();
	}catch(PDOException $e){
		echo json_encode(array("msg"=>$e->getMessage()));
	}
	/*
	$uploadFolder = "./files/json/";
	$contentJSON = file_get_contents($uploadFolder."responseData.json");
	$exportJSON = $uploadFolder."responseData.json";
	
	$array = array();
	foreach($contentJSON as $value){
		$array[] = array(
			"id" => $value->id,
			"response" => $value->response,
			"create_time" => $value->create_time
		);
	}
	
	$newArray = array(
		"id" => createUUID(),
		"response" => $data,
		"create_time" => date("Y-m-d H:i:s")
	);
	array_push($array, $newArray);
	
	//複製一份備份
	copy($exportJSON, $uploadFolder."responseDataBk.json");
	
	//寫回檔案中
	$exportFile = fopen($exportJSON, "w");
	$result = fwrite($exportFile, json_encode($array, JSON_UNESCAPED_UNICODE));
	fclose($exportFile);
	*/
}

$array = array(
	"encData" => $encData,
	"supplierInventory" => json_decode($supplierInventory, true)
	//"supplierInventory" => $supplierInventory
);

if(htmlspecialchars($_POST['action'])=="import"){
	//背景傳送資料
	$ch = curl_init();
	$curl_array = array(
		CURLOPT_HTTPAUTH => CURLAUTH_BASIC,
		CURLOPT_RETURNTRANSFER => 1,
		CURLOPT_CONNECTTIMEOUT => 30,
		CURLOPT_ENCODING => "",
		CURLOPT_MAXREDIRS => 10,
		CURLOPT_SSL_VERIFYPEER => 0,
		CURLOPT_SSL_VERIFYHOST => 0,
		CURLOPT_CUSTOMREQUEST => "POST",
		CURLOPT_POSTFIELDS => json_encode($array, JSON_UNESCAPED_SLASHES),
		CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
		CURLOPT_HTTPHEADER => array("content-type: application/json"),
		
		//測試區連結
		//CURLOPT_URL => "https://soldmzuat.tsmc.com.tw/b2b-service/CaRestService/updateInventory"
		
		//正式區連結
		CURLOPT_URL => "https://supply2.tsmc.com.tw/b2b-service/CaRestService/updateInventory"
	);
	curl_setopt_array($ch, $curl_array);
	$response = curl_exec($ch);
	curl_close($ch);
	
	//$response = '{"returnCode":"S", "returnMsg":""}';
	//$errorJSON = '{"timestamp":"2021-12-10T08:13:08.707+00:00","status":400,"error":"Bad Request","message":"","path":"/b2b-service/CaRestService/updateInventory"}';
	$response = json_decode($response);
	if($response->status==400){
		saveResponse($file_name, $response->msg, $empNo, $pdo);
		echo json_encode(array("msg"=>$response->msg), JSON_UNESCAPED_UNICODE);
		return;
	}elseif($response->returnCode=="S"){
		saveUpload($file_name, $encData, $supplierInventory, $empNo, $pdo);
		saveResponse($file_name, $response->returnMsg, $empNo, $pdo);
		echo json_encode(array("success"=>true));
		return;
	}else{
		saveResponse($file_name, $response->returnMsg, $empNo, $pdo);
		echo json_encode(array("msg"=>$response->returnMsg), JSON_UNESCAPED_UNICODE);
		return;
	}
}else{
	echo json_encode(array("msg"=>"參數錯誤！"), JSON_UNESCAPED_UNICODE);
	return;
}