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

//Inclusion de l'API Onyx
require_once(trim(file_get_contents('./.onyx')));
require_once("common.php"); //Chargement de tout le nécessaire pour le jeu

//On vérifie si le client est connecté sur le site
if (isset($SESS) && !(empty($SESS->values["connected"]) && empty($SESS->values['id']) && empty($SESS->values['race']) && empty($SESS->level)) && isset($SESS->values['idPlan']) && isset($SESS->values['idAsteroide'])) {
    //Si un nouveau joueur cherche à se connecter du même endroit, on déconnecte le joueur en cours avant
    $HB_login = gpc('l');
    if (!empty($HB_login) && strtolower($HB_login) != strtolower(trouvNom($SESS->values['id']))) {
        require("server/logout.php");
    } elseif (!empty($HB_login)) {
        redirection("./".$VAR["first_page"]);
        exit;
    }
    //Déconnexion de secours
    elseif (isset($_GET["logout"])) {
        require("server/logout.php");
        redirection("./".$VAR["first_page"]);
    }
    unset($HB_login);


    $race = $SESS->values["race"];
    $securePlanete = array();

    //Inclusion des formules
    require_once("donnees.php");
    //On inclus les différentes classes
    include_once("Class/exceptionHB.php");
    include_once("Class/user.php");
    include_once("Class/surface.php");
    include_once("Class/planete.php");
    include_once("Class/asteroide.php");
    include_once("Class/flotte.php");

    //Récupération d'informations au sujet de l'utilisateur
    $id_user = $SESS->values["id"];
    $ip = $_SERVER["REMOTE_ADDR"];

    //On commence l'envoie des données requise pour les templates
    $template->assign("menu", array_map("url", $VAR["menu"])); //Envoie des liens du menu latéral
    $template->assign("auth_level", $SESS->level); //Envoie du niveau d'accès de l'utilisateur
    $template->assign("race", $race);

    //Connexion à la base de données ou reconnexion si la classe existe
    if (isset($bdd)) {
        $bdd->reconnexion();
    } else {
        $bdd = new BDD();
    }

    //Recherche de multicompte
    $multi = $bdd->query("SELECT U.pseudo, R.id_util FROM $table_registre_identification R INNER JOIN $table_user U ON U.id = R.id_util WHERE R.ip = '$ip' GROUP BY R.ip, R.id_util HAVING R.id_util != $id_user;");

    //On gère les demande de changement de planète
    if (isset($_POST["planete"])) {
        if (preg_match("#A#", $_POST["planete"])) {
            $idAsteroideTest = intval(substr(gpc("planete", "post"), 1));
            if ($bdd->unique_query("SELECT id FROM $table_alliances WHERE id = $idAsteroideTest;") && $bdd->unique_query("SELECT id FROM $table_user WHERE id = $id_user AND id_alliance = $idAsteroideTest;")) {
                $SESS->values["idPlan"] = 0;
                $SESS->values["idAsteroide"] = $idAsteroideTest;
                $SESS->values["isolement"] = 0;
                $SESS->put();
                $template->assign("page", "vp");
                $template->display("game/vp.tpl");
                exit;
            }
            unset($idAsteroideTest);
        } else {
            $idPlanTest = intval(gpc("planete", "post"));
            if ($bdd->unique_query("SELECT id FROM $table_planete WHERE id_user = $id_user AND id = $idPlanTest;")) {
                $SESS->values["idPlan"] = $idPlanTest;
                $SESS->values["idAsteroide"] = 0;
                $SESS->values["isolement"] = 0;
                $SESS->put();
                $template->assign("page", "vp");
                $template->display("game/vp.tpl");
                exit;
            }
            unset($idPlanTest);
        }
    }
    $idPlan = $SESS->values["idPlan"];
    $idAsteroide = $SESS->values["idAsteroide"];

    $queryMail1 = $bdd->unique_query("SELECT COUNT(id) AS nombre FROM $table_mail WHERE destinataire = $id_user AND expediteur != false AND vu = '1';");
    $queryMail2 = $bdd->unique_query("SELECT COUNT(id) AS nombre FROM $table_mail WHERE destinataire = $id_user AND expediteur = false AND vu = '1';");
    $queryMail = array($queryMail1["nombre"], $queryMail2["nombre"]);
    $queryPlanetes = $bdd->query("SELECT * FROM $table_planete WHERE id_user = $id_user ORDER BY id ASC;");

    $bdd->deconnexion();
    unset($queryMail1, $queryMail2);

    //Chargement de la planète/astéroide actuel
    if ($idPlan == 0 && $idAsteroide == 0) {
        trigger_error('Planète et Asteroïde nul, deconnexion du joueur '.$id_user, E_USER_ERROR);
        include("server/logout.php");
        exit;
    } elseif ($idPlan == 0) {
        define('SURFACE', 'asteroide');
        $planete = new Asteroide($idAsteroide);
        $planete->actualiser();
        //On charge les permissions de l'utilisateur pour l'alliance
        $planete->loadPermissions($planete->fondateur);
    } else {
        define('SURFACE', 'planete');
        $planete = new Planete($idPlan);
        $planete->actualiser();
    }
    unset($ip, $idAsteroide, $idPlan);

    //On vérifie que le joueur ne soit pas en mode vacances forcé
    if ($planete->mv > 0) {
        $SESS->close();
        redirection($config["first_page"]."?mvf");
        exit;
    }

    //NOMS ET FLOTTES
    include("flottes.php");

    //Envoie d'informations au template
    $template->assign("alertMail", $queryMail);
    $template->assign("planete", $planete);
    $template->assign("planetes", $queryPlanetes);

    //Calcul du temps de jeu
    $tpsdejeu = time() - $planete->last_visite;
    $heur = floor($tpsdejeu/3600);
    $min = floor(($tpsdejeu%3600)/60);
    if ($heur > 0) {
        $min = $heur." h ".$min;
    }
    $template->assign("tpsdejeu", $min." min");
    unset($tpsdejeu, $heur, $min, $queryMail);

    //Récupération de la page demandée
    $p = gpc('p');

    //Vérification de l'isolement de la planète
    if ((empty($SESS->values['isolement']) || time() >= $SESS->values['isolement']) && $p != 'operateur' && $p != 'demarrage' && $p != 'avertmulti' && $p != 'chat' && $p != 'rename' && $p != 'accueil' && $p != 'arbre' && $p != 'prochainement' && $p != 'options' && $p != 'messagerie' && $p != 'envoyer' && $p != 'classement' && $p != 'bugs' && $p != 'deconnexion') {
        //TODO Si la planète est en isolement total, faire un autre message
        if ($planete->isolement()) {
            $template->assign("titre", "Planète isolée");
            erreur("Impossible de rentrer en contact avec cette planète.<br />Réessayez vers ".date('H:i', $planete->isolement[1]));
        } else {
            $SESS->values["isolement"] = $planete->isolement[0];
            $SESS->put();
        }
    }

    if (isset($SESS->values["avert"]) && $p != "avertmulti" && $p != "demarrage") {
        include("server/avert.php");
    } else {
        switch ($p) {
            case "batiments":
                include("game/batiments.php");
                break;
            case "caserne":
                include("game/caserne.php");
                break;
            case "chantierspatial":
                include("game/chantierspatial.php");
                break;
            case "chantierterrestre":
                include("game/chantierterrestre.php");
                break;
            case "laboratoire":
                include("game/laboratoire.php");
                break;
            case "arbre":
                include("game/arbre.php");
                break;
            case "description":
                include("game/description.php");
                break;
            case "ressources":
                include("game/ressources.php");
                break;
            case "diplomatie":
                include("game/diplomatie.php");
                break;
            case "gestion":
                include("game/gestion.php");
                break;
            case "marche":
                include("game/marche.php");
                break;
            case "flotte":
                include("game/flotte.php");
                break;
            case "carte":
                include("game/carte.php");
                break;
            case "alliances":
                include("game/alliance.php");
                break;
            case "classement":
                include("server/classement.php");
                break;
            case "rename":
                include("game/rename.php");
                break;
            case "messagerie":
                include("server/messagerie.php");
                break;
            case "alli_messagerie":
                include("game/alliances/messagerie.php");
                break;
            case "options":
            case "changeopt":
                include("server/options.php");
                break;
            case "amis":
                include("server/amis.php");
                break;
            case "destinationsrapides":
                include("server/destinrapid.php");
                break;
            case "chat":
                $page = 'chat'; $titre = 'Chat';
                break;
            case "alli_chat":
                include("game/alliances/chat.php");
                break;
            case "aide":
            case "faq":
                include("server/aide.php");
                break;

            case "operateur":
                include("server/operateur.php");
                break;
            case "prochainement":
                $page = "prochainement";
                $titre = "Prochainement";
                break;
            case "version":
                include("server/version.php");
                break;
            case "demarrage":
                include("server/demarrage.php");
                break;
            case "avertmulti":
                include("server/avertmulti.php");
                break;

            case "pilori":
                include("server/pilori.php");
                break;
            case "conditions":
                include("server/conditions.php");
                break;
            case "regles":
                include("game/regles.php");
                break;

            case "deconnexion":
            case "logout":
                include("server/logout.php");
                break;
            default:
                include("game/accueil.php");
        }
    }
    //On supprime les dernières variables inutiles pour la suite
    unset($planete, $SESS, $bdd, $VAR, $queryPlanetes, $_POST, $_GET, $LANG);

    //Inclusion de la pub et du footer
    include("pub.php");

    $template->assign("page", $page);
    if (isset($titre)) {
        $template->assign("titre", $titre);
    }

    $template->display("game/".$page.".tpl");
}
//Si le client n'est pas connecté au site
else {
    include("server/connexion.php");

    $p = gpc('p');
    switch ($p) {
        //Serveur principal
        /*		case "validation":
           include('game/validation.php');
           break;
           case "inscription":
           include('game/inscription.php');
           break;
           case "oubliemdp":
           redirection('http://halo-battle.fr/');
           break;*/
        //Serveur de jeu
        case "inscription":
           include('server/inscription.php');
           break;
        case "validation":
           include('server/validation.php');
           break;
        case "classement":
            include(_FCORE."../game/classement.php");
            break;
        case "njoueur":
            include("server/njoueur.php");
            break;
        case "inscription":
            redirection('http://halo-battle.s-fr.com/?p=inscription');
            exit;
            break;
        case "oubliemdp":
            include("server/oubliemdp.php");
            break;
        case "pilori":
            include("server/pilori.php");
            break;
            //Tous serveurs
        case "conditions":
            include("server/conditions.php");
            break;
        case "regles":
            include("server/regles.php");
            break;
        case "changeopt":
            erreur("Vous devez être connecté pour affectuer cette action !");
            // no break
        case "connexion":
        default:
            $page = 'mini';
            break;
        //default:
            //$page = 'mini';
        //	redirection('?p=connexion');
        //	exit;
    }
    $template->display('cms/'.$page.'.tpl');
}
