<?php
//var_dump($_POST);
//exit;



ini_set("memory_limit","2048M");
ini_set("upload_max_filesize","3000M");
ini_set("post_max_size","3000M");
ini_set("max_execution_time","0");
ini_set("max_input_time","0");

if(isset($_FILES["txt_suppression_file"]["type"]) and isset($_POST['cbx_offer']) and isset($_POST['cbx_suppression_type']))
{
	$offer_id			=	$_POST['cbx_offer'];
	$validextensions 	=	array("txt");
	$temporary 			=	explode(".", $_FILES["txt_suppression_file"]["name"]);
	$file_extension 	=	end($temporary);

	if ((in_array($file_extension, $validextensions)) and ($_FILES["txt_suppression_file"]["type"] == "text/plain")) 
	{
		if ($_FILES["txt_suppression_file"]["error"] > 0)
		{
			echo "Return Code: " . $_FILES["txt_suppression_file"]["error"] . "<br/><br/>";
		}
		else
		{
			$sourcePath =	$_FILES['txt_suppression_file']['tmp_name'];
			$targetPath = 	"./downloads/list";
			$targetPath2 = 	"/home/suppression/offer/".$offer_id.'/list';
			
			deleteAllExistingFiles('./downloads/');
			if(move_uploaded_file($sourcePath,$targetPath))
			{
				$isMD5DuppressionFile	=	($_POST['cbx_suppression_type'] == 'md5')?true:false;
				if($isMD5DuppressionFile)
				{
					
					//Déplacement :
					copy($targetPath, $targetPath2);
					
					//Retourner un resultat :
					echo 'vaut : -->'.$isMD5DuppressionFile.'<----\n\nSuppression file uploaded successfully !';
				}
				else
				{
					//Cryptage du fichier :
					textToMD5($targetPath,$targetPath2,$offer_id);
					
					//Retourner un resultat :
					echo 'File was Crypted successfully \n\n\n\n Suppression file uploaded successfully !';
				}
			}
			else
			{
				echo 'An error was encountered while uploading the suppression file. \n\nPlease retry later or contact your system administrator';
			}
		}
	}
	else
	{
		echo 'The extension of the uploaded file is not permited !';
	}
}
else
{
	echo 'txt_suppression_file NOT SET';
}

function deleteAllExistingFiles($p_folder)
{
	$directory 			=	$p_folder;
	$tab_files 			=	array_diff(scandir($directory), array('..', '.'));
	foreach($tab_files as $file):
		unlink($p_folder.'/'.$file);
	endforeach;
}

function textToMD5($p_source_file,$p_target_file,$p_offerId)
{
	//Supprimer le fichier destination s'il existe :
	deleteAllExistingFiles('/home/suppression/offer/'.$p_offerId.'/');
	
	//Crypter le fichier en MD5 : ligne par ligne :
	$source	=	$p_source_file;
	$target	=	$p_target_file;
	
	$textFile	=	fopen($source, 'r');
	$md5File	=	fopen($target, 'a+');
	while (!feof($textFile)) 
	{
		$line	=	fgets($textFile);
		$line	=	md5($line).PHP_EOL;
		fwrite($md5File, $line);
	}

	fclose($textFile);
	fclose($md5File);
}

?>
