<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

/*

Run4Football v0.1
This file is part of Run4Football. (C)2019 Corrado Mulas - CM TLC - R&D Dept. - Ardara (SS) 

    Run4Football is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    Run4Football is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with Run4Football.  If not, see <http://www.gnu.org/licenses/>.

*/        

/*##########NOTE################

Inserire controlli corretta esecuzione, mediante return 

*/
############FINE NOTE###########
/**
 * Description of r4fb
 *
 * @author corradomulas for Run PoliTo - Corso Duca degli Abruzzi 24, 10129 Torino (TO)
 */

//GLOBS DB (MySQL/MariaDB only)
define('DBN', ""); //DB NAME
define('DBU', ""); //DB USER
define('DBH', ""); //DB HOST
define('DBP', ""); //DB PASSWORD

require_once 'sns.php';


class r4fb {
    
    
    //generazione UUIDv4:
    public function guidv4()
    {
        //Genera UUID v4
        $data = openssl_random_pseudo_bytes(16);
        assert(strlen($data) == 16);
    
        $data[6] = chr(ord($data[6]) & 0x0f | 0x40); 
        $data[8] = chr(ord($data[8]) & 0x3f | 0x80);
    
        return strtoupper(vsprintf('%s%s-%s-%s-%s-%s%s%s', str_split(bin2hex($data), 4)));
    }
    
    public function fetchUsers($guid)
    {
        //restituisce array con elenco partite dato un torneo
        
        //Connessione SQL
            $mysqli = new mysqli(DBH, DBU, DBP, DBN);
        //Query: SELECT * FROM `partite` WHERE torneo = ? ,dove torneo = $torneo
            $query = $mysqli->prepare("SELECT * FROM `utenti` WHERE id=?");
            $query->bind_param('s',$guid);
            $query->execute();
            $result = mysqli_stmt_get_result($query);
            
           $rows = array();
            while ($row = $result->fetch_assoc())
            {
                $rows[] = $row;
            }
            
     //       $rows = $query->fetch_assoc();
        //ultima operazione: chiusura connessione DB
                        
      $query->close();      
            return $rows;
      
    }
    
    //inserimento torneo:
    public function insTorneo($tsinizio,$nome,$org,$loc,$man,$nsq,$ngi)
    {
        //query SQL + prepared statement
        //query INSERT: 
        //INSERT INTO `torneo`(`id`, `t`, `organizzazione`, `location`, `manager`) VALUES (,,,,)
        
        //Connessione SQL
            $mysqli = new mysqli(DBH, DBU, DBP, DBN);
            $id = r4fb::guidv4();
        //query SQL + prepared statement
            $query = $mysqli->prepare("INSERT INTO `torneo`(`id`,`nome`,`t`, `organizzazione`, `location`, `manager`, `nsquadre`, `ngironi`) VALUES (?,?,?,?,?,?,?,?)");
            $query->bind_param('ssisssii',$id,$nome,$tsinizio,$org,$loc,$man,$nsq,$ngi);
            $query->execute();
            $letter = 'A';
            
            for($i=0; $i < $ngi; $i++)
            {
                $query = $mysqli->prepare("INSERT INTO `gironi`(`id`, `torneo`, `lettera`) VALUES (?,?,?)");
                $query->bind_param('sss', r4fb::guidv4(),$id,$letter);
                $query->execute();
                
                $letterAscii = ord($letter);
                $letterAscii++;
                $letter = chr($letterAscii); // 'B'
            }

        //ultima operazione: chiusura connessione DB
        $query->close();
        return 1;
    }


    //inserimento arbitro:
    public function insArb($nome, $torneo, $thumb, $email, $num)
    {
        //query SQL + prepared statement
        //query INSERT: 
        //INSERT INTO `arbitri`(`id`, `amm`, `nome`, `valutazione`, `path_thumb`, `torneo`) VALUES (,,,,,)
        //INSERT INTO `utenti`(`id`, `matr`, `tc`, `nome`, `cognome`, `tm`, `tipo`) VALUES ([value-1],[value-2],[value-3],[value-4],[value-5],[value-6],[value-7])
        //INSERT INTO `users`(`uid`, `guid`, `gid`, `password`, `salt`, `givenName`, `email`, `eduPersonPrincipalName`, `isEnabled`) VALUES ()
        //Connessione SQL
            $mysqli = new mysqli(DBH, DBU, DBP, DBN);
            $id = r4fb::guidv4();
            $pass = bin2hex(openssl_random_pseudo_bytes(4));
            $salt = bin2hex(openssl_random_pseudo_bytes(20));
            $pass_ha = hash('sha256',$salt.$pass);
            $matr = "R".str_pad(mt_rand(0, 9999), 4, '0', STR_PAD_LEFT);
        //query SQL + prepared statement
            $time = time();
            $query = $mysqli->prepare("INSERT INTO `utenti`(`id`, `matr`, `tc`, `nome`, `tm`, `tipo`) VALUES (?,?,?,?,?,3)");
            $query->bind_param('ssisi',$id,$matr,$time,$nome,$time);
            $query->execute();
            

            
            $query = $mysqli->prepare("INSERT INTO `arbitri`(`id`, `nome`, `path_thumb`, `torneo`) VALUES (?,?,?,?)");
            $query->bind_param('siss',$id,$nome,$thumb,$torneo);
            $query->execute();
        
        //ultima operazione: chiusura connessione DB
        $query->close();
        
            $mysqli = new mysqli(DBH, "", "", "");
            $query = $mysqli->prepare("INSERT INTO `users`(`uid`, `guid`, `password`, `salt`, `givenName`, `email`, `eduPersonPrincipalName`, `isEnabled`) VALUES (?,?,?,?,?,?,?,1)");
            $query->bind_param('sssssss',$matr,$id,$pass_ha,$salt,$nome,$email,$nome);
            $query->execute();
            echo mysqli_error($mysqli);
            
            $query->close();
        $msg = "Credenziali RUN IdP:\r\n"
                . "User: ".$matr."\r\n"
                . "Password: ".$pass."\r\n"
                . "Valide per: run4football";
        snsrun::sendSMS($num, $msg);
        return 1;
    }
    //inserimento squadra:
    public function insSq($torneo, $n, $nome, $colore, $npls, $girone)
    {
        //query SQL + prepared statement
        //query INSERT: 
        //INSERT INTO `squadre`(`id`, `nome`, `colore`, `pt`, `valutazione`, `torneo`) VALUES (,,,,,)
        
                //Connessione SQL
            $mysqli = new mysqli(DBH, DBU, DBP, DBN);
            $id = r4fb::guidv4();
        //query SQL + prepared statement
            $query = $mysqli->prepare("INSERT INTO `squadre`(`id`,`n`, `nome`, `colore`,`nplayers`, `torneo`,`girone`) VALUES (?,?,?,?,?,?,?)");
            $query->bind_param('sississ',$id,$n,$nome,$colore,$npls,$torneo,$girone);
            $query->execute();
        
        //ultima operazione: chiusura connessione DB
        $query->close();
        return 1;
    }    
    //inserimento giocatore:
    public function insPlayer($num, $ruolo, $nome, $thumb, $squadra, $email)
    {
        //query SQL + prepared statement
        //query INSERT: 
        //INSERT INTO `giocatori`(`id`, `n`, `ruolo`, `goal`, `gialli`, `rossi`, `valutazione`, `nome`, `path_thumb`, `squadra`) VALUES (,,,,,,,,,)
        
        //Connessione SQL
            $mysqli = new mysqli(DBH, DBU, DBP, DBN);
            $id = r4fb::guidv4();
            
            $pass = bin2hex(openssl_random_pseudo_bytes(4));
            $salt = bin2hex(openssl_random_pseudo_bytes(20));
            $pass_ha = hash('sha256',$salt.$pass);
            $matr = "P".str_pad(mt_rand(0, 9999), 4, '0', STR_PAD_LEFT);
        //query SQL + prepared statement
            $time = time();
            $query = $mysqli->prepare("INSERT INTO `utenti`(`id`, `matr`, `tc`, `nome`, `tm`, `tipo`) VALUES (?,?,?,?,?,4)");
            $query->bind_param('ssisi',$id,$matr,$time,$nome,$time);
            $query->execute();
            
        //query SQL + prepared statement
            $query = $mysqli->prepare("INSERT INTO `giocatori`(`id`, `n`, `ruolo`, `nome`, `path_thumb`, `squadra`) VALUES (?,?,?,?,?,?)");
            $query->bind_param('sissss',$id,$num,$ruolo,$nome,$thumb,$squadra);
            $query->execute();
        
        //ultima operazione: chiusura connessione DB
        $query->close();
        
            $mysqli = new mysqli(DBH, "", "", "");
            $query = $mysqli->prepare("INSERT INTO `users`(`uid`, `guid`, `password`, `salt`, `givenName`, `email`, `eduPersonPrincipalName`, `isEnabled`) VALUES (?,?,?,?,?,?,?,1)");
            $query->bind_param('sssssss',$matr,$id,$pass_ha,$salt,$nome,$email,$nome);
            $query->execute();
            echo mysqli_error($mysqli);
            
            $query->close();
        $msg = "Credenziali RUN IdP:\r\n"
                . "User: ".$matr."\r\n"
                . "Password: ".$pass."\r\n"
                . "Valide per: https://r-un.ml/6tco2";
        
        $sub = 'Credenziali accesso giocatori RUN4Football';
        $from = "idp@runpolito.ml";
        if(snsrun::sendEmail($email, $sub, $msg, $from))
        {
                return 1;
        }
        else
        {
            return 0;
        }
        //mail($email, $subject, $msg, $headers);
      
        //return 1;
    }    
    //inserimento partita:
    public function insMatch($tProg, $s1, $s2, $arb, $torneo, $giornata, $campo, $tipo, $cat)
    {
        //Connessione SQL
            $mysqli = new mysqli(DBH, DBU, DBP, DBN);
            $id = r4fb::guidv4();
        //query SQL + prepared statement
        //query INSERT: 
        //INSERT INTO `partite`(`id`, `t_prog`, `t_start`, `t_stop`, `s1`, `s2`, `pt`, `falli`, `arb`, `torneo`) VALUES (,,,,,,,,)
            $query = $mysqli->prepare("INSERT INTO `partite`(`id`, `t_prog`, `s1`, `s2`, `arb`, `giornata`, `campo`, `torneo`,`tipo`, `cat`) VALUES (?,?,?,?,?,?,?,?,?,?)");
            $query->bind_param('sisssissii',$id,$tProg,$s1,$s2,$arb,$giornata,$campo,$torneo,$tipo,$cat);
            $query->execute();
        
        //ultima operazione: chiusura connessione DB
        $query->close();
        return 1;
    }    
    //EVENTI PARTITA
    
    public function insVote($bestpl,$bestsq,$bestrf,$commenti,$sid,$ip)
    {
        //Connessione SQL
            $mysqli = new mysqli(DBH, DBU, DBP, DBN);
            $id = r4fb::guidv4();
        //query SQL + prepared statement
        //query INSERT: 
        //INSERT INTO `partite`(`id`, `t_prog`, `t_start`, `t_stop`, `s1`, `s2`, `pt`, `falli`, `arb`, `torneo`) VALUES (,,,,,,,,)
            $query = $mysqli->prepare("INSERT INTO `voti`(`id`, `best_sq`, `best_pl`, `best_rf`, `sid`, `ip`, `comment`) VALUES (?,?,?,?,?,?,?)");
            $query->bind_param('sssssss',$id,$bestpl,$bestsq,$bestrf,$sid,$ip,$commenti);
            $query->execute();
        
        //ultima operazione: chiusura connessione DB
        $query->close();
        return 1;
    }    
    
    //sorteggio
    public function randStart($partita, $uid)
    {
        //sorteggio inizio
        //leggi ID squadre da s1,s2 e scegli uno dei due id in modo pseudo-random
            //Connessione SQL
            $mysqli = new mysqli(DBH, DBU, DBP, DBN);
            $query = $mysqli->prepare("SELECT * FROM `partite` WHERE id= ?");
            $query->bind_param('s',$partita);
            $result = $query->execute();
            $row = $result->fetch_array(MYSQLI_ASSOC);
            
            $s1 = $row['s1'];
            $s2 = $row['s2'];
            $sarray = compact($s1,$s2);
        
        //ultima operazione: chiusura connessione DB
        $query->close();
        
        return $sarray[rand(0,sizeof($sarray)-1)];
    }
    
    //START
    public function startMatch($partita, $uid)
    {
        if(!$partita)
        {
            return 0;
        }
        else
        {
            $tstart = time();
        //query SQL + prepared statement
        //query UPDATE per inserire T_START:
        //UPDATE `partite` SET `t_start`=[value-2] WHERE id = 'uid partita'
        //Connessione SQL
            $mysqli = new mysqli(DBH, DBU, DBP, DBN);
        
        //prepared statement
            $query = $mysqli->prepare("UPDATE `partite` SET `t_start`= ? WHERE id = ?");
            $query->bind_param('is',$tstart,$partita);
            $result = $query->execute();
            
            $query = $mysqli->prepare("UPDATE `arbitri` SET `curmatch`= ? WHERE id = ?");
            $query->bind_param('ss',$partita,$uid);
            $result = $query->execute();
        
        //ultima operazione: chiusura connessione DB
        $query->close();
        return 1;
        }
    }
    //inserimento goal
    public function insGoal($giocatore, $partita, $uid)
    {
        //$giocatore = guidV4 giocatore
        //$partita = guidV4 partita
        //ATTENZIONE: se partita non in corso, manda tutto in culo 
        //(query per controllo incrociato se t_stop != NULL (programmata) e !=1 (in corso), e t_start definito)
        //SELECT * FROM `partite` WHERE id='$partita' -> fetcha t_start e t_stop per controllo di cui sopra
        
        //Connessione SQL
            $mysqli = new mysqli(DBH, DBU, DBP, DBN);
        
        //prepared statement
            $query = $mysqli->prepare("SELECT * FROM `partite` WHERE id= ?");
            $query->bind_param('s',$partita);
            $query->execute();
            $result = mysqli_stmt_get_result($query);
            $row = $result->fetch_array(MYSQLI_ASSOC);
            $start = $row['t_start'];
            $stop = $row['t_stop'];
        
        //core if() statement per verifica di cui sopra
            if($start != NULL && $stop != 1 && $stop == NULL)
            {
        
                //query SQL + prepared statement
                //query UPDATE elenco goal + punteggio partita:
                //cerca giocatore + squadra, cerca partita, inserisci goal su tab goal e aggiorna punteggio squadra su partita
            
                //cerca giocatore e cerca squadra per capire se incrementare pt_s1 o pt_s2
                //controlla se 'squadra' in tab 'giocatori' = 's1' o 's2' su tab 'partite', se nessuno dei due = errore
                //SELECT * FROM `giocatori` WHERE id='$giocatore'
                    $query = $mysqli->prepare("SELECT * FROM `giocatori` WHERE id= ?");
                    $query->bind_param('s',$giocatore);
                    $query->execute();
                    $result = mysqli_stmt_get_result($query);
                    $row = $result->fetch_array(MYSQLI_ASSOC);
                    $squadra = $row['squadra'];
                //
                //fetcha id squadra da query prec. e inculagli il goal con una UPDATE su giocatori [STRONZATA, abbiamo l'id del giocatore porcoddio]
                //NON SERVE A UN CAZZO//UPDATE `squadre` SET `id`=[value-1],`nome`=[value-2],`colore`=[value-3],`pt`=[value-4], WHERE 1
                //UPDATE `giocatori` SET `goal`= goal + 1 WHERE id='$giocatore'
                    $query = $mysqli->prepare("UPDATE `giocatori` SET `goal`= goal + 1 WHERE id= ?");
                    $query->bind_param('s',$giocatore);
                    $query->execute();
            
                //ricerca dati squadra
                    $query = $mysqli->prepare("SELECT * FROM `partite` WHERE id= ?");
                    $query->bind_param('s',$partita);
                    $query->execute();
                    $result = mysqli_stmt_get_result($query);
                    $row = $result->fetch_array(MYSQLI_ASSOC);
                    $s1 = $row['s1'];
                    $s2 = $row['s2'];
                //
                //aggiorna punteggio partita (cerca se id squadra è s1 o s2 su tab partite, e poi aggiorna il punteggio su pt_s1 o pt_s2) 
                //UPDATE `partite` SET `pt_s1`='pt_s1+1' WHERE id='$partita'
                //UPDATE `partite` SET `pt_s2`='pt_s2+1' WHERE id='$partita'
                switch ($squadra) 
                {
                    case $s1:
                        $query = $mysqli->prepare("UPDATE `partite` SET `pt_s1`= pt_s1 + 1 WHERE id= ?");
                        $query->bind_param('s',$partita);
                        $query->execute();
                    break;
                    case $s2:
                        $query = $mysqli->prepare("UPDATE `partite` SET `pt_s2`= pt_s2 + 1 WHERE id= ?");
                        $query->bind_param('s',$partita);
                        $query->execute();
                    break;
                    default:
                        //errore;
                    break;
            }

        }
        else
        {
            //restituisci qualcosa per farmi capire che sono una testa di cazzo
        }
        //ultima operazione: chiusura connessione DB
        $query->close();
        return 1;
    }
    //inserimento fallo
    public function insFallo($squadra, $uid)
    {
        //Fallo squadra
        //query SQL + prepared statement
        //query UPDATE: 
        //UPDATE `partite` SET `falli`= falli + 1 WHERE id = ?
        //UPDATE `squadre` SET `falli`= falli + 1 WHERE id = ?
            $mysqli = new mysqli(DBH, DBU, DBP, DBN);
            $partita = r4fb::curMatch($uid);
            $query = $mysqli->prepare("UPDATE `partite` SET `falli`= falli + 1 WHERE id = ?");
            $query->bind_param('s',$partita);
            $query->execute(); 
            $query = $mysqli->prepare("UPDATE `squadre` SET `falli`= falli + 1 WHERE id = ?");
            $query->bind_param('s',$squadra);
            $query->execute(); 
            
            $query = $mysqli->prepare("SELECT * FROM `partite` WHERE id=?");
            $query->bind_param('s',$partita);
            $query->execute();
            $result = mysqli_stmt_get_result($query);
            
            $row = $result->fetch_assoc();
            
            if($squadra == $row['s1'])
            {
                $query = $mysqli->prepare("UPDATE `partite` SET `falli_s1`= falli_s1 + 1 WHERE id = ?");
                $query->bind_param('s',$partita);
                $query->execute();
            }
            else if($squadra == $row['s2'])
            {
                $query = $mysqli->prepare("UPDATE `partite` SET `falli_s2`= falli_s2 + 1 WHERE id = ?");
                $query->bind_param('s',$partita);
                $query->execute();
            }
        //ultima operazione: chiusura connessione DB
        $query->close();
        return 1;
    }
    //ammonizione
    public function insAmm($giocatore, $partita, $tipo, $uid)
    {
        
        //ATTENZIONE: $partita non utilizzato: controllare logica
        //
        //
        //parametro $tipo 1: giallo, 2: rosso
        //Ammonizione (giallo, rosso)
        //query SQL + prepared statement
        //query UPDATE:
        //UPDATE `giocatori` SET `gialli`=[value-5],`rossi`=[value-6] WHERE 1
        
        //Connessione SQL
            $mysqli = new mysqli(DBH, DBU, DBP, DBN);
        
        //inserimento ammonizione su tab giocatore mediante update
        switch ($tipo)
        {
            case 1:
                $query = $mysqli->prepare("UPDATE `giocatori` SET `gialli`= gialli + 1 WHERE id = ?");
                $query->bind_param('s',$giocatore);
                $query->execute();
            break;
            case 2:
                $query = $mysqli->prepare("UPDATE `giocatori` SET `rossi`= rossi + 1 WHERE id = ?");
                $query->bind_param('s',$giocatore);
                $query->execute();
            break;
            default:
                //errore
            break;
                
        }
         
        //ultima operazione: chiusura connessione DB
        $query->close();
        return 1;
    }
    //STOP
    public function stopMatch($partita, $uid)
    {
        //Prima di tutto definisci ts fine.
            $tsEnd = time();
        //TERMINE PARTITA
        //segna ts stop, aggiorna punteggi squadre in base a sq vincente/pareggio/perdente
        //Connessione SQL
            $mysqli = new mysqli(DBH, DBU, DBP, DBN);
        
        //UPDATE `partite` SET `t_stop`= ? WHERE id = ?
        //TERMINE PARTITA: upd ts
            $query = $mysqli->prepare("UPDATE `partite` SET `t_stop`= ? WHERE id = ?");
            $query->bind_param('ss',$tsEnd,$partita);
            $query->execute();     

        //logica punti classifica:
        //vinta +3pt, pari +1pt, persa 0
        //cerca partita, segna ts fine, fetcha squadre, confronta punteggi, cerca squadre, aggiorna punteggi squadre
            $query = $mysqli->prepare("SELECT * FROM `partite` WHERE id= ?");
            $query->bind_param('s',$partita);
            $query->execute();
            $result = mysqli_stmt_get_result($query);
            $row = $result->fetch_array(MYSQLI_ASSOC);
            
            $s1 = $row['s1'];
            $s2 = $row['s2'];
            $pt1 = $row['pt_s1'];
            $pt2 = $row['pt_s2'];
            $cat = $row['cat'];
            $tipo = $row['tipo'];
            
            /* cat:
             * 1 class gironi/generale
             * 2 class playoff
             * 3 class playout
             */
            
        //query generica
        //UPDATE `squadre` SET `pt`=[value-4] WHERE id = ?
            if($pt1 > $pt2)
            {
                //vince s1, segna +3 a s1
                $query = $mysqli->prepare("UPDATE `squadre` SET `pt`=pt + 3 WHERE id = ?");
                $query->bind_param('s',$s1);
                $query->execute();
                
                switch ($cat)
                {
                    case 1:
                        $query = $mysqli->prepare("UPDATE `squadre` SET `pt_gir`=pt_gir + 3 WHERE id = ?");
                        $query->bind_param('s',$s1);
                        $query->execute();
                        break;
                    case 2:
                        $query = $mysqli->prepare("UPDATE `squadre` SET `pt_poff`=pt_poff + 3 WHERE id = ?");
                        $query->bind_param('s',$s1);
                        $query->execute();                        
                        break;
                    case 3:
                        $query = $mysqli->prepare("UPDATE `squadre` SET `pt_pout`=pt_pout + 3 WHERE id = ?");
                        $query->bind_param('s',$s1);
                        $query->execute();                        
                        break;
                    default:
                        die();
                        break;
                }
            }
            else if($pt1 < $pt2)
            {
                //vince s2, segna +3 a s2
                $query = $mysqli->prepare("UPDATE `squadre` SET `pt`=pt + 3 WHERE id = ?");
                $query->bind_param('s',$s2);
                $query->execute();
                
                switch ($cat)
                {
                    case 1:
                        $query = $mysqli->prepare("UPDATE `squadre` SET `pt_gir`=pt_gir + 3 WHERE id = ?");
                        $query->bind_param('s',$s2);
                        $query->execute();
                        break;
                    case 2:
                        $query = $mysqli->prepare("UPDATE `squadre` SET `pt_poff`=pt_poff + 3 WHERE id = ?");
                        $query->bind_param('s',$s2);
                        $query->execute();                        
                        break;
                    case 3:
                        $query = $mysqli->prepare("UPDATE `squadre` SET `pt_pout`=pt_pout + 3 WHERE id = ?");
                        $query->bind_param('s',$s2);
                        $query->execute();                        
                        break;
                    default:
                        die();
                        break;
                }                
            }
            else if($pt1 == $pt2)
            {
                //pareggio, segna +1 a s1 e +1 a s2
                //s1:
                $query = $mysqli->prepare("UPDATE `squadre` SET `pt`=pt + 1 WHERE id = ?");
                $query->bind_param('s',$s1);
                $query->execute();
                
                //s2:
                $query = $mysqli->prepare("UPDATE `squadre` SET `pt`=pt + 1 WHERE id = ?");
                $query->bind_param('s',$s2);
                $query->execute();
                
                switch ($cat)
                {
                    case 1:
                        $query = $mysqli->prepare("UPDATE `squadre` SET `pt_gir`=pt_gir + 1 WHERE id = ?");
                        $query->bind_param('s',$s1);
                        $query->execute();
                        
                        $query = $mysqli->prepare("UPDATE `squadre` SET `pt_gir`=pt_gir + 1 WHERE id = ?");
                        $query->bind_param('s',$s2);
                        $query->execute();                        
                        break;
                    case 2:
                        $query = $mysqli->prepare("UPDATE `squadre` SET `pt_poff`=pt_poff + 1 WHERE id = ?");
                        $query->bind_param('s',$s1);
                        $query->execute();  
                        
                        $query = $mysqli->prepare("UPDATE `squadre` SET `pt_poff`=pt_poff + 1 WHERE id = ?");
                        $query->bind_param('s',$s2);
                        $query->execute();                          
                        break;
                    case 3:
                        $query = $mysqli->prepare("UPDATE `squadre` SET `pt_pout`=pt_pout + 1 WHERE id = ?");
                        $query->bind_param('s',$s1);
                        $query->execute();  
                        
                        $query = $mysqli->prepare("UPDATE `squadre` SET `pt_pout`=pt_pout + 1 WHERE id = ?");
                        $query->bind_param('s',$s2);
                        $query->execute();                          
                        break;
                    default:
                        die();
                        break;
                }                
            }
            
            $query = $mysqli->prepare("UPDATE `arbitri` SET `curmatch`= NULL WHERE id = ?");
            $query->bind_param('s',$uid);
            $query->execute();
        
        //ultima operazione: chiusura connessione DB
        $query->close();
        return 1;
    }
    
    public function fetchPartite($torneo, $uid)
    {
        //restituisce array con elenco partite dato un torneo
        
        //Connessione SQL
            $mysqli = new mysqli(DBH, DBU, DBP, DBN);
        //Query: SELECT * FROM `partite` WHERE torneo = ? ,dove torneo = $torneo
            $query = $mysqli->prepare("SELECT * FROM `partite` WHERE torneo=? AND arb=? AND t_stop = 0 ORDER BY t_prog ASC");
            $query->bind_param('ss',$torneo,$uid);
            $query->execute();
            $result = mysqli_stmt_get_result($query);
            
           $rows = array();
            while ($row = $result->fetch_assoc())
            {
                $rows[] = $row;
            }
            
     //       $rows = $query->fetch_assoc();
        //ultima operazione: chiusura connessione DB
                        
      $query->close();      
            return $rows;
      
    }
    
    public function fetchPlayers($squadra)
    {
        //restituisce array con elenco partite dato un torneo
        
        //Connessione SQL
            $mysqli = new mysqli(DBH, DBU, DBP, DBN);
        //Query: SELECT * FROM `partite` WHERE torneo = ? ,dove torneo = $torneo
            $query = $mysqli->prepare("SELECT * FROM `giocatori` WHERE squadra=? ORDER BY n ASC");
            $query->bind_param('s',$squadra);
            $query->execute();
            $result = mysqli_stmt_get_result($query);
            
           $rows = array();
            while ($row = $result->fetch_assoc())
            {
                $rows[] = $row;
            }
            
     //       $rows = $query->fetch_assoc();
        //ultima operazione: chiusura connessione DB
                        
      $query->close();      
            return $rows;
      
    }
    
    public function fetchArbs($tourn)
    {
        //restituisce array con elenco partite dato un torneo
        
        //Connessione SQL
            $mysqli = new mysqli(DBH, DBU, DBP, DBN);
        //Query: SELECT * FROM `partite` WHERE torneo = ? ,dove torneo = $torneo
            $query = $mysqli->prepare("SELECT * FROM `arbitri` WHERE torneo=?");
            $query->bind_param('s',$tourn);
            $query->execute();
            $result = mysqli_stmt_get_result($query);
            
           $rows = array();
            while ($row = $result->fetch_assoc())
            {
                $rows[] = $row;
            }
            
     //       $rows = $query->fetch_assoc();
        //ultima operazione: chiusura connessione DB
                        
      $query->close();      
            return $rows;
      
    }
    
    public function fetchTourneys()
    {
        //restituisce array con elenco partite dato un torneo
        
        //Connessione SQL
            $mysqli = new mysqli(DBH, DBU, DBP, DBN);
        //Query: SELECT * FROM `partite` WHERE torneo = ? ,dove torneo = $torneo
            $query = $mysqli->prepare("SELECT * FROM `torneo` WHERE 1 ORDER BY t DESC");
            //$query->bind_param('s',$squadra);
            $query->execute();
            $result = mysqli_stmt_get_result($query);
            
           $rows = array();
            while ($row = $result->fetch_assoc())
            {
                $rows[] = $row;
            }
            
     //       $rows = $query->fetch_assoc();
        //ultima operazione: chiusura connessione DB
                        
      $query->close();      
            return $rows;
      
    }
 
    public function fetchSquadreTourn($torneo)
    {
        //restituisce array con elenco partite dato un torneo
        
        //Connessione SQL
            $mysqli = new mysqli(DBH, DBU, DBP, DBN);
        //Query: SELECT * FROM `partite` WHERE torneo = ? ,dove torneo = $torneo
            $query = $mysqli->prepare("SELECT * FROM `squadre` WHERE torneo=? ORDER BY n ASC");
            $query->bind_param('s',$torneo);
            $query->execute();
            $result = mysqli_stmt_get_result($query);
            
           $rows = array();
            while ($row = $result->fetch_assoc())
            {
                $rows[] = $row;
            }
            
     //       $rows = $query->fetch_assoc();
        //ultima operazione: chiusura connessione DB
                        
      $query->close();      
            return $rows;
      
      
    }
    
    public function fetchArbsTourn($torneo)
    {
        //restituisce array con elenco partite dato un torneo
        
        //Connessione SQL
            $mysqli = new mysqli(DBH, DBU, DBP, DBN);
        //Query: SELECT * FROM `partite` WHERE torneo = ? ,dove torneo = $torneo
            $query = $mysqli->prepare("SELECT * FROM `arbitri` WHERE torneo=? ORDER BY nome ASC");
            $query->bind_param('s',$torneo);
            $query->execute();
            $result = mysqli_stmt_get_result($query);
            
           $rows = array();
            while ($row = $result->fetch_assoc())
            {
                $rows[] = $row;
            }
            
     //       $rows = $query->fetch_assoc();
        //ultima operazione: chiusura connessione DB
                        
      $query->close();      
            return $rows;
      
      
    }
    public function fetchSquadre($matchid)
    {
        //restituisce array con elenco partite dato un torneo
        
        //Connessione SQL
            $mysqli = new mysqli(DBH, DBU, DBP, DBN);
        //Query: SELECT * FROM `partite` WHERE torneo = ? ,dove torneo = $torneo
            $query = $mysqli->prepare("SELECT * FROM `partite` WHERE id=?");
            $query->bind_param('s',$matchid);
            $query->execute();
            $result = mysqli_stmt_get_result($query);
            
            $row = $result->fetch_assoc();
            //ultima operazione: chiusura connessione DB
                        
      $query->close();      
            return $row;
      
    }
    
    public function curMatch($uid)
    {
        //restituisce array con elenco partite dato un torneo
        
        //Connessione SQL
            $mysqli = new mysqli(DBH, DBU, DBP, DBN);
        //Query: SELECT * FROM `partite` WHERE torneo = ? ,dove torneo = $torneo
            $query = $mysqli->prepare("SELECT * FROM `arbitri` WHERE id=?");
            $query->bind_param('s',$uid);
            $query->execute();
            $result = mysqli_stmt_get_result($query);
            $row = $result->fetch_array(MYSQLI_ASSOC);
           
            
     //       $rows = $query->fetch_assoc();
        //ultima operazione: chiusura connessione DB
                        
      $query->close();      
            return $row['curmatch'];
      
    }
    
    public function curTourn($uid)
    {
        //restituisce array con elenco partite dato un torneo
        
        //Connessione SQL
            $mysqli = new mysqli(DBH, DBU, DBP, DBN);
        //Query: SELECT * FROM `partite` WHERE torneo = ? ,dove torneo = $torneo
            $query = $mysqli->prepare("SELECT * FROM `arbitri` WHERE id=?");
            $query->bind_param('s',$uid);
            $query->execute();
            $result = mysqli_stmt_get_result($query);
            $row = $result->fetch_array(MYSQLI_ASSOC);
           
            
     //       $rows = $query->fetch_assoc();
        //ultima operazione: chiusura connessione DB
                        
      $query->close();      
            return $row['torneo'];
      
    }
    
    public function tournData($torneo)
    {
        //restituisce array con elenco partite dato un torneo
        
        //Connessione SQL
            $mysqli = new mysqli(DBH, DBU, DBP, DBN);
        //Query: SELECT * FROM `partite` WHERE torneo = ? ,dove torneo = $torneo
            $query = $mysqli->prepare("SELECT * FROM `torneo` WHERE id=?");
            $query->bind_param('s',$torneo);
            $query->execute();
            $result = mysqli_stmt_get_result($query);
            $row = $result->fetch_array(MYSQLI_ASSOC);
           
            
     //       $rows = $query->fetch_assoc();
        //ultima operazione: chiusura connessione DB
                        
      $query->close();      
            return $row;
      
    }
    
    public function getFalli($sid)
    {
        //restituisce array con elenco partite dato un torneo
        
        //Connessione SQL
            $mysqli = new mysqli(DBH, DBU, DBP, DBN);
        //Query: SELECT * FROM `partite` WHERE torneo = ? ,dove torneo = $torneo
            $query = $mysqli->prepare("SELECT * FROM `squadre` WHERE id=?");
            $query->bind_param('s',$sid);
            $query->execute();
            $result = mysqli_stmt_get_result($query);
            $row = $result->fetch_array(MYSQLI_ASSOC);
           
            
     //       $rows = $query->fetch_assoc();
        //ultima operazione: chiusura connessione DB
                        
      $query->close();      
            return $row['falli'];
      
    }
    
    public function getFalliSq($sid)
    {
        //restituisce array con elenco partite dato un torneo
        
        //Connessione SQL
            $mysqli = new mysqli(DBH, DBU, DBP, DBN);
        //Query: SELECT * FROM `partite` WHERE torneo = ? ,dove torneo = $torneo
            $query = $mysqli->prepare("SELECT * FROM `partite` WHERE id=?");
            $query->bind_param('s',$sid);
            $query->execute();
            $result = mysqli_stmt_get_result($query);
            $row = $result->fetch_array(MYSQLI_ASSOC);
           $query->close(); 
           
            if($sid == $row['s1'])
            {
                return $row['falli_s1'];
            }
            else if($sid == $row['s2'])
            {
                return $row['falli_s2'];
            }      
    }
    
    public function getPoints($mid,$sn)
    {
        //restituisce array con elenco partite dato un torneo
        
        //Connessione SQL
            $mysqli = new mysqli(DBH, DBU, DBP, DBN);
        //Query: SELECT * FROM `partite` WHERE torneo = ? ,dove torneo = $torneo
            $query = $mysqli->prepare("SELECT * FROM `partite` WHERE id=?");
            $query->bind_param('s',$mid);
            $query->execute();
            $result = mysqli_stmt_get_result($query);
            $row = $result->fetch_array(MYSQLI_ASSOC);
           
            
     //       $rows = $query->fetch_assoc();
        //ultima operazione: chiusura connessione DB
                        
      $query->close();  
      
      if($sn == 1)
      {
            return $row['pt_s1'];
      }
      else if($sn == 2)
      {
          return $row['pt_s2'];
      }
    }
    
    public function isRigore($sid)
    {
        //restituisce array con elenco partite dato un torneo
        
        //Connessione SQL
            $mysqli = new mysqli(DBH, DBU, DBP, DBN);
        //Query: SELECT * FROM `partite` WHERE torneo = ? ,dove torneo = $torneo
            $query = $mysqli->prepare("SELECT * FROM `squadre` WHERE id=?");
            $query->bind_param('s',$sid);
            $query->execute();
            $result = mysqli_stmt_get_result($query);
            $row = $result->fetch_array(MYSQLI_ASSOC);
           
            
     //       $rows = $query->fetch_assoc();
        //ultima operazione: chiusura connessione DB
                        
     
      
      if($row['rigori'] == 0)
      {
          if($row['falli'] == 5)
          {
            $query = $mysqli->prepare("UPDATE `squadre` SET `rigori`=rigori + 1 WHERE id = ?");
            $query->bind_param('s',$sid);
            $query->execute();
            return 1;
          }
          else
          {
              return 0;
          }
      }
      else
      {
        $div = $row['falli']/$row['rigori'];
        if($div == 5)
        {
            $query = $mysqli->prepare("UPDATE `squadre` SET `rigori`=rigori + 1 WHERE id = ?");
            $query->bind_param('s',$sid);
            $query->execute();
            return 1;
        }
        else
        {
            return 0;
        }
      } 
      $query->close(); 
    }
    
    public function nSquadre($torneo)
    {
        //restituisce array con elenco partite dato un torneo
        
        //Connessione SQL
            $mysqli = new mysqli(DBH, DBU, DBP, DBN);
        //Query: SELECT * FROM `partite` WHERE torneo = ? ,dove torneo = $torneo
            $query = $mysqli->prepare("SELECT * FROM `torneo` WHERE id=?");
            $query->bind_param('s',$torneo);
            $query->execute();
            $result = mysqli_stmt_get_result($query);
            $row = $result->fetch_array(MYSQLI_ASSOC);
           
            
     //       $rows = $query->fetch_assoc();
        //ultima operazione: chiusura connessione DB
                        
      $query->close();      
            return $row['nsquadre'];
      
    }
    
    public function nPlayers($squadra)
    {
        //restituisce array con elenco partite dato un torneo
        
        //Connessione SQL
            $mysqli = new mysqli(DBH, DBU, DBP, DBN);
        //Query: SELECT * FROM `partite` WHERE torneo = ? ,dove torneo = $torneo
            $query = $mysqli->prepare("SELECT * FROM `squadre` WHERE id=?");
            $query->bind_param('s',$squadra);
            $query->execute();
            $result = mysqli_stmt_get_result($query);
            $row = $result->fetch_array(MYSQLI_ASSOC);
           
            
     //       $rows = $query->fetch_assoc();
        //ultima operazione: chiusura connessione DB
                        
      $query->close();      
            return $row['nplayers'];
      
    }
    
    public function fetchGironi($tourn)
    {
        //restituisce array con elenco partite dato un torneo
        
        //Connessione SQL
            $mysqli = new mysqli(DBH, DBU, DBP, DBN);
        //Query: SELECT * FROM `partite` WHERE torneo = ? ,dove torneo = $torneo
            $query = $mysqli->prepare("SELECT * FROM `gironi` WHERE torneo=? ORDER BY lettera ASC");
            $query->bind_param('s',$tourn);
            $query->execute();
            $result = mysqli_stmt_get_result($query);
            
           $rows = array();
            while ($row = $result->fetch_assoc())
            {
                $rows[] = $row;
            }
            
     //       $rows = $query->fetch_assoc();
        //ultima operazione: chiusura connessione DB
                        
      $query->close();      
            return $rows;
      
    }
    
    public function fetchClassGrn($tourn, $grn)
    {
        //restituisce array con elenco partite dato un torneo
        
        //Connessione SQL
            $mysqli = new mysqli(DBH, DBU, DBP, DBN);
        //Query: SELECT * FROM `partite` WHERE torneo = ? ,dove torneo = $torneo
            $query = $mysqli->prepare("SELECT * FROM `squadre` WHERE torneo=? AND girone=? ORDER BY pt_gir DESC");
            $query->bind_param('ss',$tourn,$grn);
            $query->execute();
            $result = mysqli_stmt_get_result($query);
            
           $rows = array();
            while ($row = $result->fetch_assoc())
            {
                $rows[] = $row;
            }
            
     //       $rows = $query->fetch_assoc();
        //ultima operazione: chiusura connessione DB
                        
      $query->close();      
            return $rows;
      
    }
    
    public function fetchClassPoff($tourn, $tipo)
    {
        //restituisce array con elenco partite dato un torneo
                /*<option value="1">Gironi</option>
                                <option value="2">Ottavi</option>
                                <option value="3">Quarti</option>
                                <option value="4">Semifinali</option>
                                <option value="5">Finale</option>*/
        //Connessione SQL
        //Connessione SQL
            $mysqli = new mysqli(DBH, DBU, DBP, DBN);
        //Query: SELECT * FROM `partite` WHERE torneo = ? ,dove torneo = $torneo
            
        switch($tipo)    
        {
            default:
                $query = $mysqli->prepare("SELECT * FROM `squadre` WHERE torneo=? ORDER BY pt_poff DESC");
            break;
            case 2:
                $query = $mysqli->prepare("SELECT * FROM `squadre` WHERE torneo=? AND tipo=2 ORDER BY pt_poff DESC");
            break;
            case 3:
                $query = $mysqli->prepare("SELECT * FROM `squadre` WHERE torneo=? AND tipo=3 ORDER BY pt_poff DESC");
            break;
            case 4:
                $query = $mysqli->prepare("SELECT * FROM `squadre` WHERE torneo=? AND tipo=4 ORDER BY pt_poff DESC");
            break;
            case 5:
                $query = $mysqli->prepare("SELECT * FROM `squadre` WHERE torneo=? AND tipo=5 ORDER BY pt_poff DESC");
            break;
        }            
            $query->bind_param('s',$tourn);
            $query->execute();
            $result = mysqli_stmt_get_result($query);
            
           $rows = array();
            while ($row = $result->fetch_assoc())
            {
                $rows[] = $row;
            }
            
     //       $rows = $query->fetch_assoc();
        //ultima operazione: chiusura connessione DB
                        
      $query->close();      
            return $rows;
      
    }
    
    public function fetchClassPout($tourn,$tipo)
    {
        //restituisce array con elenco partite dato un torneo
        /*<option value="1">Gironi</option>
                                <option value="2">Ottavi</option>
                                <option value="3">Quarti</option>
                                <option value="4">Semifinali</option>
                                <option value="5">Finale</option>*/
        //Connessione SQL
            $mysqli = new mysqli(DBH, DBU, DBP, DBN);
        //Query: SELECT * FROM `partite` WHERE torneo = ? ,dove torneo = $torneo
        switch($tipo)    
        {
            default:
                $query = $mysqli->prepare("SELECT * FROM `squadre` WHERE torneo=? ORDER BY pt_pout DESC");
            break;
            case 2:
                $query = $mysqli->prepare("SELECT * FROM `squadre` WHERE torneo=? AND tipo=2 ORDER BY pt_pout DESC");
            break;
            case 3:
                $query = $mysqli->prepare("SELECT * FROM `squadre` WHERE torneo=? AND tipo=3 ORDER BY pt_pout DESC");
            break;
            case 4:
                $query = $mysqli->prepare("SELECT * FROM `squadre` WHERE torneo=? AND tipo=4 ORDER BY pt_pout DESC");
            break;
            case 5:
                $query = $mysqli->prepare("SELECT * FROM `squadre` WHERE torneo=? AND tipo=5 ORDER BY pt_pout DESC");
            break;
        }
            $query->bind_param('s',$tourn);
            $query->execute();
            $result = mysqli_stmt_get_result($query);
            
           $rows = array();
            while ($row = $result->fetch_assoc())
            {
                $rows[] = $row;
            }
            
     //       $rows = $query->fetch_assoc();
        //ultima operazione: chiusura connessione DB
                        
      $query->close();      
            return $rows;
      
    }
    
    public function fetchClassCC($tourn)
    {
        //restituisce array con elenco partite dato un torneo
        
        //Connessione SQL
            $mysqli = new mysqli(DBH, DBU, DBP, DBN);
        //Query: SELECT * FROM `partite` WHERE torneo = ? ,dove torneo = $torneo
            $query = $mysqli->prepare("SELECT * FROM `giocatori` WHERE 1 ORDER BY goal DESC");
        //    $query->bind_param('s',$tourn);
            $query->execute();
            $result = mysqli_stmt_get_result($query);
            
           $rows = array();
            while ($row = $result->fetch_assoc())
            {
                $rows[] = $row;
            }
            
     //       $rows = $query->fetch_assoc();
        //ultima operazione: chiusura connessione DB
                        
      $query->close();      
            return $rows;
      
    }
    
    public function fetchClass($tourn)
    {
        //restituisce array con elenco partite dato un torneo
        
        //Connessione SQL
            $mysqli = new mysqli(DBH, DBU, DBP, DBN);
        //Query: SELECT * FROM `partite` WHERE torneo = ? ,dove torneo = $torneo
            $query = $mysqli->prepare("SELECT * FROM `squadre` WHERE torneo=? ORDER BY pt DESC");
            $query->bind_param('s',$tourn);
            $query->execute();
            $result = mysqli_stmt_get_result($query);
            
           $rows = array();
            while ($row = $result->fetch_assoc())
            {
                $rows[] = $row;
            }
            
     //       $rows = $query->fetch_assoc();
        //ultima operazione: chiusura connessione DB
                        
      $query->close();      
            return $rows;
      
    }
    
    public function togglePls($chkbx,$s1,$s2)
    {
            $mysqli = new mysqli(DBH, DBU, DBP, DBN);
            
            $query = $mysqli->prepare("UPDATE `giocatori` SET `isActive`= 0 WHERE squadra= ?");
            $query->bind_param('s',$s1);
            $query->execute();

            $query = $mysqli->prepare("UPDATE `giocatori` SET `isActive`= 0 WHERE squadra= ?");
            $query->bind_param('s',$s2);
            $query->execute();
            
            $max = count($chkbx);
            for($i=0; $i<$max; $i++)
            {
                $id = $chkbx[$i];
                $query = $mysqli->prepare("UPDATE `giocatori` SET `isActive`=1 WHERE id = ?");
                $query->bind_param('s',$id);
                $query->execute();
            }
            
         /*   $max2 = count($chkbx2);
            for($j=0; $j<$max2; $j++)
            {
                $id2 = $chkbx2[$j];
                $query = $mysqli->prepare("UPDATE `giocatori` SET `isActive`=1 WHERE id = ?");
                $query->bind_param('s',$id2);
                $query->execute();
            }*/
            
        /*    $query = $mysqli->prepare("UPDATE `giocatori` SET `isActive`= 1 WHERE id = ? AND squadra= ?");
            $query->bind_param('iss',$status,$uid,$squadra);
            $query->execute(); */
                       
        //ultima operazione: chiusura connessione DB
        $query->close();
        return 1;
    }
    
    public function fetchSquadraData($squadra)
    {
        //restituisce array con elenco partite dato un torneo
        
        //Connessione SQL
            $mysqli = new mysqli(DBH, DBU, DBP, DBN);
        //Query: SELECT * FROM `partite` WHERE torneo = ? ,dove torneo = $torneo
            $query = $mysqli->prepare("SELECT * FROM `squadre` WHERE id=?");
            $query->bind_param('s',$squadra);
            $query->execute();
            $result = mysqli_stmt_get_result($query);
            
           $rows = array();
            while ($row = $result->fetch_assoc())
            {
                $rows[] = $row;
            }
            
     //       $rows = $query->fetch_assoc();
        //ultima operazione: chiusura connessione DB
                        
      $query->close();      
            return $rows;
      
      
    }
    
    public function proxMatches($tourn)
    {
        //restituisce array con elenco partite dato un torneo
        
        //Connessione SQL
            $mysqli = new mysqli(DBH, DBU, DBP, DBN);
            $ts = time();
        //Query: SELECT * FROM `partite` WHERE torneo = ? ,dove torneo = $torneo
            $query = $mysqli->prepare("SELECT * FROM `partite` WHERE torneo=? AND t_start=0 AND t_prog > ? ORDER BY t_prog ASC");
            //$query = $mysqli->prepare("SELECT * FROM `partite` WHERE torneo=? AND t_start=0 ORDER BY t_prog DESC");
            $query->bind_param('si',$tourn,$ts);
            //$query->bind_param('s',$tourn);
            $query->execute();
            $result = mysqli_stmt_get_result($query);
            
           $rows = array();
            while ($row = $result->fetch_assoc())
            {
                $rows[] = $row;
            }
            
     //       $rows = $query->fetch_assoc();
        //ultima operazione: chiusura connessione DB
                        
      $query->close();      
            return $rows;
      
    }
    
    public function curMatches($tourn)
    {
        //restituisce array con elenco partite dato un torneo
        
        //Connessione SQL
            $mysqli = new mysqli(DBH, DBU, DBP, DBN);
            $ts = time();
        //Query: SELECT * FROM `partite` WHERE torneo = ? ,dove torneo = $torneo
            $query = $mysqli->prepare("SELECT * FROM `partite` WHERE torneo=? AND t_start > 0 AND t_stop=0 ORDER BY t_start ASC");
            $query->bind_param('s',$tourn);
            $query->execute();
            $result = mysqli_stmt_get_result($query);
            
           $rows = array();
            while ($row = $result->fetch_assoc())
            {
                $rows[] = $row;
            }
            
     //       $rows = $query->fetch_assoc();
        //ultima operazione: chiusura connessione DB
                        
      $query->close();      
            return $rows;
      
    }
    
    public function toggleVote($trn, $status)
    {
        //Connessione SQL
            $mysqli = new mysqli(DBH, DBU, DBP, DBN);
            if($status == 1)
            {
                $query = $mysqli->prepare("UPDATE `torneo` SET `voteStatus`= 1 WHERE id = ?");
            }
            else if($status == 2)
            {
                $query = $mysqli->prepare("UPDATE `torneo` SET `voteStatus`= 2 WHERE id = ?");
            }
            else
            {
                die();
            }
                $query->bind_param('s',$trn);
                $query->execute();
                $query->close();      
            return 1;
      
    }
    
    public function TTrcvdMsgs($guid, $tipo)
    {        
        //Connessione SQL
            $mysqli = new mysqli(DBH, DBU, DBP, DBN);
        //Query: SELECT * FROM `partite` WHERE torneo = ? ,dove torneo = $torneo
        switch ($tipo)
        {
            case 0:
                $query = $mysqli->prepare("SELECT * FROM `messaggi` WHERE recipient=? ORDER BY ts_sent DESC");
                break;
            case 1:
                $query = $mysqli->prepare("SELECT * FROM `messaggi` WHERE recipient=? AND ts_read= 0 ORDER BY ts_sent DESC");
                break;
            case 2:
                $query = $mysqli->prepare("SELECT * FROM `messaggi` WHERE recipient=? AND ts_read > 0 ORDER BY ts_sent DESC");
                break;
        }
           // $query = $mysqli->prepare("SELECT * FROM `messaggi` WHERE recipient=? ORDER BY ts_sent DESC");
            $query->bind_param('s',$guid);
            $query->execute();
            $result = mysqli_stmt_get_result($query);
            
           $rows = array();
            while ($row = $result->fetch_assoc())
            {
                $rows[] = $row;
            }
            
     //       $rows = $query->fetch_assoc();
        //ultima operazione: chiusura connessione DB
                        
      $query->close();      
            return $rows;
      
      
    }
}

 
