<?php
	//chdir('/var/www/html/avion-poeme/');
	require_once 'session_init.php';
	require_once 'config.inc.php';
	require_once 'db.class.php';
	require_once 'log.php';
	require_once 'envoi_courriel.inc.php';

	$db = new db();
	//test();
	 $_SERVER["PHP_AUTH_USER"] = "cron";
	//peripetieDatee();
	print "envoi des courriers en attente" . EOLH;
	envoiCourrielEnattente();
	print "envoi des péripéties" . EOLH;
	peripeties();
	print "Envoi des arrivées" . EOLH;
	arrivee();

	function peripetieDatee()
	{
		global $db;

		$flag = false;
		$db->urlAvion = $base_url . "/?avionpoeme=" . $db->idAvion;
		//recherche des péripéties datées
		$query = "SELECT * FROM peripeties WHERE quand!='' AND DATEDIFF(quand,CURDATE())=0";
		$db->query($query);
		$peripetieTable = $result = $db->result->fetch_all(MYSQLI_ASSOC);
		$query = "SELECT * FROM avionpoeme WHERE atteri=0";
		$db->query($query);
		while ( ($result = $db->result->fetch_assoc()) )
		{
			$dicoExpe = getLang( $result['expeLang'] );
			$dicoDest = getLang( $result['destLang'] );
			foreach( $peripetieTable as $p )
			{
				$indexObjet = "Objet_" . $p['indexText'];
				$objetMail = $dicoExpe["Objet_" . $p['indexText']];
				$mailText = $dicoExpe[$p['indexText']] .EOL .EOL ;
				print $objetMail . EOLH;
				print $mailText . EOLH;
				envoiMail( $result['destMail'], $objetMail, $mailText, false);
				sleep(1);
				envoiMail( $result['expeMail'], $objetMail, $mailText, true);
				sleep(1);
			}
		}
	}

	function peripeties()			//recherche des péripéties non datées
	{
		global $db, $base_url;
		$r = 0;
		$s = 0;
		// ouverture DB peripéties
		$dbPeripetie = new db();
		// requête Mysql
		$query = "SELECT *, UNIX_TIMESTAMP(date) as datePeripetie FROM avionPeripetie LEFT JOIN peripeties USING (idPeripetie) WHERE mailSent=false AND TIMEDIFF(CONCAT_WS(' ',CURDATE(),CURTIME()), date) > '00:00'";
		$dbPeripetie->query($query);
		$peripeties = $dbPeripetie->result->fetch_all(MYSQLI_ASSOC);
		$dbPeripetie->close();
		foreach ( $peripeties as $peripetie)
		{
			print "péripétie " . $peripetie["idAP"] . " - avion poème n° " . $peripetie['idAvion'] .EOLH;
			$db->getPlane($peripetie['idAvion']);
			if ($db->connect->affected_rows == 0)
			{
				log_error("Péripétie " . $peripetie["idAP"] . "n'a pas d'avion associé idAvion=>" . $peripetie['idAvion']);
				print "Péripétie " . $peripetie["idAP"] . "n'a pas d'avion associé idAvion=>" . $peripetie['idAvion'];
			}
			else
			{
				//print_r($db);
				$dicoExpe = getLang( $db->expeLang );
				$dicoDest = getLang( $db->destLang );
				// TODO calcul de la nouvelle date d'arrivée
				$dateExpe = new DateTime("@$db->startTime");
				$dateDest = new DateTime("@$db->deliveryTime");
				$interval = $dateExpe->diff($dateDest);
				$numericInterval = (($interval->days*24 + $interval->h)*60 + $interval->i)*60 + $interval->s;
				$addDate = $numericInterval * 15/100;
				$db->deliveryTime += $addDate;
				$db->deliveryTimeServer += $addDate;
				$query = "UPDATE avionpoeme SET deliveryTime=FROM_UNIXTIME(" . $db->deliveryTime . "), deliveryTimeServer=FROM_UNIXTIME(" . $db->deliveryTimeServer . ") WHERE idAvion='" . $peripetie['idAvion'] . "'" ;
				$db->query($query);
				$db->urlAvion = $base_url . "/?avionpoeme=" . $db->uid;
				$db->datePeripetie = formatteDate($db->expeLang, $db->deliveryTime, $db->startTZ);
				$indexObjet = "Objet_" . $peripetie['indexText'];
				$result = replaceVariables($db, $dicoExpe["Objet_" . $peripetie['indexText']], $dicoExpe);
				$objetMail = $result["text"];
				$result = replaceVariables($db, $dicoExpe[$peripetie['indexText']], $dicoExpe);
				$mailText =  $result["text"];
				//$html = $result['html'];
				sleep(1);
				print "envoi courriel à l'expéditeur : " . $db->expeMail . EOLH . $mailText .EOLH;
				$r = envoiMail( $db->expeMail, $objetMail, $mailText);
				$db->datePeripetie = formatteDate($db->destLang, $db->deliveryTime, $db->deliveryTZ);
				$result = replaceVariables($db, $dicoDest["Objet_" . $peripetie['indexText']], $dicoDest);
				$objetMail = $result["text"];
				$result = replaceVariables($db, $dicoDest[$peripetie['indexText']], $dicoDest);
				$mailText = $result["text"];
				print "envoi courriel au destinataire : " . $db->destMail . EOLH  . $mailText .EOLH;
				$s = envoiMail( $db->destMail, $objetMail, $mailText);
				sleep(1);
				//print "r=" . $r ." => s=" .$s .EOLH;

				if ($r AND $s)
				{
					$query = "UPDATE avionPeripetie SET mailSent=true WHERE idAP='" . $peripetie['idAP'] ."'";
					$db->query($query);
				}else
				{
					print "table avion péripétie non mise à jour" .EOL;
					print "UPDATE avionPeripetie SET mailSent=true WHERE idAP='" . $peripetie['idAP'] ."'" .EOLH;
				}

				sleep(1);
			}
		}
	}


	function arrivee()
	{
		global $db;
		$r = 0;
		$s = 0;
		//recherche des avions atteris
		$query = "SELECT * FROM avionpoeme WHERE atteri = 0 AND TIMEDIFF(CONCAT_WS(' ',CURDATE(),CURTIME()),deliveryTimeServer) > '00:00'";
		$db->query($query);
		$avionArrive = $db->result->fetch_all(MYSQLI_ASSOC);
		var_dump($avionArrive);
		foreach ($avionArrive as $avion)
		{
			print "avion poème n° " . $avion['idAvion'] . "a atterri" . EOLH;
			$dicoExpe = getLang( $avion['expeLang'] );
			$dicoDest = getLang( $avion['destLang'] );

			//envoi notification arrivée expéditeur
			$indexObjet = "Objet_";
			$index = "Notification_Arrivee_Expediteur";
			$objetMail = replaceVariables( (object)$avion, $dicoExpe[$indexObjet . $index], $dicoExpe);
			$result = replaceVariables((object)$avion, $dicoExpe[$index], $dicoExpe);
			$mailText= $result["text"];
			print "envoi courriel à l'expéditeur : " . $avion['expeMail'] . EOLH . $mailText .EOLH;
			$r = envoiMail( $avion['expeMail'], $objetMail["text"], $mailText);

			//envoi notification arrivée destinataire
			$index = "Notification_Arrivee_Destinataire";
			$objetMail = replaceVariables((object)$avion, $dicoDest[$indexObjet . $index], $dicoDest);
			$result = replaceVariables((object)$avion, $dicoDest[$index], $dicoDest);
			$mailText = $result["text"];
			$html = $result['html'];
			if ( $html )
			{
				$mailText = "<html><head></head>\n<body>" . $mailText . "</body></html>";
			}
			print "envoi courriel au destinataire : " . $avion['destMail'] . EOLH . $mailText .EOLH;
			sleep(1);
			$s = envoiMail( $avion['destMail'], $objetMail["text"], $mailText, $html);
			if ($r AND $s)
			{
				$query = "UPDATE avionpoeme SET atteri=true WHERE idAvion='" . $avion['idAvion'] ."'";
				$db->query($query);
			}
			sleep(1);
		}
	}

	function envoiCourrielEnattente()
	{
		global $db;
		$query = "SELECT * FROM courriels";
		$db->query($query);
		$courriels = $db->result->fetch_all(MYSQLI_ASSOC);
		foreach( $courriels as $courriel)
		{
			$r = envoiMail( $courriel['destinataire'], $courriel['objet'], $courriel['message'], $courriel['html']);
			if ($r)
			{
				$query = "DELETE FROM courriels WHERE id='" . $courriel['id'] . "'";
				$db->query($query);
			}
			sleep(1);
		}
	}

	function test()
	{
		$lang = array( 'fr', 'en', 'es', 'de', 'ar', 'bg', 'zh', 'ja', 'pt');
		foreach ($lang as $value)
		{
			getLang( $value );
			print $value;
			print json_last_error_msg() .EOLH;
		}
	}
	$db->close();
?>
