<?php
if(!defined('__KIMS__')) exit;

checkAdmin(0);

header('Content-Type: application/json; charset=UTF-8');
function filemanagerUploadResponse($ok, $message, $status = 200)
{
	http_response_code($status);
	echo json_encode(array('ok'=>$ok,'message'=>$message), JSON_UNESCAPED_UNICODE);
	exit;
}

$sess_Code = (string)($_POST['sess_Code'] ?? '');
$upload_dir = (string)($_POST['upload_dir'] ?? '');
$Overwrite = (string)($_POST['Overwrite'] ?? 'false');
if(!$sess_Code || !hash_equals((string)$my['admin'], $sess_Code)) filemanagerUploadResponse(false,'관리자 인증을 확인해 주세요.',403);

$uploaded = kimsq_validate_upload($_FILES['Filedata'] ?? array());
if (!$uploaded) filemanagerUploadResponse(false,'업로드 파일을 확인해 주세요.',400);

$extension = strtolower(pathinfo($uploaded['name'], PATHINFO_EXTENSION));
$allowedExtensions = array('jpg','jpeg','gif','png','webp');
$imageInfo = @getimagesize($uploaded['tmp_name']);
$allowedTypes = array(IMAGETYPE_JPEG,IMAGETYPE_GIF,IMAGETYPE_PNG,IMAGETYPE_WEBP);
if (!in_array($extension,$allowedExtensions,true) || !$imageInfo || !in_array($imageInfo[2],$allowedTypes,true)) filemanagerUploadResponse(false,'JPG, GIF, PNG, WEBP 이미지만 업로드할 수 있습니다.',400);

$rootPath = realpath($g['path_root']);
$savePath = realpath((string)$upload_dir);
if (!$rootPath || !$savePath || strpos($savePath.DIRECTORY_SEPARATOR, $rootPath.DIRECTORY_SEPARATOR) !== 0) filemanagerUploadResponse(false,'업로드 경로가 올바르지 않습니다.',400);
if (!is_writable($savePath)) filemanagerUploadResponse(false,'선택한 폴더에 파일을 저장할 권한이 없습니다.',403);

$saveFile = $savePath.DIRECTORY_SEPARATOR.$uploaded['name'];
if ($Overwrite == 'true' || !is_file($saveFile))
{
	if (!move_uploaded_file($uploaded['tmp_name'], $saveFile)) filemanagerUploadResponse(false,'파일 저장에 실패했습니다.',500);
	@chmod($saveFile, 0644);
}

filemanagerUploadResponse(true,'업로드되었습니다.');
?>
