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

if (isset($_FILES['files']) && isset($_FILES['video']) && isset($_FILES['thumbnail'])) {
	if ($_POST['APIName'] != "" && $_POST['software'] != "") {
		$APIName = $_POST['APIName'];
		$foldername = '../../assets/API/Universal/' . $_POST['software'] . '/' . $_POST['APIName'];
		if (!is_dir($foldername)) mkdir($foldername);
		for ($count = 0; $count < count($_FILES['files']['name']); $count++) {
			if ($_FILES['files']['name'][$count] != $_FILES['thumbnail']['name'] && $_FILES['files']['name'][$count] != $_FILES['video']['name']) {
				move_uploaded_file($_FILES['files']['tmp_name'][$count], $foldername . '/' . $_FILES['files']['name'][$count]);
			}
		}
		$thumbnail_path = $foldername . '/' . $_FILES['thumbnail']['name'];
		$ext = pathinfo($_FILES['video']['name'], PATHINFO_EXTENSION);
		move_uploaded_file($_FILES['video']['tmp_name'], $foldername . '/' . $APIName . "." . $ext);
		move_uploaded_file($_FILES['thumbnail']['tmp_name'], $thumbnail_path);
		imagepng(imagecreatefromstring(file_get_contents($thumbnail_path)), $foldername . '/' . $APIName . ".png");	//轉成 api名稱.png
		unlink($thumbnail_path);	//刪除原始檔案

		$placeholder = "?";
		$count = 0;
		foreach ($_POST as $key => $value) {
			if ($key != "") {
				array_push($keys, "[" . htmlspecialchars($key) . "]");
				array_push($values, htmlspecialchars($value));
				$count++;
			}
		}
		array_push($values, $_SESSION['UserID']); //將 [uploaderID] 放入
		$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 . ",[uploaderID]
			)
	  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";
