<?php
session_start();
if(!isset($_SESSION['auth'])) {
	header("location:index.php");
}

require '../inc/PHPMailerAutoload.php';
require_once("../inc/confNetisse.php");
require_once("./functions.php");
if(WTS_ENV == 'demo'){
	require '../bornes/src/ses.php';
}
if($_SESSION["profil"] == 100){
// $msg = "";
// function send_email($email)
// {
// 	$ADRESSES = [$email];
// 	$headers ='From: "Administration des Bornes d\'orientations"<'.$MAIL_FROM.'>'."\n";
// 	$headers  = 'MIME-Version: 1.0' . "\r\n";
// 	$headers .= 'Content-type: text/html; charset=utf-8' . "\r\n";
//     $code = rand(100000000,999999999);
//     $purge_date = date('Y-m-d H:i');
//     $q = "UPDATE ca_admins SET purge_code = :purge_code, purge_date = :purge_date WHERE email = :email AND supp = :supp AND inactif = :inactif";
//     $values = [':purge_code' => $code, ':purge_date' => $purge_date, ':email' => $_SESSION["email"], ':supp' => 0, ':inactif' => 0];
//     $r = excuteQuery($q, $values);
// 	$body=  '
// 		<html xmlns="http://www.w3.org/1999/xhtml">
// 		<head>
// 		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
// 		</head>
// 		<body>
// 		<table width="100%" border="0" cellspacing="0" cellpadding="0">
// 		  <tr>
// 			<td align="center"><span style="font-family:Verdana, Geneva, sans-serif; font-size:16px; font-weight:bold;text-transform: uppercase;">'.$PROJECT_TITLE.'</span></td>
// 		  </tr>
// 		  <tr>
// 			<td align="center">&nbsp;</td>
// 		  </tr>
// 		  <tr>
// 			<td align="center" bgcolor="#fafafa">&nbsp;</td>
// 		  </tr>
// 		  <tr>
// 			<td align="center" bgcolor="#fafafa" style="font-size: 16px;">Voici votre code de vérification pour accéder au menu Purge du back office d\'administration : '.$code.'</td>
// 		  </tr>
// 		  <tr><td bgcolor="#fafafa" style="50px;"><br><br></td></tr>
// 		  <tr>
// 			<td align="center" bgcolor="#fafafa" style="font-size:12px;font-weight: bold;">Attention ce code est actif pour une durée de 30 min, passé ce délai, il faudrait faire une nouvelle demande de réinitialisation de code.</td>
// 		  </tr>
// 		  <tr>
// 			<td align="center" bgcolor="#fafafa">&nbsp;</td>
// 		  </tr>
// 		</table>

// 		</body>
// 		</html>';
// 	if(WTS_ENV == 'demo'){

// 		$SENDERNAME = $PROJECT_ABBREVIATION;
// 		$SENDEREMAIL = "borne@welcometouchscreen.com";
// 		$SUBJECT = "Purge : Code de vérification";

// 		$ses = new SimpleEmailService('AKIAJ4AK54QVXKXT2VXA', 'OyNcXwcmTGhvxEqrgD8TjCwYeg68fPFXXBGVU2WZ');
// 		$m = new SimpleEmailServiceMessage();
// 		// ENCODAGE :
// 		$m->setFrom($SENDERNAME.' <'.$SENDEREMAIL.'>');
// 		$m->addReplyTo($SENDEREMAIL);
// 		$m->setSubject($SUBJECT);
// 		$m->setMessageFromString('',$body);
// 		// DESTINATAIRES
// 		$m->addTo($ADRESSES);
// 		try {
// 			$ses->sendEmail($m);
// 			$return = array("status"=>true, "email envoyé", 'details' => array('mailfrom' => $MAIL_FROM, 'sendermail' => $SENDEREMAIL, 'destination' => $ADRESSES));
// 		} 
// 		catch (AwsException $e) {
// 			$return = array("status"=>false, "message" => ("Mailer Error: " . $e->getMessage()));
// 		}
// 		//echo json_encode($return);
// 	}
// 	else{
// 		//Create a new PHPMailer instance
// 		$mail = new PHPMailer();
// 		//Tell PHPMailer to use SMTP
// 		$mail->isSMTP();
// 		//Enable SMTP debugging
// 		// 0 = off (for production use)
// 		// 1 = client messages
// 		// 2 = client and server messages
// 		$mail->SMTPDebug = 0;
// 		//Ask for HTML-friendly debug output
// 		$mail->Debugoutput = 'html';
// 		//Set the hostname of the mail server
// 		$mail->Host = SMTP_HOST;
// 		//"10.154.187.197";
// 		//Set the SMTP port number - likely to be 25, 465 or 587
// 		$mail->Port = SMTP_PORT;
// 		//Whether to use SMTP authentication
// 		$mail->SMTPAuth = false;
// 		//Username to use for SMTP authentication
// 		$mail->Username = SMTP_USERNAME;
// 		//Password to use for SMTP authentication
// 		$mail->Password = SMTP_PASSWORD;
// 		//Set who the message is to be sent from
// 		$mail->setFrom(MAIL_FROM, $PROJECT_ABBREVIATION.' : Borne d\'orientation');
// 		$mail->CharSet = 'UTF-8';
// 		//Set who the message is to be sent to
// 		for($i=0;$i<count($ADRESSES);$i++){
// 			$mail->addAddress($ADRESSES[$i], $PROJECT_ABBREVIATION.' : Borne d\'orientation');
// 		}
// 		//Set the subject line
// 		$mail->Subject = "Purge : Code de vérification";
// 		$mail->msgHTML($body);
		
// 		//send the message, check for errors
// 		if($mail->send()) 
// 		{
// 			$return = array("status"=>true);
// 		} 
// 		else 
// 		{
// 			$return = array("status"=>false, "message" => ("Mailer Error: " . $mail->ErrorInfo));
// 		}
// 		//echo json_encode($return);
// 	}
// }
// $show_auth_code = $_SESSION["purge_auth_mail"] ? true : false;
// $show_auth_mail = true;
// $show_purge = false;
// if($_REQUEST["formEmailSubmitted"]){
// 	if($_REQUEST["email"] == ""){
// 		$msg .= "Veillez saisir votre adresse Email.";
// 		$_SESSION["purge_auth_mail"] = false;
// 		$show_auth_code = false;
// 		$show_auth_mail = true;
// 	}
// }
// function checkemail($str) {
//      return (!preg_match("/^([a-z0-9\+_\-]+)(\.[a-z0-9\+_\-]+)*@([a-z0-9\-]+\.)+[a-z]{2,6}$/ix", $str)) ? FALSE : TRUE;
// }
// /* Start authentication by email */
// if($_REQUEST["email"]){
// 	if(!checkemail($_REQUEST["email"])){
//       	$msg .= "Adresse email invalide.";
//       	$_SESSION["purge_auth_mail"] = false;
// 		$show_auth_code = false;
// 		$show_auth_mail = true;
//    	}else{
// 		if($_REQUEST["email"] == $_SESSION["email"]){
// 			$_SESSION["purge_auth_mail"] = true;
// 			$show_auth_code = true;
// 			$show_auth_mail = false;
// 			send_email($_REQUEST["email"]);

// 		}else{
// 			$msg .= "<p>Adresse email inconnue.</p>";
// 			$_SESSION["purge_auth_mail"] = false;
// 			$show_auth_code = false;
// 			$show_auth_mail = true;
// 		}
// 	}
// }else{
// 	$show_auth_code = false;
// 	$show_auth_mail = true;
// }
// /* end authentication by email */
// if(isset($_SESSION["purge_auth_code"]) && !empty($_SESSION["purge_auth_code"])){
// 	if(!$_REQUEST["code"]){
// 		$q = "SELECT id_admin, purge_code, IF(purge_date >= DATE_SUB( NOW(), INTERVAL 30 MINUTE ), 0, 1) expired FROM ca_admins WHERE id_admin = :id_admin AND supp = :supp AND inactif = :inactif ORDER BY purge_date DESC LIMIT 1";
// 			$values = array(':id_admin'=> $_SESSION["id"], ':supp' => 0, ':inactif' => 0);
// 			$result = excuteQuery($q, $values);
// 			$r = $result['stmt'];
// 			$n = $r->rowCount();
// 		if($n > 0){
// 			$o = $r->fetchObject();
// 			if($o->expired == 1){
// 				$msg .= "<p>Votre code a expiré</p>";
// 				$show_purge = false;
// 				$show_auth_code = false;
// 				$show_auth_mail = true;
// 				$_SESSION["purge_auth_code"] = "";
// 			}
// 		}
// 	}
// }
// /* Start authentication by code */
// if(isset($_REQUEST["code"]) && !empty($_REQUEST["code"])){
// 	$message = "";
// 	$code_purge = isset($_REQUEST["code"]) && !empty($_REQUEST["code"]) ? $_REQUEST["code"] : $_SESSION["purge_auth_code"];
// 	$q = "SELECT id_admin, purge_code, IF(purge_date >= DATE_SUB( NOW(), INTERVAL 30 MINUTE ), 0, 1) expired FROM ca_admins WHERE id_admin = :id_admin AND purge_code = :code_purge AND supp = :supp AND inactif = :inactif ORDER BY purge_date DESC LIMIT 1";
// 	$values = array(':id_admin'=> $_SESSION["id"],':code_purge' => $code_purge, ':supp' => 0, ':inactif' => 0);
// 	$result = excuteQuery($q, $values);
// 	$r = $result['stmt'];
// 	$n = $r->rowCount();
// 	$error = false;
// 	if($n == 0){
// 		$error = true;
// 		$show_purge = false;
// 		$show_auth_code = true;
// 		$show_auth_mail = false;
// 		$_SESSION["purge_auth_code"] = "";
// 		$message .= "<p>Code incorrect</p>";
// 	}else{
// 		$o = $r->fetchObject();
// 		if($o->expired == 1){
// 			$msg .= "<p>Votre code a expiré</p>";
// 			$show_purge = false;
// 			$show_auth_code = false;
// 			$show_auth_mail = true;
// 			$_SESSION["purge_auth_code"] = "";
// 		}else{
// 			$_SESSION["purge_auth_code"] = $o->purge_code;
// 			$show_auth_code = false;
// 			$show_auth_mail = false;
// 			$_SESSION["purge_auth_mail"] = false;
// 			$show_purge = true;
// 		}
// 	}
// }
// /* end authentication by code */

// /* start Cas où un admin a un purge code */
// if(!$_REQUEST["code"] && !$_REQUEST["email"] && (isset($_SESSION["purge_auth_code"]) && !empty($_SESSION["purge_auth_code"]))){
// 	$q = "SELECT id_admin, purge_code, IF(purge_date >= DATE_SUB( NOW(), INTERVAL 30 MINUTE ), 0, 1) expired FROM ca_admins WHERE id_admin = :id_admin AND purge_code IS NOT NULL AND supp = :supp AND inactif = :inactif ORDER BY purge_date DESC LIMIT 1";
// 	$values = array(':id_admin'=> $_SESSION["id"], ':supp' => 0, ':inactif' => 0);
// 	$result = excuteQuery($q, $values);
// 	$r = $result['stmt'];
// 	$n = $r->rowCount();
// 	$o = $r->fetchObject();
// 	if($n > 0){
// 		if($o->expired == 1){
// 			$msg .= "<p>Votre code a expiré</p>";
// 			$show_purge = false;
// 			$show_auth_code = false;
// 			$show_auth_mail = true;
// 			$_SESSION["purge_auth_code"] = "";
// 		}else{
// 			$_SESSION["purge_auth_code"] = $o->purge_code;
// 			$show_purge = true;
// 			$show_auth_code = false;
// 			$show_auth_mail = false;
// 		}
// 	}
// }
// /* end Cas où un admin a un purge code */


$delays = getBorneDelays();
$from_year_to_purge = $GLOBALS["BO_CONF"]["PURGE"]["YEARS"] ? $GLOBALS["BO_CONF"]["PURGE"]["YEARS"] : 5;
$time = strtotime("-5 year", time());
$lastYear = date("Y", $time);
$yearToPurge = date("Y") - $from_year_to_purge;
$q = "SELECT DISTINCT(YEAR(date_arrivee)) annee FROM ca_statistiques WHERE date_arrivee < '".$yearToPurge."-01-01 00:00:00' ORDER BY YEAR(date_arrivee) DESC";
$result = excuteQuery($q);
$r = $result['stmt'];
$nb_years = $r->rowCount();
$listYears = "";
while($o = $r->fetchObject()){
	$listYears .= '<option value="'.$o->annee.'" class="years">'.$o->annee.'</option>';
}
}else{
	header("location:dashboard.php");
}
?>

<html>

<head>
	<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
	<title><?php echo $PROJECT_TITLE;?> : Gestion des délais</title>
	<link rel="stylesheet" href="css/font-awesome.min.css" />
	<link rel="stylesheet" type="text/css" href="css/cadif.css" />
	<link rel="stylesheet" type="text/css" href="css/dashboard.css" />
	<link rel="stylesheet" type="text/css" href="css/cans/jquery-ui-1.8.17.custom.css" />
	<!--<link rel="stylesheet" type="text/css" href="css/tableTools_jui.css" />-->
	<link rel="stylesheet" type="text/css" href="css/datatable_jui.css" />
	<link rel="stylesheet" type="text/css" href="css/purge.css">

	<script type="text/javascript" src="js/jquery-1.7.2.min.js"></script>
	<script type="text/javascript" src="js/jquery-ui-1.8.22.custom.min.js"></script>
	<script type="text/javascript" src="js/jquery.dataTables.js"></script>
	<script type="text/javascript" src="js/purge.js"></script>
	<script type="text/javascript">
		// function checkForm2() {
		// 	if (document.getElementById("code").value == "") {
		// 		var POP = $('<div></div>').html("<center>Vous devez renseigner le champ 'Code'.</center>").dialog({autoOpen: false,title: 'Erreur'});
		// 		POP.dialog({autoOpen:false, modal:true, draggable: false, width:360,close:function(ev, ui){document.getElementById("code").focus();} });
		// 		POP.dialog("open");
		// 	} else {
		// 		document.formAuthCode.submit();
		// 	}
		// }

	</script>
</head>


<body>
	<div id="global">
		<div id="home">
			<div id="logo"><a href="dashboard.php"><img src="<?php echo $SERVER; ?>assets/img/logo.png" height="110" border="0"/></a></div>
			<div id="username">
				<b><?php echo isset($_SESSION["nom"]) ? $_SESSION["nom"] : $_SESSION["matricule"];?></b> &nbsp; | &nbsp; <a href="close.php" class="link" title="Fermer et clore votre session">D&#233;connexion</a>
				<br/>
			</div>
		</div>
		<div id="panels">
			<?php include "menu.php";?>
			<div class="main-content">
				<div id="title">
					SUPPRESSION DES DONNEES CLIENTS (HISTORIQUES DES VISITES)
				</div>

				<div id="container">
					<p style="margin-top: 20px;text-align: justify;">
						Conformité RGPD :
						<br><br>
						Conformément aux directives générales du RGPD en matière de limitation de la durée de conservation des données à caractère personnel, et en particulier celles énoncées à l’article 5 du RGPD qui impose à chaque responsable de traitement de déterminer une durée de conservation des données personnelles cohérente et justifiée au regard de l’objectif de leur traitement, il a été convenu en accord avec le <?php echo $PROJECT_TITLE;?> (Responsable de Traitement) :
						<div>
						- La durée maximale de conservation des données personnelles est de <?php 
						echo $GLOBALS["BO_CONF"]["PURGE"]["YEARS"]; ?> ans au-delà de l’année courante
						<br>
						- La mise en place de mécanismes techniques et organisationnels par le sous-traitant (Netisse) permettant au Responsable de Traitement la suppression de ces données
						</div>
						<br>
						La suppression par cet écran des données sélectionnées par le responsable de traitement seront irréversibles et définitives.


					</p>

					<form name="formAuthMail" method="post" id="formAuthMail" action="purge.php" style="display: none;" <?php /*if($show_auth_mail){ echo 'style="display: block;"';}else{echo 'style="display: none;"';}*/ ?>>
						<input type="hidden" name="formEmailSubmitted" value="1">
						<table>
							<tr><td colspan="3"><div style="font-size: 12px;color: red;"><?php echo $msg; ?></div></td></tr>
							<tr>
								<td>E-mail : </td>
								<td><input type="text" name="email" id="email"></td>
								<td><input type="submit" name="valider" value="Valider" class="formAct"></td>
							</tr>
						</table>
					</form>
					<form name="formAuthCode" id="formAuthCode" action="purge.php" style="display: none;" <?php /*if($show_auth_code){ echo 'style="display: block;"';}else{echo 'style="display: none;"';}*/ ?>>
						<table>
							<tr><td colspan="3"><div style="font-size: 12px;color: red;"><?php echo $message; ?></div></td></tr>
							<tr>
								<td>Code : </td>
								<td><input type="text" name="code" id="code"></td>
								<td><input type="button" name="valider" value="Valider" class="formAct" onclick="checkForm2();"></td>
							</tr>
						</table>
					</form>
					<form name="formPurge" id="formPurge" method="post" <?php /*if($show_purge){ echo 'style="display: block;"';}else{echo 'style="display: none;"';}*/ ?>>
						<table>
							<tr>
								<td></td>
							</tr>
							<?php if($nb_years>0){ ?>
								<tr>
									<td>
										<label style="text-align:left">À partir de </label>
									</td>
									<td>
										<input type="hidden" name="totalToPurge" class="totalToPurge">
										<input type="hidden" name="MaxYearToPurge" id="MaxYearToPurge" value="<?php echo $GLOBALS["BO_CONF"]["PURGE"]["YEARS"]; ?>">
										<select name="year" class="placeholder" id="selectYear">
											<option selected="true" class="placeholder" value="" disabled>Sélectionner une année</option>
											<?php echo $listYears; ?>
										</select>
										<input type="hidden" name="nb_data_to_purge" id="nb_data_to_purge">
									</td>
									<td>
										<button type="button" class="deleteBtn" disabled="true">Supprimer</button>
									</td>
								</tr>
							<?php }else{ ?>
								<tr><td colspan="3">Pas de données à supprimer</td></tr>
							<?php } ?>
						</table>
					</form>
				</div>
			</div>
		</div>
	</div>
	<?php include 'footer.php';?>
</body>
</html>