<?php
if(!defined('INDEX')) { header('Location: ../'); exit; }
$page = 'messagerie';
$titre = 'Messagerie';

if (isset($_POST['IM'])) {
	$stop = false;
	for($i=1 ; $i<=$_POST['IM'] ; $i++) {
		if (!empty($_POST['m'.$i])) {
			$mes = $_POST['m'.$i];
			$bdd->connexion();
			$bdd->query("DELETE FROM $table_mail WHERE destinataire = $id_user AND id = '$mes';");
			$bdd->deconnexion();
			$stop = true;
		}
	}
	if ($stop) { header('Location: ?p=messagerie'); exit; }
}
if (isset($_POST['IR'])) {
	$stop = false;
	for($i=1 ; $i<=$_POST['IR'] ; $i++) {
		if (!empty($_POST['r'.$i])) {
			$mes = $_POST['r'.$i];
			$bdd->connexion();
			$bdd->query("UPDATE $table_mail SET vu='s' WHERE destinataire = $id_user AND id = '$mes';");
			$bdd->deconnexion();
			$stop = true;
		}
	}
	if ($stop) { header('Location: ?p=messagerie'); exit; }
}

$bdd->connexion();
$messcomp = $bdd->query("SELECT M.*, U.pseudo AS expediteur FROM $table_mail M INNER JOIN $table_user U ON U.id = M.expediteur WHERE M.destinataire = $id_user AND M.expediteur != false ORDER BY M.id DESC;");
$nbmax = $bdd->num_rows;

$result = $bdd->query("SELECT M.*, U.pseudo AS expediteur FROM $table_mail M INNER JOIN $table_user U ON U.id = M.expediteur WHERE M.destinataire = $id_user AND M.expediteur != false ORDER BY M.id DESC LIMIT 50;");

if ($queryUser['auth_level'] >= 3 && $nbmax > $bdd->num_rows) $result = $messcomp;
elseif ($nbmax > $bdd->num_rows) $template->assign('avertissement', '<p style="color: red; "><b>Vous avez des messages en attente de réception. Libérez de la place dans votre messagerie pour les afficher.</b></p>');

$TEMP_messages = array();
$i=0;
$nbc = count($result);
for ($i=0 ; $i < $nbc ; $i++) {
	$TEMP_messages[] = array($result[$i]['sujet'], date("d/m/y H:i:s", $result[$i]['temps']), $result[$i]['expediteur'], bbcode($result[$i]['contenu']), $i+1, $result[$i]['id']);
}
$template->assign('messages', $TEMP_messages);
$template->assign('IM', $i);


$data = $bdd->query("SELECT * FROM $table_mail WHERE destinataire = $id_user AND expediteur = false AND vu != 's' ORDER BY id DESC;");
$nbres = $bdd->num_rows;
$TEMP_rapport = array();
for($i = 0; $i < $nbres; $i++){
	$TEMP_rapport[] = array($data[$i]['sujet'], date("d/m/y H:i:s", $data[$i]['temps']), 0, bbcode($data[$i]['contenu']), $i+1, $data[$i]['id']);
}
$template->assign('rapports', $TEMP_rapport);
$template->assign('IR', $i);
$template->assign('script', '<script>
for (j=2; document.getElementsByName(\'m\'+j)[0]; j++) hide(document.getElementsByName(\'m\'+j)[0].previousSibling);
for (j=2; document.getElementsByName(\'r\'+j)[0]; j++) hide(document.getElementsByName(\'r\'+j)[0].previousSibling);
</script>');

$bdd->query("UPDATE $table_mail SET vu = '0' WHERE destinataire = $id_user AND vu != 's'");
$bdd->deconnexion();
?>