<?php
function sendResponse($status, $message) {
    header('Content-Type: application/json');
    echo json_encode(['status' => $status, 'message' => $message]);
    exit();
}
require_once("config.php");
require_once("user/protect.php");
require_once("user/user-lib.php");

if (isset($_FILES['file'])) {
    $file = $_FILES['file'];
    $fileName = $file['name'];
    $fileTmpName = $file['tmp_name'];
    $fileError = $file['error'];
    $fileType = $file['type'];
    $fileExt = explode('.', $fileName);
    $fileActualExt = strtolower(end($fileExt));
    if ($fileActualExt === "png") {
        if ($fileError === 0) {
			if (!is_dir("u_img/".$userid)){
				mkdir("u_img/".$userid);
				file_put_contents("u_img/".$userid."/index.php","<?php echo '404'; ?>");
			}
			$u_filename=$userid.uniqid().".png";
            $fileDestination = 'u_img/'.$userid."/".$u_filename;
            if (move_uploaded_file($fileTmpName, $fileDestination)) {
                sendResponse("success",$fileDestination);
            } else {
                sendResponse('error', 'There was an error moving the uploaded file.');
            }
        } else {
            sendResponse('error', 'There was an error uploading the file.');
        }
    } else {
        sendResponse('error', 'Sorry, only PNG files are allowed.');
    }
} else {
    sendResponse('error', 'No file was uploaded.');
}
?>
