<?php

	include '../autoload.php';

	$result 			= "";
	$final_filename 	= "";

	if ($_SERVER['REQUEST_METHOD'] == 'POST') 
	{
		if (isset($_FILES['file']) && $_FILES['file']['error'] == 0) 
		{
			$uploads_dir 	= $GLOBALS["upload_folder"];
			$tmp_name 		= $_FILES['file']['tmp_name'];

			$name 			= basename($_FILES['file']['name']);

			// $upload_file 	= "$uploads_dir/$name";
			$final_filename = date('YmdHis')."_".$name;
			$upload_file 	= $uploads_dir."/".$final_filename;

			// Vérifie si le dossier existe, sinon le crée
			if (!is_dir($uploads_dir)) 
			{
				mkdir($uploads_dir, 0777, true);
			}

			// Déplace le fichier téléchargé

			if (move_uploaded_file ( $tmp_name, $upload_file)) 
			{
				error_log ( "tmp_name : " .$tmp_name );
				error_log ( "upload_file : " .$upload_file );
				
				$result = "OK";
			} 
			else 
			{
				$result = "ERROR_0";
			}
		}	 
		else 
		{
			$result = "ERROR_1";
		}
	} 
	else 
	{
		$result ="ERROR_2";
	}

	$arr = array (
			"result"            => $result,
			"filename"			=> $final_filename
	);

	header('Content-type: application/json');
	
	$result = json_encode ( $arr );

	echo $result;
?>