package Models.Client;

import Controllers.Client.ListeClient;
import Controllers.Dialog.ShowDialog;
import Controllers.Traitement.Adaptateur;
import Controllers.Traitement.ParametreSystem;
import Controllers.Traitement.contro;
import Models.connexion;
import java.io.UnsupportedEncodingException;
import java.sql.ResultSet;
import java.sql.SQLException;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

/**
 * @author Maher Ben Tili
 */
public class ClientDB {
    
    connexion cnx = new connexion();
    contro clt = new contro();
    ShowDialog SD = new ShowDialog();
    
    public boolean addClient(Client clt) throws UnsupportedEncodingException{
        String req = "INSERT INTO `client` (`codeclient`, `cin`, `nomcomplet`, `nom`, `prenom`, `naissance`, `telefix`, `telemobile`, `adresse`, `codepostale`, `mail`, `sexe`, `local_nom`, `date_add` ) VALUES ("+clt.getCodeclient()+", "+clt.getCin()+", '"+clt.getNomcomplet()+"', '"+clt.getNom()+"', '"+clt.getPrenom()+"', '"+clt.getNaissance()+"', "+clt.getTelefix()+", "+clt.getTelemobile()+", '"+clt.getAdresse()+"', "+clt.getCodepostal()+", '"+clt.getMail()+"', '"+clt.getSexe()+"', '"+ParametreSystem.NomLocalPC+"', CURTIME());";
        //System.out.println(req);
        if(cnx.ouverture()){
            try{
               int nbr = cnx.executionupdate(req);
               return true;
            }
            catch(SQLException ex){
                System.err.println("Erreur SQL ! \n"+ex.getMessage());
                return false ;
            }
        }
        else{
            return false ;
        }
    }
    
    public boolean updateClient(Client client) throws UnsupportedEncodingException
    {
        String req = "UPDATE `client`";
        req += "SET `cin` = '"+client.getCin()+"',";
        
        req += " `nom` = '"+client.getNom()+"',";
        req += " `prenom` = '"+client.getPrenom()+"',";
        req += " `naissance` = '"+client.getNaissance()+"',";
        req += " `telefix` = '"+client.getTelefix()+"',";
        
        if(client.getTelemobile() != null){
            req += " `nomcomplet` = '"+client.getNomcomplet()+"',";
        }
        if(client.getTelemobile() != null){
           req += " `telemobile` = '"+client.getTelemobile()+"',"; 
        }
        
        if(client.getMail() != null){
            req += " `mail` = '"+client.getMail()+"',";
        }
        
        
        if(client.getCodepostal() != null){
            req += " `codepostale` = '"+client.getCodepostal()+"',";
        }
        
        req += " `adresse` = '"+client.getAdresse()+"',";
        
        
        req += " `sexe` = '"+client.getSexe()+"' ";
        req += "WHERE (`codeclient` = '"+client.getCodeclient()+"') and (`local_nom` = '"+ParametreSystem.NomLocalPC+"');";
        
        if(cnx.ouverture()){
            try{
               int nbr = cnx.executionupdate(req);
               return true;
            }
            catch(SQLException ex){
                System.err.println("Erreur SQL ! \n"+ex.getMessage());
                System.out.println(req);
                return false ;
            }
        }
        else{
            return false ;
        }
    }
    
    public Client getClient(String code){
        Client clt = new Client();
        int id =0 ;
        if(cnx.ouverture()){
            String sql="SELECT *, DATE_FORMAT(naissance, '%d/%m/%Y') AS naissance_string FROM client WHERE (`codeclient`= "+code+") AND (local_nom = '"+ParametreSystem.NomLocalPC+"');";
            ResultSet resultat;
            try {
                resultat = cnx.excutionquery(sql);
                resultat.next();
                
                clt.setCodeclientString(resultat.getString("codeclient"));
                clt.setCin(resultat.getInt("cin"));
                clt.setNom(resultat.getString("nom"));
                clt.setPrenom(resultat.getString("prenom"));
                clt.setNomcomplet(resultat.getString("nomcomplet"));
                clt.setSexe(resultat.getInt("sexe"));
                clt.setNaissance(resultat.getDate("naissance"));
                clt.setDateNaissanceString(resultat.getString("naissance_string"));
                clt.setAdresse(resultat.getString("adresse"));
                clt.setTelefixString(resultat.getString("telefix"));
                clt.setTelemobileString(resultat.getString("telemobile"));
                clt.setMail(resultat.getString("mail"));
                clt.setCodepostal(resultat.getString("codepostale"));
            } 
            catch (SQLException ex) {
                System.err.println("Erreur SQL ! \n"+ex.getMessage());
                System.out.println(sql);
            }
        }
         return clt ;
    }
    
    public int getidClient(){
        
        int id =0 ;
        if(cnx.ouverture()){
            String sql="SELECT MAX(`codeclient`) FROM client WHERE (local_nom = '"+ParametreSystem.NomLocalPC+"');";
            ResultSet resultat;
            try {
                resultat = cnx.excutionquery(sql);
                resultat.next();
                id=resultat.getInt(1);
            } 
            catch (SQLException ex) {
                System.err.println("Erreur SQL ! \n"+ex.getMessage());
            }
           
        }
         return id ;
    }
    
    
    public boolean verifyIdClient(int id){
        boolean result = false ;
        
        if(cnx.ouverture()){
            String sql="SELECT `codeclient` FROM `client` WHERE (`codeclient`= "+id+") AND (local_nom = '"+ParametreSystem.NomLocalPC+"');";
            
            try {
               ResultSet resultat = cnx.excutionquery(sql);
               resultat.last(); //on place le curseur sur le dernier tuple
               if(resultat.getRow()>0){
                  result= true ;
               }
            } 
            catch (SQLException ex) {
                result= false ;
                System.err.println("Erreur SQL ! \n"+ex.getMessage());
            }
       
        }
        return result ;
    }
    
    public boolean verifyCinClient(int cin){
        boolean result = false ;
        
        if(cnx.ouverture()){
            String sql="SELECT `codeclient` FROM `client` WHERE (`cin`= "+cin+") AND (local_nom = '"+ParametreSystem.NomLocalPC+"') ;";
            
            try {
               ResultSet resultat = cnx.excutionquery(sql);
               //on place le curseur sur le dernier tuple
               resultat.last();
               if(resultat.getRow()>0){
                  result= true ;
                  
               }
                
            } 
            catch (SQLException ex) {
                result= false ;
                System.err.println("Erreur SQL ! \n"+ex.getMessage());
            }
       
        }
        return result ;
    }
    
    /********************************** Initial *******************************/
    public ObservableList<ListeClient> SearchCltPersonneGestion(Integer debut, Integer nbr, String Code, String Cin, String NomComplet, String Nom, String Prenom, String Naissance)
    {
        ObservableList<ListeClient> data = FXCollections.observableArrayList();
        
        String Where = "";
        
        if(!clt.isStringNull(Code)){
            Where += " (`codeclient` = \""+Adaptateur.addSlashes(Code)+"\") AND ";
        }
        
        if(!clt.isStringNull(Cin)){
            Where += " (`cin` = \""+Adaptateur.addSlashes(Cin)+"\") AND ";
        }
        
        if(!clt.isStringNull(NomComplet)){
            Where += " (`nomcomplet` LIKE \"%"+Adaptateur.addSlashes(NomComplet)+"%\") AND ";
        }
        
        if(!clt.isStringNull(Nom)){
            Where += " (`nom` LIKE \"%"+Adaptateur.addSlashes(Nom)+"%\") AND ";
        }
        
        if(!clt.isStringNull(Prenom)){
            Where += " (`prenom` LIKE \"%"+Adaptateur.addSlashes(Prenom)+"%\") AND ";
        }
        
        if(!clt.isStringNull(Naissance)){
            Where += " (DATE(`naissance`) =  \""+Naissance+"\") AND ";
        }
        
        if(!Where.equals("")){
            Where = Where.substring(0, Where.length() - 4);
            Where = "WHERE (`local_nom` = '"+ParametreSystem.NomLocalPC+"') AND " + Where;
        }else{
            Where = "WHERE (`local_nom` = '"+ParametreSystem.NomLocalPC+"') ";
        }
        
        String req="SELECT *, DATE_FORMAT(`naissance`, '%d/%m/%Y') AS naissance_string  "
                + "FROM `client` "
                + Where
                + "ORDER BY codeclient DESC "
                + "LIMIT "+debut+" , "+nbr+" ;";
        
        if(cnx.ouverture()){
            try{
               /* Exécution d'une requête de lecture */
                ResultSet resultat = cnx.excutionquery(req);
                resultat.last();  //on place le curseur sur le dernier tuple
                int nombreLignes = resultat.getRow();  //on récupère le numéro de la ligne
                if(nombreLignes>0){
                    resultat.beforeFirst(); //on repace le curseur avant la première ligne
                    while ( resultat.next() ) {
                        String codeclient = resultat.getString( "codeclient" );
                        String cin = resultat.getString( "cin" );
                        String nomcomplet=resultat.getString("nomcomplet");
                        String nom=resultat.getString("nom");
                        String prenom=resultat.getString("prenom");
                        String naissance_str = resultat.getString("naissance_string");
                        String adresse=resultat.getString("adresse");
                        String telefix = resultat.getString( "telefix" );
                        String telemobile = resultat.getString( "telemobile" );
                        Integer sexe = resultat.getInt( "sexe" );
                        data.add(new ListeClient(codeclient, cin, nomcomplet, nom, prenom, naissance_str, adresse, telefix, telemobile, sexe));
                    }
                }
            }
            catch(SQLException ex){
                System.err.println("Erreur SQL ! \n"+ex.getMessage());
                System.out.println(req);
            }
        }
        else{
            SD.ShowAletDialog();
        }
       return data ;
    }
    
    public Integer nbrCltPersonneGestion( String Code, String Cin, String NomComplet, String Nom, String Prenom, String Naissance)
    {
        String Where = "";
        
        if(!clt.isStringNull(Code)){
            Where += " (`codeclient` = \""+Adaptateur.addSlashes(Code)+"\") AND ";
        }
        
        if(!clt.isStringNull(Cin)){
            Where += " (`cin` = \""+Adaptateur.addSlashes(Cin)+"\") AND ";
        }
        
        if(!clt.isStringNull(NomComplet)){
            Where += " (`nomcomplet` LIKE \"%"+Adaptateur.addSlashes(NomComplet)+"%\") AND ";
        }
        
        if(!clt.isStringNull(Nom)){
            Where += " (`nom` LIKE \"%"+Adaptateur.addSlashes(Nom)+"%\") AND ";
        }
        
        if(!clt.isStringNull(Prenom)){
            Where += " (`prenom` LIKE \"%"+Adaptateur.addSlashes(Prenom)+"%\") AND ";
        }
        
        if(!clt.isStringNull(Naissance)){
            Where += " (DATE(`naissance`) =  \""+Naissance+"\") AND ";
        }
        
        if(!Where.equals("")){
            Where = Where.substring(0, Where.length() - 4);
            Where = "WHERE (`local_nom` = '"+ParametreSystem.NomLocalPC+"') AND " + Where;
        }else{
            Where = "WHERE (`local_nom` = '"+ParametreSystem.NomLocalPC+"') ";
        }
        
        
        String req=" SELECT COUNT(`codeclient`) "+ 
                    " FROM `client` "+ 
                    Where+" ;"; 
        
        int sommme =0;
        
        if(cnx.ouverture()){
            try{
               /* Exécution d'une requête de lecture */
                ResultSet resultat = cnx.excutionquery(req);
                resultat.next();    // get the number of rows from the result set
                sommme = resultat.getInt(1);
            }
            catch(SQLException ex){
                System.err.println("Erreur SQL ! \n"+ex.getMessage());
                System.out.println(req);
            }
        }
        return sommme ;
    }
}
