<?php
//Gestion des dépendances
include_once("Class/tinyasteroide.php");

/***************************************************************************
 *                            class.user.php
 *                           ----------------
 *   begin                : Dimanche 7 septembre 2008
 *   update               : Vendredi 27 février 2009
 *   email                : nemunaire@gmail.com
 *
 *
 ***************************************************************************/
class User
{
    public $id_user;
    public $pseudo;
    public $auth_level;
    public $options;
    public $race;
    public $alliance;
    public $id_alliance;
    public $id_grade_alliance;
    public $permissions_alliance;
    public $mv;
    public $mail;
    public $envoyerMail;
    public $last_visite;
    public $points;
    public $place_points;
    public $technologies = array();
    public $credits;
    public $politique;
    public $politique_lastchange;
    public $destinationsFavoris;
    public $amis = array();
    public $combatAT_tactique;
    public $combatDE_tactique;
    public $modifUser = array();

    /**
     * Constructeur
     * @param    int	$id	id de la planète à importer
     *
     * @return   void
     * @access   public
     */
    public function User($id = 0)
    {
        if (!empty($id)) {
            global $technologiesVAR, $table_user;
            $bdd = new bdd();
            $bdd->escape($id);
            $user = $bdd->unique_query("SELECT * FROM $table_user WHERE id = $id;");
            $bdd->deconnexion();
            if (!empty($user)) {
                $this->id_user = $user["id"];
                $this->pseudo = $user["pseudo"];
                $this->auth_level = $user["auth_level"];
                $this->race = $user["race"];
                $this->options = @intval($user["options"]);
                $this->mv = $user["mv"];
                $this->id_alliance = $user["id_alliance"];
                $this->id_grade_alliance = $user["id_grade_alliance"];
                $this->mail = $user["mail"];
                $this->envoyerMail = $user["envoyerMail"];
                $this->last_visite = $user["last_visite"];
                $this->points = $user["points"];
                $this->place_points = $user["place_points"];
                $this->credits = $user["credits"];
                $this->politique = $user["politique"];
                $this->politique_lastchange = $user["politique_lastchange"];
                if (!empty($user["amis"])) {
                    $this->amis = unserialize($user["amis"]);
                } else {
                    $this->amis = array();
                }
                if (!empty($user["destinationsFavoris"])) {
                    $this->destinationsFavoris = unserialize($user["destinationsFavoris"]);
                } else {
                    $this->destinationsFavoris = array();
                }
                $this->combatAT_tactique = $user["combatAT_tactique"];
                $this->combatDE_tactique = $user["combatDE_tactique"];

                foreach ($technologiesVAR as $tech) {
                    $this->technologies[] = intval($user[$tech]);
                }

                //Si l'ID d'alliance est défini, on charge l'alliance
                if (!empty($this->id_alliance)) {
                    $this->alliance = new TinyAsteroide($this->id_alliance);
                }
            } else {
                die('Erreur #01 : Utilisateur recherché introuvable dans la base de données. Contactez le support technique ('.$config['mail_support'].') au plus vite en précisant le code d\'erreur.');
            }
        }
    }

    public function loadPermissions($fondateur = 0)
    {
        if ($fondateur == $this->id_user) {
            $this->permissions_alliance = 1023;
        } else {
            global $table_alliances_grade;
            $bdd = new BDD();
            $grade = $bdd->unique_query("SELECT * FROM $table_alliances_grade WHERE id = ".$this->id_grade_alliance.";");
            $bdd->deconnexion();

            $this->permissions_alliance = intval($grade['auth']);
        }
    }

    public function addPoints($metal, $cristal, $hydrogene, $credits = 0, $demolition = false)
    {
        /* Ancien code, fait des calculs boursier dans le système de points, wtf ?
        global $table_bourse_ressources;
        //On charge les 3 valeurs boursières
        $bdd = new BDD();
        $bourse = $bdd->query("SELECT dispo FROM $table_bourse_ressources;");
        $bdd->deconnexion();

        if (!empty($credits)) {
            //TODO Equivalence non prouvée entre $credits/bourse_calcPrixBase($bourse[0]["dispo"], 0.7); et $credits/bourse_calcPrixBase($bourse[0]["dispo"], 1) * 0.7; dans le but de ne donner que 70% des points
            $metal += $credits/bourse_calcPrixBase($bourse[0]["dispo"], 0.7);
            $cristal += $credits/bourse_calcPrixBase($bourse[1]["dispo"], 0.7);
            $hydrogene += $credits/bourse_calcPrixBase($bourse[2]["dispo"], 0.7);
        }

        $points = bourse_calcPrixBase($bourse[0]["dispo"], $metal);
        $points += bourse_calcPrixBase($bourse[1]["dispo"], $cristal);
        $points += bourse_calcPrixBase($bourse[2]["dispo"], $hydrogene);
        */
        $rate = 0.7;
        $points = $metal *$rate;
        $points += $cristal *$rate;
        $points += $hydrogene *$rate;

        if ($demolition) {
            $this->points -= intval($points);
        } else {
            $this->points += intval($points);
        }

        $this->addModifUser("points");
    }

    public function addCredits($credits)
    {
        $this->credits += $credits;
        $this->addModifUser("credits");

        return 0;
    }

    public function addModifUser($modif)
    {
        if (!in_array($modif, $this->modifUser)) {
            $this->modifUser[] = $modif;
        }
    }

    /**
     * Destructeur
     *
     * @return   void
     * @access   public
     */
    public function __destruct()
    {
        global $table_user;
        $out = array();
        $bdd = new BDD();
        foreach ($this->modifUser as $key => $modif) {
            //On gère les champs variables tableaux
            if (is_array($modif)) {
                $calc = dDonnees::nameVAR($modif[0]);

                if (!isset(${$calc.'VAR'})) {
                    global ${$calc.'VAR'};
                }
                if (empty(${$calc.'VAR'})) {
                    trigger_error('Impossible de trouver les données pour '.$modif[0], E_USER_ERROR);
                }

                $out[] = ${$calc.'VAR'}[$modif[1]]." = ".$this->{$modif[0]}[$modif[1]];
            } elseif ($modif == "force") {
                $out[] = " ";
            } elseif (!is_array($this->{$modif})) {
                $bdd->escape($this->{$modif});
                if (is_int($this->{$modif}) || is_float($this->{$modif})) {
                    $out[] .= $modif." = ".$this->{$modif};
                } else {
                    $out[] .= $modif." = '".$this->{$modif}."'";
                }
            } else {
                if ($modif != "coeff_bat" && $modif != "vaisseaux" && $modif != "terrestres" && $modif != "casernes" && $modif != "technologies" && $modif != "batiments") {
                    $prep = serialize($this->{$modif});
                    $bdd->escape($prep);
                    $out[] = $modif." = '$prep'";
                } else {
                    $calc = dDonnees::nameVAR($modif);

                    if (!isset(${$calc.'VAR'})) {
                        global ${$calc.'VAR'};
                    }

                    foreach ($this->{$modif} as $j => $value) {
                        $out[] = ${$calc.'VAR'}[$j]." = ".$value;
                    }
                }
            }
        }
        if (!empty($out)) {
            $sql = "UPDATE $table_user SET ".implode(', ', $out)." WHERE id = ".$this->id_user.";";
            if (DEBUG) {
                echo '<br /><br />'.$sql;
            }
            $bdd->query($sql);
            if ($bdd->affected() != 1) {
                elog($bdd->affected()." champ(s) affecté(s) par la requête du fichier ".__FILE__." à la ligne ".__LINE__.", données : out = ".serialize($out)." avec l'ID ".$this->id_user, 2);
            }
        }
        $bdd->deconnexion();
    }
}
