<?php header('Access-Control-Allow-Origin: *'); ?>
<?php
$fail = [];
$success = [];
$data = [];
if (count($_FILES)>0 && is_array($_FILES['files']['tmp_name'])){
    for($key = 0; $key < count($_FILES['files']['tmp_name']); $key++) {
        $target_dir = $_POST['dir'];
        $imageFileType = strtolower(pathinfo(basename($_FILES['files']["name"][$key]), PATHINFO_EXTENSION));
        $target_file = $target_dir . $_POST['uuid'][$key] . '.' . $imageFileType;
        $uploadOk = 1;

        // Check if image file is a actual image or fake image
        /*
        $check = getimagesize($_FILES['files']["tmp_name"][$key]);
        if($check !== false) {
            array_push($fail, "File is an image - " . $check["mime"] . ".");
            $uploadOk = 1;
        }
        else {
            array_push($fail, "File is not an image.");
            $uploadOk = 0;
        }
        */
        // Check if file already exists
        if(file_exists($target_file)) {
            array_push($fail, "File exists: ". basename($_FILES['files']["name"][$key]));
            $uploadOk = 0;
            continue;
        }

        // Check file size
        // The default PHP values are 2 MB for upload_max_filesize, and 8 MB for post_max_size
        if($_FILES['files']["size"][$key] > 5 * 1024 * 1024) {
            array_push($fail, "Exceed 5 MB size: ". basename($_FILES['files']["name"][$key]));
            $uploadOk = 0;
            continue;
        }

        // Allow certain file formats
        // if($imageFileType != "svg" && $imageFileType != "jpg" && $imageFileType != "png" && $imageFileType != "jpeg" && $imageFileType != "gif" && $imageFileType != "mp4") {
        //     array_push($fail, "Sorry, only JPG, JPEG, PNG & GIF files are allowed.");
        //     $uploadOk = 0;
        //     continue;
        // }

        // Check if dir exists
        if(!is_dir($target_dir)){
            array_push($fail, "Path does not exist: " . $target_dir);
            $uploadOk = 0;
            continue;
        }

        // Check if $uploadOk is set to 0 by an error
        if ($uploadOk == 0) {
            array_push($fail, "Fail to upload: ". basename($_FILES['files']["name"][$key]));
        // if everything is ok, try to upload file
        } else {
            if (move_uploaded_file($_FILES['files']["tmp_name"][$key], $target_file)) {
                // array_push($fail, "The file ". $target_file. " has been uploaded.");
                // array_push($fail, 'success');
                array_push($data, [ "url" => $_POST['path'] . $target_file ]);
            } else {
                array_push($fail, "Fail to upload: ". basename($_FILES['files']["name"][$key]));
            }
        }
    }    
} else {
    array_push($fail, 'Cannot find any files');
}
// echo json_encode(['data' => $data, 'output' => $output, 'post' => $_POST, 'files' => $_FILES]);
echo json_encode(['data' => $data, 'fail' => $fail]);
?>