<?php
include "helpers.php";

$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'] : "";

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