<?php

class FileUpload{

        function random_string($length) {
		    $key = '';
		    $keys = array_merge(range(0, 9), range('A', 'Z'));

		    for ($i = 0; $i < $length; $i++) {
		        $key .= $keys[array_rand($keys)];
		    }

		    return $key;
        }
        

        function file_upload($dir, $fileName){
            //create file directories

            if (!file_exists('./../src/web/uploads/documents')) {
                mkdir('./../src/web/uploads/documents', 0777, true);
            }
            
            //multiple fileupload


            $file_array = $_FILES[$fileName]["name"];

			$array_ret = array();
			

			if(is_array($file_array)){
				for($i=0;$i<sizeof($file_array);$i++){
					$file_path = $this->upload_one($dir, $_FILES[$fileName]["name"][$i], $_FILES[$fileName]["tmp_name"][$i], $_FILES[$fileName]["size"][$i]);
					array_push($array_ret,$file_path);
				}
			}else{
				$file_path = $this->upload_one($dir, $_FILES[$fileName]["name"], $_FILES[$fileName]["tmp_name"], $_FILES[$fileName]["size"]);
				array_push($array_ret,$file_path);
			}


			return json_encode($array_ret);

			
			
			
			

        }
        

        function upload_one($dir, $file_arr,$tmp_name, $size){
            $temp = explode(".", $file_arr);
			$temp=str_replace("..",".",$temp);
            $newfilename = 'file_'.$this->random_string(20).'.'.end($temp);

			$target_dir = $dir;
			$target_file = $target_dir . basename($file_arr);
			$uploadOk = 1;
			$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
			
			if (file_exists($target_file)) {
			    $uploadOk = 0;
			}
			
			if ($size > 500000000) {
			    $uploadOk = 0;
			}
			
			if ($uploadOk == 0) {
			    echo "sorry";
            
            // if everything is ok, try to upload file
			} else {
			    if (move_uploaded_file($tmp_name, $target_dir . $newfilename)) {

			        return $newfilename;

			    } else {

			        return $uploadok;
                }     
                
			}
		}
		

		function file_delete($dir, $filename){

			$filename=str_replace("..",".",$filename);

			if (file_exists($dir.$filename)) {
				unlink($dir.$filename);
				return "done";
            }else{
				return "notdone";
			}
		}
}