<?php
define("INDEX", 1);
define("DEBUG", false);
$chrono_start = microtime();
require_once(trim(file_get_contents('./.onyx')));
require_once("common.php"); //Chargement de tout le nécessaire pour le jeu
require_once("function.php");
require_once("Class/JSON.php");
require_once("Class/flotte.php");
require_once("Class/planete.php");

if (isset($SESS) && isset($SESS->values['connected']) && $SESS->values['connected'] && !empty($SESS->values['id']) && !empty($SESS->values['idPlan'])) {
    $idPrep = gpc("cds_temp", "post");
    $json = new Services_JSON();
    $nbtrajet = 2;

    if (empty($VAR['flottes']) && $SESS->level <= 1) {
        $datas = array(
            'root' => array(
                'destination' => '<input class="dest" type="text" id="amas" name="amas" maxlength="2" value="'.gpc('galaxie', 'post').'" />:<input class="dest" type="text" id="ss" name="ss" maxlength="2" value="'.gpc('ss', 'post').'" />:<input class="dest" type="text" id="plan" name="pos" maxlength="2" value="'.gpc('pos', 'post').'" />',
                'temps' => '-',
                'deblok' => '<span style="color: #FF0000;"><b>Les flottes sont désactivés pour le moment.</b></span>',
                'conso' => '-',
                'tactique' => '',
                'places' => ''
            )
        );
        header("X-JSON: ".$json->encode($datas));
        exit;
    }

    $destin = gpc('fav_dest', 'post');

    $chapeau = new bdd();
    $idPlan = $SESS->values['idPlan'];
    $queryPlanete = $chapeau->unique_query("SELECT * FROM $table_planete WHERE id = '$idPlan'");
    if (!empty($destin)) {
        $chapeau->escape($destin);
        $queryPlaneteRapid = $chapeau->unique_query("SELECT nom_planete, galaxie, ss, position FROM $table_planete WHERE id = $destin;");
        if ($queryPlaneteRapid) {
            $destinRapid = '['.$queryPlaneteRapid['galaxie'].':'.$queryPlaneteRapid['ss'].':'.$queryPlaneteRapid['position'].']<input type="hidden" id="amas" name="amas" maxlength="2" value="'.$queryPlaneteRapid['galaxie'].'" /><input type="hidden" id="ss" name="ss" maxlength="2" value="'.$queryPlaneteRapid['ss'].'" /><input type="hidden" id="plan" name="pos" maxlength="2" value="'.$queryPlaneteRapid['position'].'" />';
        }
    }
    if (!isset($destinRapid)) {
        $destinRapid = '<input class="dest" type="text" id="amas" name="amas" maxlength="2" value="'.gpc('galaxie', 'post').'" />:<input class="dest" type="text" id="ss" name="ss" maxlength="2" value="'.gpc('ss', 'post').'" />:<input class="dest" type="text" id="plan" name="pos" maxlength="2" value="'.gpc('pos', 'post').'" />';
    }
    $start_galaxie = $queryPlanete['galaxie'];
    $start_ss = $queryPlanete['ss'];
    $start_position = $queryPlanete['position'];

    if (empty($SESS->values["prepFlottes"][$idPrep]['time']) ||
              $SESS->values["prepFlottes"][$idPrep]['time'] + 1200 < time() ||
              empty($SESS->values["prepFlottes"][$idPrep]['nbVaisseaux']) ||
              empty($SESS->values["prepFlottes"][$idPrep]['vitesse']) &&
              isset($SESS->values['auth_level'])) {
        $datas = array(
            'root' => array(
                'destination' => $destinRapid,
                'temps' => '-',
                'deblok' => '<b>Une erreur est survenue lors de la création de la flotte. Veuillez recommencer</b>',
                'conso' => '-',
                'tactique' => '',
                'places' => '',
            )
        );
    } elseif (empty($_POST['nom']) || preg_replace('@[^a-zA-Z0-9_ ]@i', '', $_POST['nom']) != $_POST['nom']) {
        $datas = array(
            'root' => array(
                'destination' => $destinRapid,
                'temps' => '-',
                'deblok' => '<b>Nom de la flotte incorrect !</b>',
                'conso' => '-',
                'tactique' => '',
                'places' => '',
            )
        );
    } elseif ($_POST['galaxie'] > $VAR['nb_amas'] || $_POST['ss'] > $VAR['nb_systeme'] || $_POST['pos'] > $VAR['nb_planete'] || $_POST['galaxie'] < 0 || $_POST['ss'] < 1 || $_POST['pos'] < 1 || ($_POST['galaxie'] < 1 && $SESS->values['auth_level'] < 6)) {
        $datas = array(
            'root' => array(
                'destination' => $destinRapid,
                'temps' => '<span style="color: #FF0000;"><b>Lieu inaccessible</b></span>',
                'deblok' => '<b>Corrigez la destination !</b>',
                'conso' => '-',
                'tactique' => '',
                'places' => '',
            )
        );
    } else {
        $_POST['vitesse'] /= 100;

        $planete = new planete($idPlan);
        $flotte = new flotte();
        $temps = $flotte->calc_deplacement($planete, $_POST['galaxie'], $_POST['ss'], $_POST['pos'], $_POST['vitesse'], $SESS->values["prepFlottes"][$idPrep]['vaisseaux'], 1000);
        if ($temps <= 0) {
            $temps = 454;
        }
        $conso = $flotte->calc_deplacement($planete, $_POST['galaxie'], $_POST['ss'], $_POST['pos'], $_POST['vitesse'], $SESS->values["prepFlottes"][$idPrep]['vaisseaux'], 1000, false, true);
        // $conso renvoi le temps ET la conso dans un array
        $conso = intval($conso[1]);

        $met = intval(gpc('met', 'post'));
        $cri = intval(gpc('cri', 'post'));
        $hyd = intval(gpc('hyd', 'post'));
        $places = $flotte->calcStockage($SESS->values["prepFlottes"][$idPrep]['vaisseaux'], $planete);
        $places -= ceil($conso * $nbtrajet);
        if (($met+$cri+$hyd) > 0) {
            $places -= ($met+$cri+$hyd);
        }
        $tactique = '';
        // si la mission est une mission d'attaque
        if ($_POST['mission'] == '3') {
            $tactique = '<label for="selecttactique">Tactique d\'attaque :</label><select id="selecttactique" name="tactique">';
            //On récupère le niveau actuel de la technologie Commandement militaire
            $id_user = $SESS->values['id'];
            global $table_user;
            $table = $table_user;
            $queryUser = $chapeau->unique_query("SELECT * FROM $table WHERE id = '$id_user'");
            $lvltechno = $queryUser['tactique'];
            $tactiquedef = $queryUser['combatAT_tactique'];

            if ($lvltechno < 1) { //Si on a pas le niveau, on ne peux pas envoyer la flotte
                $datas = array(
                        'root' => array(
                            'destination' => $destinRapid,
                            'temps' => affTemp(floor($temps)),
                            'deblok' => '<b>Vous ne pouvez pas attaquer sans un minimum de connaissances militaires !</b>',
                            'conso' => ceil($conso*$nbtrajet),
                            'tactique' => '',
                            'places' => $places
                        )
                    );
                header("X-JSON: ".$json->encode($datas));
                exit;
            } else {
                for ($i=1 ; $i<=$lvltechno ; $i++) {
                    if ($tactiquedef == $i) {
                        $tactique .= '<option value="'.$i.'" selected>'.txtTactique($i).'</option>';
                    } else {
                        $tactique .= '<option value="'.$i.'">'.txtTactique($i).'</option>';
                    }
                }
            }
            $tactique .= '</select><br />';
        }
        $SESS->values['flcds'] = $idPrep;
        $SESS->put();
        $datas = array(
                'root' => array(
                    'destination' => $destinRapid,
                    'temps' => affTemp(floor($temps)),
                    'deblok' => '<input type="hidden" name="cds" value="'.$idPrep.'" /><input type="submit" value="GO" class="submit" />',
                    'conso' => ceil($conso*2),
                    'tactique' => $tactique,
                    'places' => $places
                )
            );
    }

    $chapeau->deconnexion();
    header("X-JSON: ".$json->encode($datas));
}
