<?php
//Définition de la constante anti-hacking
define("INDEX", 2);
define("DEBUG", false);

//Inclusion de l'API Onyx
require_once(trim(file_get_contents('./.onyx')));
require_once("function.php"); //Inclusion des fonctions principales
require_once("tables.php"); //Inclusion des noms des tables de base de données correspondant à l'architecture du serveur
require_once("donnees.php");

//On charge la session
$SESS = new Session();

//On vérifie si le client est connecté sur le site
if (isset($SESS) && isset($SESS->values['connected']) && $SESS->values['connected'] && !empty($SESS->values['id']) && !empty($SESS->values['race']) && !empty($SESS->level) && isset($SESS->values['idPlan']) && isset($SESS->values['idAsteroide'])) {
    include_once("Class/user.php");
    $user = new User($SESS->values['id']);
    if (!empty($user->id_alliance)) {
        if (isset($_POST['message'])) {
            $message = htmlentities(trim(gpc("message", "post")));
            if (!empty($message) || $message == "0") {
                $bdd = new BDD();
                $bdd->escape($message);
                $bdd->query("INSERT INTO $table_alliances_chat (id_alliance, emetteur, timestamp, message) VALUES (".$user->id_alliance.", ".$user->id_user.", ".time().", '$message');");
                $bdd->deconnexion();
            }
        } else {
            if (!empty($_GET['time'])) {
                $time = intval(gpc("time"))." ORDER BY timestamp DESC";
            } else {
                $time = "0 ORDER BY timestamp DESC LIMIT 15";
            }

            $bdd = new BDD();
            $messages = $bdd->query("SELECT C.*, U.pseudo FROM $table_alliances_chat C INNER JOIN $table_user U ON U.id = C.emetteur WHERE C.id_alliance = ".$user->id_alliance." AND C.timestamp > $time;");
            $bdd->deconnexion();

            header("X-JSON: ".json_encode($messages));
        }
    }
}
