package Models.Client;

import Controllers.Client.ListeClientEntreprise;
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 ClientEntrepriseDB {
    
    connexion cnx = new connexion();
    contro clt = new contro();
    
    public boolean verifyCodeEntreprise(int code){
        boolean result = false ;
        
        if(cnx.ouverture()){
            String sql="SELECT * FROM `cltentreprise` WHERE (`idcliententreprise` = "+code+") 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 ClientEntreprise GetClientEtr(String CodeEtr){
        ClientEntreprise ClientEtr = new ClientEntreprise();
        if(cnx.ouverture()){
            String sql="SELECT * FROM `cltentreprise` WHERE (`idcliententreprise` = "+CodeEtr+") 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){
                  ClientEtr.setCodeString(resultat.getString("idcliententreprise"));
                  ClientEtr.setNom(resultat.getString("nomentrepise"));
                  ClientEtr.setGerant(resultat.getString("gerant"));
                  ClientEtr.setAdresse(resultat.getString("adresse"));
                  ClientEtr.setMail(resultat.getString("mail"));
                  ClientEtr.setMatricule(resultat.getString("matricule_fiscale"));
                  ClientEtr.setPostal(resultat.getLong("code_postal"));
                  ClientEtr.setTele1(resultat.getLong("telefix"));
                  ClientEtr.setTele2(resultat.getLong("telefix2"));
                  ClientEtr.setFax(resultat.getLong("fax"));
                  ClientEtr.setLocalNom(resultat.getString("local_nom"));
                  ClientEntrepriseContact EtrContact = new ClientEntrepriseContactDB().getContactByIdEntreprise(resultat.getString("idcliententreprise"));
                  ClientEtr.setContact(EtrContact);
               }
            } 
            catch (SQLException ex) {
                System.err.println("Erreur SQL ! \n"+ex.getMessage());
                System.err.println(sql);
            }
        }
        return ClientEtr ;
    }
        
    public int getidClientEtr(){
        
        int id = -1 ;
        if(cnx.ouverture()){
            String sql="SELECT MAX(`idcliententreprise`) FROM cltentreprise WHERE `local_nom` = '"+ParametreSystem.NomLocalPC+"';";
            ResultSet resultat;
            try {
                resultat = cnx.excutionquery(sql);
                resultat.next();
                id=resultat.getInt(1);
            } 
            catch (SQLException ex) {
                ShowDialog.setTitre("Erreur SQL !");
                ShowDialog.setDetail(ex.getMessage()+"\n"+ex.getSQLState());
                
                ShowDialog SD = new ShowDialog();
                SD.ShowAletDialog();
            }
        }
         return  id;
    }

    
    public boolean addEntreprise(ClientEntreprise CltEtr){
        String req = "INSERT INTO `cltentreprise` (`idcliententreprise`, `nomentrepise`, `gerant`, `matricule_fiscale`, `adresse`, `telefix`, `telefix2`, `fax`, `code_postal`, `mail`, `local_nom`, `date_add`) VALUES ("+CltEtr.getCode()+", '"+CltEtr.getNom()+"', '"+CltEtr.getGerant()+"', '"+CltEtr.getMatricule()+"', '"+CltEtr.getAdresse()+"', "+CltEtr.getTele1()+", "+CltEtr.getTele2()+", "+CltEtr.getFax()+", "+CltEtr.getPostal()+", '"+CltEtr.getMail()+"', '"+ParametreSystem.NomLocalPC+"', CURTIME());";
        return cnx.insertion(req);
    }
    
    
    public boolean updateEntreprise(ClientEntreprise CltEtr) throws UnsupportedEncodingException
    {
        String req = "UPDATE `cltentreprise`";
        
        req += "SET `nomentrepise` = '"+CltEtr.getNom()+"',";
        
        if(!clt.isStringNull(CltEtr.getMatricule())){
            req += " `matricule_fiscale` = '"+CltEtr.getMatricule()+"',";
        }
        if(!clt.isStringNull(CltEtr.getTele2String())){
           req += " `telefix2` = '"+CltEtr.getTele2String()+"',";
        }
        if(!clt.isStringNull(CltEtr.getFaxString())){
            req += " `fax` = '"+CltEtr.getFaxString()+"',";
        }
        if(!clt.isStringNull(CltEtr.getPostalString())){
            req += " `code_postal` = '"+CltEtr.getPostalString()+"',";
        }
        if(!clt.isStringNull(CltEtr.getMail())){
            req += " `mail` = '"+CltEtr.getMail()+"',";
        }
        
        req += " `adresse` = '"+CltEtr.getAdresse()+"',";
        req += " `gerant` = '"+CltEtr.getGerant()+"',";
        req += " `telefix` = '"+CltEtr.getTele1String()+"'";
        
        req += "WHERE (`idcliententreprise` = '"+CltEtr.getCodeString()+"') and (`local_nom` = '"+CltEtr.getLocalNom()+"');";
        
        if(cnx.ouverture()){
            try{
               int nbr = cnx.executionupdate(req);
               return new ClientEntrepriseContactDB().updateEtrContact(CltEtr.getContact());
            }
            catch(SQLException ex){
                System.err.println("Erreur SQL ! \n"+ex.getMessage());
                System.out.println(req);
                return false ;
            }
        }
        else{
            return false ;
        }
    }
    
    /*
    ;
     
                        */
    /********************************** Initial *******************************/
    public ObservableList<ListeClientEntreprise> SearchCltEntrepriseGestion(Integer debut, Integer nbr, String CodeEtr, String NomEtr, String GerantEtr, String MatriculeEtr, String AdresseEtr, String TelephoneEtr)
    {
        ObservableList<ListeClientEntreprise> data = FXCollections.observableArrayList();
        
        String Where = "";
        
        if(!clt.isStringNull(CodeEtr)){
            Where += " (`idcliententreprise` = \""+Adaptateur.addSlashes(CodeEtr)+"\") AND ";
        }
        
        if(!clt.isStringNull(NomEtr)){
            Where += " (`nomentrepise` LIKE \"%"+Adaptateur.addSlashes(NomEtr)+"%\") AND ";
        }
        
        if(!clt.isStringNull(GerantEtr)){
            Where += " (`gerant` LIKE \"%"+Adaptateur.addSlashes(GerantEtr)+"%\") AND ";
        }
        
        if(!clt.isStringNull(MatriculeEtr)){
            Where += " (`matricule_fiscale` = \""+Adaptateur.addSlashes(MatriculeEtr)+"\") AND ";
        }
        
        if(!clt.isStringNull(AdresseEtr)){
            Where += " (`adresse` LIKE \"%"+Adaptateur.addSlashes(AdresseEtr)+"%\") AND ";
        }
        
        if(!clt.isStringNull(TelephoneEtr)){
            Where += " (`telefix` = \""+Adaptateur.addSlashes(TelephoneEtr)+"\") 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 * "
                + "FROM `cltentreprise` "
                + Where
                + "ORDER BY idcliententreprise 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 code = resultat.getString("idcliententreprise");
                        String nom=resultat.getString("nomentrepise");
                        String gerant =resultat.getString("gerant");
                        String matricule =resultat.getString("matricule_fiscale");
                        String adresse =resultat.getString("adresse");
                        String telefix = resultat.getString( "telefix" );
                        String telefix2 = resultat.getString( "telefix2" );
                        
                        data.add(new ListeClientEntreprise(code, nom, gerant, matricule, adresse, telefix, telefix2));
                        
                    }
                }
            }
            catch(SQLException ex){
                System.err.println("Erreur SQL ! \n"+ex.getMessage());
                System.out.println(req);
            }
        }
       return data ;
    }
    
    public Integer nbrCltEntrepriseGestion(String CodeEtr, String NomEtr, String GerantEtr, String MatriculeEtr, String AdresseEtr, String TelephoneEtr)
    {
        String Where = "";
        
        if(!clt.isStringNull(CodeEtr)){
            Where += " (`idcliententreprise` = \""+Adaptateur.addSlashes(CodeEtr)+"\") AND ";
        }
        
        if(!clt.isStringNull(NomEtr)){
            Where += " (`nomentrepise` LIKE \"%"+Adaptateur.addSlashes(NomEtr)+"%\") AND ";
        }
        
        if(!clt.isStringNull(GerantEtr)){
            Where += " (`gerant` LIKE \"%"+Adaptateur.addSlashes(GerantEtr)+"%\") AND ";
        }
        
        if(!clt.isStringNull(MatriculeEtr)){
            Where += " (`matricule_fiscale` = \""+Adaptateur.addSlashes(MatriculeEtr)+"\") AND ";
        }
        
        if(!clt.isStringNull(AdresseEtr)){
            Where += " (`adresse` LIKE \"%"+Adaptateur.addSlashes(AdresseEtr)+"%\") AND ";
        }
        
        if(!clt.isStringNull(TelephoneEtr)){
            Where += " (`telefix` = \""+Adaptateur.addSlashes(TelephoneEtr)+"\") 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(`idcliententreprise`) "+ 
                    " FROM `cltentreprise` "+ 
                    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 ;
    }
    
}
