//creo gli oggetti necessari
$db = new database();
$json = new json();
$response = new response();

//parso l’intero array $_POST per adattarsi al database
foreach($_POST as $ind => $v)
$_POST[$ind] = mysql_escape_string(htmlspecialchars($_POST[$ind]));

switch($_POST['action']) {

  case "login":
    $nick = $_POST['nick'];
    $time = time();
    $query = "INSERT INTO xchat_users VALUES (MD5('$time'),'$nick', NOW() + INTERVAL 5 SECOND)";
    $db->doQuery($query);
    $query = "SELECT id FROM xchat_users WHERE id = MD5('$time')";
    $res = $db->doQuery($query);
    $id = $res[0]['id'];
    $response->setSessionId($id);
    $response->setAllUtenti();
    $response->setLastId();
  break;

  case "sendMex":
    $userId = $_POST['userId'];
    $mex = $_POST['mex'];
    $lastMex = $_POST['lastMex'];
    updateMyTimeout($userId);
    $query = "SELECT nick FROM xchat_users WHERE id = '$userId'";
    $rrr = $db->doQuery($query);
    $nick = $rrr[0]['nick'];
    $query = "INSERT INTO xchat_mex (nick, mex,t) VALUES ('$nick','$mex',NOW())";
    $db->doQuery($query);
    $response->setAllUtenti();
    $response->setLastId();
    $response->setAllMessaggi($lastMex);
  break;
  case "refresh":
    $userId = $_POST['userId'];
    $lastMex = $_POST['lastMex'];
    updateMyTimeout($userId);
    $response->setAllUtenti();
    $response->setLastId();
    $response->setAllMessaggi($lastMex);
  break;

  //stampo l’oggetto response encodato e chiudo la connessione al db
  echo $json->encode($response);
  $db->close();
}