<?php
if (!defined('INDEX')) {
    header('Location: ../');
    exit;
}
$pagea = 'mail_liste';
$titre = 'Demandes et problèmes de la galaxie';

    $template->assign('linkpage', 'courrier');

if (!empty($_GET['w']) || !empty($_GET['x'])) {
    if (!empty($_GET['w'])) {
        $id = $_GET['w'];
    } else {
        $id = $_GET['x'];
    }
    $bdd = new BDD();
    $bdd->escape($id);
    $req = $bdd->unique_query("SELECT $table_user.pseudo, $table_ope_mail.statut, $table_ope_mail.time, $table_ope_mail.titre, $table_ope_mail.contenu, $table_ope_mail.id FROM $table_ope_mail INNER JOIN $table_user ON $table_user.id = $table_ope_mail.id_user WHERE $table_ope_mail.id = '$id';");
    if ($req['statut'] >= 6) {
        $bdd->query("UPDATE $table_ope_mail SET statut = '0' WHERE id = '$id';");
    } else {
        $bdd->query("UPDATE $table_ope_mail SET statut = statut + 1 WHERE id = '$id';");
    }
    $bdd->deconnexion();

    if (isset($_GET['x'])) {
        header('Location: admin.php?p=courrier&v='.$id);
    } else {
        header('Location: admin.php?p=courrier');
    }
    exit;
} elseif (!empty($_GET['v'])) {
    $id = $_GET['v'];
    $bdd = new BDD();
    $bdd->escape($id);
    $req = $bdd->unique_query("SELECT $table_user.pseudo, $table_ope_mail.statut, $table_ope_mail.time, $table_ope_mail.titre, $table_ope_mail.contenu, $table_ope_mail.id FROM $table_ope_mail INNER JOIN $table_user ON $table_user.id = $table_ope_mail.id_user WHERE $table_ope_mail.id = '$id';");
    $bdd->deconnexion();

    $template->assign('req', $req);
    $template->assign('id', $id);
    $pagea = 'mail_view';
} elseif (!empty($_GET['d']) && $sess->level >= 5) {
    $id = $_GET['d'];
    $bdd = new BDD();
    $bdd->escape($id);
    $bdd->query("DELETE FROM $table_ope_mail WHERE id = '$id';");
    $bdd->deconnexion();

    header('Location: admin.php?p=courrier');
    exit;
} else {
    $bdd = new BDD();
    $req = $bdd->query("SELECT $table_user.pseudo, $table_ope_mail.statut, $table_ope_mail.time, $table_ope_mail.titre, $table_ope_mail.contenu, $table_ope_mail.id FROM $table_ope_mail INNER JOIN $table_user ON $table_user.id = $table_ope_mail.id_user ORDER BY $table_ope_mail.time DESC;");
    $bdd->deconnexion();
    $template->assign('mails', $req);
}
