package Models.DevisClt;

import Models.Produit.ListeProduit;
import Controllers.Traitement.Adaptateur;
import Controllers.Traitement.ParametreSystem;
import Controllers.Traitement.contro;
import Models.User.User;
import Models.connexion;
import java.sql.ResultSet;
import java.sql.SQLException;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

/**
 *
 * @author Maher Ben Tili
 */
public class DevisDB {
    
    connexion cnx = new connexion();
    contro clt = new contro();
    
    public String AddDevis(Devis devis){
        
        String codedevis = null ;
        
        String datecreation = Adaptateur.DatabaseDateFormat(devis.getDate());
        String codeclient = devis.getCodeClient();
        String datefinvalidite =Adaptateur.DatabaseDateFormat(devis.getValidite());
        String totalhorstaxnet =devis.getTotalHorsTaxNet().replace(",", ".");
        String totaltva = devis.getTotalTVA().replace(",", ".");
        String netapayer = devis.getNetAPayer().replace(",", ".");
        String remise = devis.getRemise().replace(",", ".");
        
        String sql = "";
        
        if(devis.getTypeClient()==0){
          sql ="INSERT INTO `devisclt` (`date_creation`, `fin_validite`, `typeclt`, `type_reglement`, `codeclient`, `total_h_t_net`, `total_tva`, `remise`, `timbre_loi`, `net_a_payer`, `idprofile`, `local_nom`) VALUES ('"+datecreation+"', '"+datefinvalidite+"', '0', '"+devis.getTypeRegementInteger()+"', '"+codeclient+"',  "+totalhorstaxnet+", "+totaltva+",  "+remise+", '"+ParametreSystem.Timbre+"', '"+netapayer+"', "+User.idprofile+", '"+ParametreSystem.NomLocalPC+"');";
        }
        if(devis.getTypeClient()==1){
          sql ="INSERT INTO `devisclt` (`date_creation`, `fin_validite`, `typeclt`, `type_reglement`, `idcliententreprise`, `total_h_t_net`, `total_tva`, `remise`,  `timbre_loi`, `net_a_payer`, `idprofile`, `local_nom`) VALUES ('"+datecreation+"', '"+datefinvalidite+"', '1', '"+devis.getTypeRegementInteger()+"', '"+codeclient+"',  "+totalhorstaxnet+", "+totaltva+",  "+remise+",  '"+ParametreSystem.Timbre+"', "+netapayer+", "+User.idprofile+", '"+ParametreSystem.NomLocalPC+"');";
        }
        if(devis.getTypeClient()==2){
            //insertion de passager
            String req = "INSERT INTO `cltpassageur` (`nom`, `prenom`, `adresse`, `tele`, `gsm`, `local_nom`) VALUES ('"+devis.getNom()+"', '"+devis.getPrenom()+"', \""+devis.getAdresse()+"\", '"+devis.getTele1()+"', "+devis.getTele2Null()+", '"+ParametreSystem.NomLocalPC+"');";
            String codepassager = cnx.InsertGetLastId(req);
            if(!codepassager.isEmpty()){
                sql ="INSERT INTO `devisclt` (`date_creation`, `fin_validite`, `typeclt`, `type_reglement`, `idcltpassageur`, `total_h_t_net`, `total_tva`, `remise`,  `timbre_loi`, `net_a_payer`, `idprofile`, `local_nom`) VALUES ('"+datecreation+"', '"+datefinvalidite+"', '2', '"+devis.getTypeRegementInteger()+"', '"+codepassager+"',  '"+totalhorstaxnet+"', '"+totaltva+"', '"+remise+"', '"+ParametreSystem.Timbre+"', '"+netapayer+"', '"+User.idprofile+"', '"+ParametreSystem.NomLocalPC+"');";
            }
        }
      codedevis = cnx.InsertGetLastId(sql);
      
        String req ;
        String PrixHT ;
        String Remise ;
        String TotalHT ;
        String TVA ;
        String TotalTTC ;
        
      for(ListeProduit listeprod : devis.getListeproduit()){
          PrixHT = listeprod.getPrixHT().replace(",",".");
          Remise= listeprod.getRemise().replace("%","").replace(",",".");
          TotalHT= listeprod.getTotalHT().replace(",",".");
          TVA=listeprod.getTVA().replace("%","").replace(",",".");
          TotalTTC= listeprod.getTotalTTC().replace(",","."); 
                  
          req = "INSERT INTO `list_produit_devisclt` (`iddevis_devis`, `reference_produit`, `designation_produit`, `quantie`, `p_u_h_t`, `remise`, `p_u_h_t_net`, `tva`, `montant`, `local_nom`) VALUES ('"+codedevis+"', \""+listeprod.getReference()+"\", \""+listeprod.getDesignation()+"\", "+listeprod.getQuantite()+", "+PrixHT+", "+Remise+", "+TotalHT+", "+TVA+", "+TotalTTC+", '"+ParametreSystem.NomLocalPC+"');";
          cnx.insertion(req);
      }
      return codedevis ;
    }
    
    public Devis getDevis(String codedevis){
        Devis devis = new Devis() ;
        String req = "SELECT `iddevis`, `date_creation`, DATE_FORMAT(fin_validite, '%d/%m/%Y') as fin_validite , `type_reglement`, `codeclient`, `typeclt`, `idcliententreprise`, `idcltpassageur`, `total_h_t_net`, `total_tva`, `timbre_loi`, `net_a_payer`, `idprofile`, `remise` FROM `devisclt` WHERE `iddevis` = '"+codedevis+"' AND (local_nom = '"+ParametreSystem.NomLocalPC+"'); ";
        if(cnx.ouverture()){
            try{
               ResultSet resultat = cnx.excutionquery(req);
                //on place le curseur sur le dernier tuple
                resultat.last();
                //on récupère le numéro de la ligne
                int nombreLignes = resultat.getRow();
                if(nombreLignes>0){
                    
                    devis.setCodeDevis(resultat.getString("iddevis"));
                    
                    devis.setTypeRegement(resultat.getString("type_reglement"));
                    devis.setDate(resultat.getString("date_creation"));
                    devis.setValidite(resultat.getString("fin_validite"));
                    devis.setNetAPayer(resultat.getString("net_a_payer"));
                    devis.setTotalHorsTaxNet(resultat.getString("total_h_t_net"));
                    devis.setTotalTVA(resultat.getString("total_tva"));
                    devis.setTimbre(resultat.getString("timbre_loi"));
                    devis.setCodeUser(resultat.getInt("idprofile"));
                    devis.setTypeClient(resultat.getInt("typeclt"));
                    devis.setRemise(resultat.getString("remise"));
                    
                    if(devis.getTypeClient()==0){
                        devis.setCodeClient(resultat.getString("codeclient"));
                        cnx.ouverture();
                        String reqclt = "SELECT * FROM `client` WHERE (`codeclient` = '"+devis.getCodeClient()+"') AND (local_nom = '"+ParametreSystem.NomLocalPC+"'); ";
                        ResultSet resuclt = cnx.excutionquery(reqclt);
                        resuclt.last();
                        devis.setNom(resuclt.getString("nom"));
                        devis.setPrenom(resuclt.getString("prenom"));
                        devis.setAdresse(resuclt.getString("adresse"));
                        devis.setTele1(resuclt.getString("telefix"));
                        devis.setTele2(resuclt.getString("telemobile"));
                    }
                    
                    if(devis.getTypeClient()==1){
                        devis.setCodeClient(resultat.getString("idcliententreprise"));
                        cnx.ouverture();
                        String reqclt = "SELECT * FROM `cltentreprise` WHERE `idcliententreprise` = '"+devis.getCodeClient()+"' AND (local_nom = '"+ParametreSystem.NomLocalPC+"'); ";
                        ResultSet resucltetr = cnx.excutionquery(reqclt);
                        resucltetr.last();
                        devis.setNom(resucltetr.getString("nomentrepise"));
                        devis.setMatricule(resucltetr.getString("matricule_fiscale"));
                        devis.setAdresse(resucltetr.getString("adresse"));
                        devis.setTele1(resucltetr.getString("telefix"));
                        devis.setTele2(resucltetr.getString("telefix2"));
                     }
                    
                    if(devis.getTypeClient()==2){
                        devis.setCodeClient(resultat.getString("idcltpassageur"));
                        cnx.ouverture();
                        String reqclt = "SELECT * FROM `cltpassageur` WHERE `idcltpassageur` = '"+devis.getCodeClient()+"' AND (local_nom = '"+ParametreSystem.NomLocalPC+"'); ";
                        ResultSet resucltpa = cnx.excutionquery(reqclt);
                        resucltpa.last();
                        devis.setNom(resucltpa.getString("nom"));
                        devis.setPrenom(resucltpa.getString("prenom"));
                        devis.setAdresse(resucltpa.getString("adresse"));
                        devis.setTele1(resucltpa.getString("tele"));
                        devis.setTele2(resucltpa.getString("gsm"));
                    }
                    cnx.ouverture();
                    String reqprod = "SELECT * FROM list_produit_devisclt where iddevis_devis = "+codedevis+" AND (local_nom = '"+ParametreSystem.NomLocalPC+"');";
                    ResultSet resulist = cnx.excutionquery(reqprod);
                    //on repace le curseur avant la première ligne
                    resulist.beforeFirst();
                     ObservableList<ListeProduit> dataProdDev=FXCollections.observableArrayList();
                    while ( resulist.next() ) {          
                        String reference = resulist.getString("reference_produit");
                        String designaton = resulist.getString("designation_produit");
                        String quantite=resulist.getString("quantie");
                        String PrixHT =resulist.getString("p_u_h_t");
                        String Remise =resulist.getString("remise");
                        String TotalHT =resulist.getString("p_u_h_t_net");
                        String TVA =resulist.getString("tva");
                        String TotalTTC =resulist.getString("montant");
                        dataProdDev.add(new ListeProduit(reference, designaton, quantite, PrixHT, Remise, TotalHT, TVA, TotalTTC));
                        }
                    devis.setListeproduit(dataProdDev);
                    }
            }
            catch(SQLException ex){
                System.err.println("Erreur SQL ! \n"+ex.getMessage());
            }
        }
        return devis ;
    }
    
    
    
    
    /********************************** Initial *******************************/
    public ObservableList<DevisCltListe> SearchDevisCltGestion(Integer debut, Integer nbr, String CodeDevis, String CodeClient, String Reglement, String DateCreation, String NameClient, String CinClient)
    {
        ObservableList<DevisCltListe> data = FXCollections.observableArrayList();
        
        String Where = "";
        
        if(!clt.isStringNull(CodeDevis)){
            Where += " (D.`iddevis` LIKE \"%"+Adaptateur.addSlashes(CodeDevis)+"%\") AND ";
        }
        
        if(!clt.isStringNull(CodeClient)){
           Where += " ( (D.idcliententreprise = '"+CodeClient+"') OR (D.codeclient = '"+CodeClient+"') OR (D.idcltpassageur = '"+CodeClient+"') ) AND ";
        }
        
        if(!clt.isStringNull(Reglement)){
            Where += " (D.`type_reglement` = \""+Reglement+"\") AND ";
        }
        
        if(!clt.isStringNull(DateCreation)){
            Where += " (DATE(D.`date_creation`) =  \""+DateCreation+"\") AND ";
        }
        
        String LeftJoin = "";
        if(!clt.isStringNull(NameClient) || !clt.isStringNull(CinClient) ){
            LeftJoin =  " LEFT JOIN `client` C ON (C.codeclient = D.codeclient) AND (D.typeclt = 0) "
                        +" LEFT JOIN `cltentreprise` E ON (E.idcliententreprise = D.idcliententreprise ) AND (D.typeclt = 1) "
                        +" LEFT JOIN `cltpassageur` P ON (P.idcltpassageur = D.idcltpassageur) AND (D.typeclt = 2) ";
            
            if(!clt.isStringNull(NameClient)){
                NameClient = Adaptateur.addSlashes(NameClient);
                Where += "( ((C.nom LIKE \"%"+NameClient+"%\") OR (C.prenom LIKE \"%"+NameClient+"%\") OR  (C.nomcomplet LIKE \"%"+NameClient+"%\"))  OR  (E.nomentrepise LIKE \"%"+NameClient+"%\") OR  (P.nom LIKE \"%"+NameClient+"%\") ) AND";
            }
            
            if(!clt.isStringNull(CinClient)){
                CinClient = Adaptateur.addSlashes(CinClient);
                Where += "( (C.cin = \""+CinClient+"\") OR (E.matricule_fiscale = \""+CinClient+"\") ) AND";
            }
        }
        
        if(!Where.equals("")){
            Where = "WHERE  " + Where + " (D.local_nom = '"+ParametreSystem.NomLocalPC+"') ";
        }else{
            Where = "WHERE (D.local_nom = '"+ParametreSystem.NomLocalPC+"') ";
        }
        
        String req="SELECT D.`iddevis`, DATE_FORMAT(D.date_creation, '%d/%m/%Y') as date_creation , DATE_FORMAT(D.fin_validite, '%d/%m/%Y') as fin_validite , D.`type_reglement`, D.`codeclient`, D.`typeclt`, D.`idcliententreprise`, D.`idcltpassageur`, D.`net_a_payer` "
                + "FROM `devisclt` D "
                + LeftJoin
                + Where
                + "ORDER BY D.date_creation DESC "
                + "LIMIT "+debut+" , "+nbr+" ;";
        
        
        
        if(cnx.ouverture()){
            try{
               // Exécution d'une requête de lecture 
                ResultSet resultat = cnx.excutionquery(req);
                //on place le curseur sur le dernier tuple
                resultat.last();
                //on récupère le numéro de la ligne
                int nombreLignes = resultat.getRow();
                if(nombreLignes>0){
                    //on repace le curseur avant la première ligne
                    resultat.beforeFirst();
                    while ( resultat.next() ) {
                        
                        String code_devis = resultat.getString("iddevis");
                        
                        String type_client = "";
                        String code_client = "";
                        if(resultat.getString("typeclt").equals("0")){
                            type_client ="Exist Client";
                            code_client = resultat.getString("codeclient");
                        }else if(resultat.getString("typeclt").equals("1")){
                            type_client ="Entreprise";
                            code_client = resultat.getString("idcliententreprise");
                        }else if(resultat.getString("typeclt").equals("2")){
                            type_client ="Passager";
                            code_client = resultat.getString("idcltpassageur");
                        }
                        
                        String total_devis =resultat.getString("net_a_payer");
                        
                        String mode_reglement = ""; //Mode Paiement
                        if(resultat.getString("type_reglement").equals("0")){
                            mode_reglement = "Comptant";
                        }else if(resultat.getString("type_reglement").equals("1")){
                            mode_reglement = "Facilité";
                        }
                        
                        String date_creation =resultat.getString("date_creation");
                        String date_fin_validite =resultat.getString("fin_validite");
                        
                        data.add(new DevisCltListe(code_devis, type_client, code_client, mode_reglement, total_devis, date_creation, date_fin_validite));
                    }
                }
            }
            catch(SQLException ex){
                System.err.println("Erreur SQL ! \n"+ex.getMessage());
                System.out.println(req);
            }
        }
        return data ;
    }
    
    public Integer nbrDevisCltGestion(String CodeDevis, String CodeClient, String Reglement, String DateCreation, String NameClient, String CinClient)
    {
        String Where = "";
        
        if(!clt.isStringNull(CodeDevis)){
            Where += " (D.`iddevis` LIKE \"%"+Adaptateur.addSlashes(CodeDevis)+"%\") AND ";
        }
        
        if(!clt.isStringNull(CodeClient)){
           Where += " ( (D.idcliententreprise = '"+CodeClient+"') OR (D.codeclient = '"+CodeClient+"') OR (D.idcltpassageur = '"+CodeClient+"') ) AND ";
        }
        
        if(!clt.isStringNull(Reglement)){
            Where += " (D.`type_reglement` = \""+Reglement+"\") AND ";
        }
        
        if(!clt.isStringNull(DateCreation)){
            Where += " (DATE(D.`date_creation`) =  \""+DateCreation+"\") AND ";
        }
        
        String LeftJoin = "";
        if(!clt.isStringNull(NameClient) || !clt.isStringNull(CinClient) ){
            LeftJoin =  " LEFT JOIN `client` C ON (C.codeclient = D.codeclient) AND (D.typeclt = 0) "
                        +" LEFT JOIN `cltentreprise` E ON (E.idcliententreprise = D.idcliententreprise ) AND (D.typeclt = 1) "
                        +" LEFT JOIN `cltpassageur` P ON (P.idcltpassageur = D.idcltpassageur) AND (D.typeclt = 2) ";
            
            if(!clt.isStringNull(NameClient)){
                NameClient = Adaptateur.addSlashes(NameClient);
                Where += "( ((C.nom LIKE \"%"+NameClient+"%\") OR (C.prenom LIKE \"%"+NameClient+"%\") OR  (C.nomcomplet LIKE \"%"+NameClient+"%\"))  OR  (E.nomentrepise LIKE \"%"+NameClient+"%\") OR  (P.nom LIKE \"%"+NameClient+"%\") ) AND";
            }
            
            if(!clt.isStringNull(CinClient)){
                CinClient = Adaptateur.addSlashes(CinClient);
                Where += "( (C.cin = \""+CinClient+"\") OR (E.matricule_fiscale = \""+CinClient+"\") ) AND";
            }
        }
        
        if(!Where.equals("")){
            Where = "WHERE  " + Where + " (D.`local_nom` = '"+ParametreSystem.NomLocalPC+"') ";
        }else{
            Where = "WHERE (D.`local_nom` = '"+ParametreSystem.NomLocalPC+"') ";
        }
        
        String req=" SELECT COUNT(D.`iddevis`) " 
                    + " FROM `devisclt` D "
                    + LeftJoin
                    + 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 ;
    }
    
    
    /**********************************Controller  Import *******************************/
    public ObservableList<DevisCltListe> getdataImport(String  tab,String  mot, Integer debut, Integer nbr){
        ObservableList<DevisCltListe> data=FXCollections.observableArrayList();
        
        String req="SELECT DC.iddevis, DATE_FORMAT(DC.date_creation, '%d/%m/%Y') as date_creation , DATE_FORMAT(DC.fin_validite, '%d/%m/%Y') as fin_validite , DC.type_reglement, DC.codeclient, DC.typeclt, DC.idcliententreprise, DC.idcltpassageur, DC.net_a_payer FROM devisclt DC WHERE ("+tab+" LIKE \"%"+mot+"%\") AND (Date(DC.fin_validite) > now()) AND (DC.iddevis NOT IN (SELECT DISTINCT(iddevis) FROM commandeclt WHERE  (iddevis IS NOT NULL) AND (local_nom = '"+ParametreSystem.NomLocalPC+"'))) AND (DC.local_nom = '"+ParametreSystem.NomLocalPC+"') ORDER BY DC.date_creation DESC LIMIT "+debut+" , "+nbr+" ;";       
        
        if(tab.equals("DC.CodeClient")){
            req="SELECT DC.iddevis, DATE_FORMAT(DC.date_creation, '%d/%m/%Y') as date_creation , DATE_FORMAT(DC.fin_validite, '%d/%m/%Y') as fin_validite , DC.type_reglement, DC.codeclient, DC.typeclt, DC.idcliententreprise, DC.idcltpassageur, DC.net_a_payer FROM devisclt DC WHERE   (Date(DC.fin_validite) > now()) AND (DC.iddevis NOT IN (SELECT DISTINCT(iddevis) FROM commandeclt WHERE (iddevis IS NOT NULL) AND (local_nom = '"+ParametreSystem.NomLocalPC+"'))) AND (DC.idcliententreprise LIKE '%"+mot+"%' OR DC.codeclient LIKE '%"+mot+"%' OR DC.idcltpassageur LIKE '%"+mot+"%') AND (DC.local_nom = '"+ParametreSystem.NomLocalPC+"') ORDER BY DC.date_creation DESC LIMIT "+debut+" , "+nbr+" ;";
        }
       
        if(cnx.ouverture()){
            try{
               // Exécution d'une requête de lecture 
                ResultSet resultat = cnx.excutionquery(req);
                //on place le curseur sur le dernier tuple
                resultat.last();
                //on récupère le numéro de la ligne
                int nombreLignes = resultat.getRow();
                if(nombreLignes>0){
                    //on repace le curseur avant la première ligne
                    resultat.beforeFirst();
                    while ( resultat.next() ) {
                        
                        String code_devis = resultat.getString("iddevis");
                        
                        String type_client = "";
                        String code_client = "";
                        if(resultat.getString("typeclt").equals("0")){
                            type_client ="Exist Client";
                            code_client = resultat.getString("codeclient");
                        }else if(resultat.getString("typeclt").equals("1")){
                            type_client ="Entreprise";
                            code_client = resultat.getString("idcliententreprise");
                        }else if(resultat.getString("typeclt").equals("2")){
                            type_client ="Passager";
                            code_client = resultat.getString("idcltpassageur");
                        }
                        
                        String total_devis =resultat.getString("net_a_payer");
                        
                        String mode_reglement = ""; //Mode Paiement
                        if(resultat.getString("type_reglement").equals("0")){
                            mode_reglement = "Comptant";
                        }else if(resultat.getString("type_reglement").equals("1")){
                            mode_reglement = "Facilité";
                        }
                       
                        String date_creation =resultat.getString("date_creation");
                        String date_fin_validite =resultat.getString("fin_validite");
                        
                        data.add(new DevisCltListe(code_devis, type_client, code_client, mode_reglement, total_devis, date_creation, date_fin_validite));
                    }
                }
            }
            catch(SQLException ex){
                System.err.println("Erreur SQL ! \n"+ex.getMessage());
                System.out.println(req);
            }
        }
       return data ;
    }
    
    public String nbrDevisCltImport(String  tab, String mot){
        
        String req = "SELECT count(DC.iddevis) FROM devisclt DC, commandeclt CC WHERE ("+tab+" LIKE \"%"+mot+"%\") AND (Date(DC.fin_validite) > now()) AND (CC.iddevis != DC.iddevis) AND (DC.local_nom = '"+ParametreSystem.NomLocalPC+"') ;";
        
        if(tab.equals("DC.CodeClient")){
            req = "SELECT count(DC.iddevis) FROM devisclt DC, commandeclt CC WHERE (Date(DC.fin_validite) > now()) AND (CC.iddevis != DC.iddevis) AND (DC.idcliententreprise LIKE '%"+mot+"%' OR DC.codeclient LIKE '%"+mot+"%' OR DC.idcltpassageur LIKE '%"+mot+"%') AND (DC.local_nom = '"+ParametreSystem.NomLocalPC+"') ;";
        }
        
        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(req+" \n Erreur SQL ! \n"+ex.getMessage());
            }
        }
       return  Integer.toString(sommme) ;
    }
}
