<?php
include("connectSQL_Component.php");
$keys = [];
$values = [];
$APIName = "";

if (isset($_FILES['files'])) {
	if ($_POST['APIName'] != "" && $_POST['software'] != "") {
		$APIName = $_POST['APIName'];
		$foldername = '../../上傳測試/' . $_POST['software'] . '/' . $_POST['APIName'];
		if (!is_dir($foldername)) mkdir($foldername);
		for ($count = 0; $count < count($_FILES['files']['name']); $count++) {
			move_uploaded_file($_FILES['files']['tmp_name'][$count], $foldername . '/' . $_FILES['files']['name'][$count]);
		}
		$placeholder = "?";
		$count = 0;
		foreach ($_POST as $key => $value) {
			if ($key != "") {
				array_push($keys, "[" . htmlspecialchars($key) . "]");
				array_push($values, htmlspecialchars($value));
				$count++;
			}
		}
		$placeholder = $placeholder . str_repeat(",?", $count - 1);
		$params = implode(",", $keys);
		$sql =  "IF NOT EXISTS (SELECT [APIName] FROM [API_Table] WHERE [APIName] = '{$_POST["APIName"]}')
            BEGIN
			INSERT INTO [API_Table]
			(
				" . $params . "
			)
	  VALUES
			(" . $placeholder  . ");
			END";
		$stmt = sqlsrv_query($conn, $sql, $values);

		if ($stmt === false) {
			if (($errors = sqlsrv_errors()) != null) {
				foreach ($errors as $error) {
					echo "SQLSTATE: " . $error['SQLSTATE'] . "<br />";
					echo "code: " . $error['code'] . "<br />";
					echo "message: " . $error['message'] . "<br />";
				}
			}
		} else {
			include("api_video_tool.php");
		}
	} else
		echo "Upload folder name is empty";
} else
	echo "Upload files is empty";
