<?php
//Fichier appelé pour afficher l'application

$p = strtolower(gpc("p"));
$nom = trim(utf8_decode(utf8_encode(strtolower(gpc("nom", "post")))));
$ligne = trim(utf8_decode(utf8_encode(strtoupper(gpc("ligne", "post")))));

//sleep(5);

if ($p == "liste")
{
    $bdd = new BDD();
    $req = $bdd->query("SELECT * FROM gspc;");
    $req["nombre"] = $bdd->num_rows;
    $bdd->deconnexion();

    $xml_pc = $xml->createElement("liste");
    foreach($req as $ligne)
    {
        if (!empty($ligne["reftable"]))
	{
	    $portecle = $xml->createElement("porteclef");
	    $portecle->setAttribute("id", $ligne["reftable"]);
	    $portecle->setAttribute("nom", $ligne["nom"]);
	    $portecle->setAttribute("caracteristique", ucfirst($ligne["caracteristique"]));
	    $portecle->setAttribute("ligne", $ligne["ligne"]);
	    $portecle->setAttribute("special", $ligne["special"]);
	    $xml_pc->appendChild($portecle);
	}
    }
    $xml_root->appendChild($xml_pc);
}
elseif ($p == "stats")
{
    $bdd = new BDD();
    $req = $bdd->query("SELECT ligne, COUNT(reftable) AS nombre FROM `gspc` GROUP BY ligne ORDER BY ligne ASC;");
    $bdd->deconnexion();

    $xml_pc = $xml->createElement("statistiques");
    foreach($req as $ligne)
    {
        $portecle = $xml->createElement("ligne");
	$portecle->setAttribute("nom", $ligne["ligne"]);
	$portecle->setAttribute("nombre", $ligne["nombre"]);
	$xml_pc->appendChild($portecle);
    }
    $xml_root->appendChild($xml_pc);
}
elseif ($p == "del" && $id = intval(gpc("id", "post")))
{
    $bdd = new BDD();
    $bdd->query("DELETE FROM `gspc` WHERE reftable = $id;");
    $req = $bdd->unique_query("SELECT COUNT(reftable) AS nombre FROM gspc");
    $bdd->deconnexion();
}
elseif (!empty($nom) && !empty($ligne))
{
    $carac = trim(utf8_decode(utf8_encode(gpc("caracteristique", "post"))));
    $quantite = intval(gpc("quantite", "post"));
    $id = intval(gpc("id"));

    $bdd = new BDD();
    $bdd->escape($nom);
    $bdd->escape($carac);
    $bdd->escape($ligne);
    if ($id)
      $bdd->query("UPDATE gspc SET nom = '$nom', caracteristique = '$carac', ligne = '$ligne', special = $quantite WHERE reftable = $id;");
    else
      $bdd->query("INSERT INTO gspc (nom, caracteristique, ligne, special) VALUES ('$nom', '$carac', '$ligne', $quantite);");
    $req = $bdd->unique_query("SELECT COUNT(reftable) AS nombre FROM gspc");
    $bdd->deconnexion();
}
else
{
    $bdd = new BDD();
    $req = $bdd->unique_query("SELECT COUNT(reftable) AS nombre FROM gspc");
    $bdd->deconnexion();
}

$xml_root->setAttribute("nombre", $req["nombre"]);
