package Models.TraiteClt;

import Controllers.Dialog.ShowDialog;
import Controllers.Traitement.Adaptateur;
import Controllers.Traitement.ParametreSystem;
import Controllers.Traitement.contro;
import Models.H2JDBC;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import org.apache.log4j.Logger;

/**
 * @author Maher Ben Tili
 */
public class TraiteCltGestionDB {
    
    H2JDBC h2jdbc = new H2JDBC();
    ShowDialog SD = new ShowDialog();
    Logger logger = Logger.getLogger(TraiteCltGestionDB.class.getName());
    contro clt = new contro();
    
    public ResultSet GetDetailTraite(String  IdTraiteClt)
    {
        String req = "SELECT T.*, F.typeclt, F.net_a_payer, to_char(date_traite, 'dd/mm/yyyy') AS date_traite_format, "
                    + "CASE  WHEN montant_traite >=  montant_payer THEN  '1' WHEN date_traite >= now() OR  date_traite >= date_paiement THEN  '2' ELSE  '3' END AS etat, "
                    + " C.codeclient, C.cin, C.nom, C.prenom, "
                    + "E.idcliententreprise, E.matricule_fiscale, E.nomentrepise "
                    + "FROM traite_clt T, factureclt F "
                    + "LEFT JOIN client C ON (C.local_nom= '"+ParametreSystem.NomLocalPC+"') AND (F.idcltexiste = C.codeclient) "
                    + "LEFT JOIN cltentreprise E ON (E.local_nom= '"+ParametreSystem.NomLocalPC+"') AND (F.idcltentreprise = E.idcliententreprise) "
                    + "WHERE (T.local_nom = '"+ParametreSystem.NomLocalPC+"') AND (T.id_factureclt = F.idfactureclt) "
                    + "AND (T.id_traite = "+IdTraiteClt+") ";
        
        return h2jdbc.selectFromDB(req);
    }
    
    
    
    /********************************** Search *******************************/
    
    public ObservableList<TraiteCltGestionListe>  SearchTraiteClt(Integer debut, Integer nbr, String idTraite, String idFactureclt, String dateTraite, String codeClient, String cin, String nom)
    {
        ObservableList<TraiteCltGestionListe> DataListTraiteClt = FXCollections.observableArrayList();
        
        String Where = "";
        
        if(!clt.isNumericNotnull(idTraite)){
            Where += " (T.id_traite = '"+Adaptateur.addSlashes(idTraite)+"') AND ";
        }
        
        if(!clt.isNumericNotnull(idFactureclt)){
            Where += " (F.idfactureclt = '"+Adaptateur.addSlashes(idFactureclt)+"') AND ";
        }
        
        if(!clt.isNumericNotnull(codeClient)){
           Where += "( (F.idcltentreprise = '"+Adaptateur.addSlashes(codeClient)+"') OR (F.idcltexiste = '"+Adaptateur.addSlashes(codeClient)+"') ) AND ";
        }
        
        if(!clt.isStringNull(nom)){
            Where += "( (E.nomentrepise LIKE '%"+Adaptateur.addSlashes(nom)+"%') OR (C.nomcomplet LIKE '%"+Adaptateur.addSlashes(nom)+"%') ) AND "; 
        }
        
        if(!clt.isNumericNotnull(cin)){
            Where += "( (C.cin = '"+Adaptateur.addSlashes(cin)+"') OR (E.matricule_fiscale = '"+Adaptateur.addSlashes(cin)+"') ) AND ";
        }
        
        if(!clt.isStringNull(dateTraite)){
            Where += " (T.date_traite = '"+dateTraite+"') AND ";
        }
        
        if(!Where.equals("")){
            Where = " AND "+Where.substring(0, Where.length() - 4);
        }
        
        String req = "SELECT T.*, F.typeclt, "
                    + "CASE  WHEN montant_traite >=  montant_payer THEN  '1' WHEN date_traite >= now() OR  date_traite >= date_paiement THEN  '2' ELSE  '3' END AS etat, "
                    + "C.codeclient, C.cin, concat(C.nom, ' ',C.prenom) AS nom_prenom_client, "
                    + "E.idcliententreprise, E.matricule_fiscale, E.nomentrepise "
                    + "FROM traite_clt T, factureclt F "
                    + "LEFT JOIN client C ON (C.local_nom= '"+ParametreSystem.NomLocalPC+"') AND (F.idcltexiste = C.codeclient) "
                    + "LEFT JOIN cltentreprise E ON (E.local_nom= '"+ParametreSystem.NomLocalPC+"') AND (F.idcltentreprise = E.idcliententreprise) "
                    + "WHERE (T.local_nom = '"+ParametreSystem.NomLocalPC+"') AND (T.id_factureclt = F.idfactureclt) "
                    + Where
                    + "LIMIT "+debut+" , "+nbr+" ;";
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            Date date_system = sdf.parse(sdf.format(new Date()));
            ResultSet resultat = h2jdbc.selectFromDB(req);
            while (resultat.next()){
                String NumTraite = resultat.getString("id_traite");
                String Facture  = resultat.getString("id_factureclt");
                String DatePayer = resultat.getString("date_paiement");
                String DateTraite = resultat.getString("date_traite");
                float FMontant = resultat.getFloat("montant_traite");
                //1 Payer       2 En Cours      3 En Retart
                String Etat = resultat.getString("etat");
                
                //0 Personne  1 Entreprise
                Integer Typeclt = resultat.getInt("typeclt");
                String TypeClient = ""; String CodeClt = ""; String NomPrenom = "";
                if(Typeclt == 0){
                    TypeClient = "Personne";
                    CodeClt = resultat.getString("codeclient");
                    NomPrenom = resultat.getString("nom_prenom_client");
                }if(Typeclt == 1){
                    TypeClient = "Entreprise";
                    CodeClt = resultat.getString("idcliententreprise");
                    NomPrenom = resultat.getString("nomentrepise");
                }
                DataListTraiteClt.add(new TraiteCltGestionListe(NumTraite, Etat, Facture, CodeClt, TypeClient, NomPrenom, Adaptateur.NormalDateFormat(DateTraite), Adaptateur.NormalDateFormat(DatePayer), "", FMontant));
            }
        } catch(SQLException ex){
            System.err.println("Erreur SQL ! \n"+ex.getMessage());
            System.out.println(req);
            if(ParametreSystem.ErrorShowLogger)
            {
                logger.error("TraiteCltGestionDB  : GetDetailTraite :" + ex.getMessage());
            }
            if(ParametreSystem.ErrorShowDialog)
            {
                ShowDialog.setTitre("Erreur SQL !");
                ShowDialog.setDetail(ex.getMessage()+"\n"+ex.getSQLState());
                SD.ShowAletDialog();
            }
        } catch (ParseException ex) {
            logger.error("TraiteCltGestionDB  : GetDetailTraite :" + ex.getMessage());
        }
        return DataListTraiteClt; 
    }
    
    
    public Integer nbrSearchTraiteClt(String idTraite, String idFactureclt, String dateTraite, String codeClient, String cin, String nom)
    {
        String Where = "";
        
        if(!clt.isNumericNotnull(idTraite)){
            Where += " (T.id_traite = '"+Adaptateur.addSlashes(idTraite)+"') AND ";
        }
        
        if(!clt.isNumericNotnull(idFactureclt)){
            Where += " (F.idfactureclt = '"+Adaptateur.addSlashes(idFactureclt)+"') AND ";
        }
        
        if(!clt.isNumericNotnull(codeClient)){
           Where += "( (F.idcltentreprise = '"+Adaptateur.addSlashes(codeClient)+"') OR (F.idcltexiste = '"+Adaptateur.addSlashes(codeClient)+"') ) AND ";
        }
        
        if(!clt.isStringNull(nom)){
            Where += "( (E.nomentrepise LIKE '%"+Adaptateur.addSlashes(nom)+"%') OR (C.nomcomplet LIKE '%"+Adaptateur.addSlashes(nom)+"%') ) AND "; 
        }
        
        if(!clt.isNumericNotnull(cin)){
            Where += "( (C.cin = '"+Adaptateur.addSlashes(cin)+"') OR (E.matricule_fiscale = '"+Adaptateur.addSlashes(cin)+"') ) AND ";
        }
        
        if(!clt.isStringNull(dateTraite)){
            Where += " (T.date_traite = '"+dateTraite+"') AND ";
        }
        
        if(!Where.equals("")){
            Where = " AND "+Where.substring(0, Where.length() - 4);
        }
        
        String req= "SELECT COUNT(*)"
                    + "FROM traite_clt T, factureclt F "
                    + "LEFT JOIN client C ON (C.local_nom= '"+ParametreSystem.NomLocalPC+"') AND (F.idcltexiste = C.codeclient) "
                    + "LEFT JOIN cltentreprise E ON (E.local_nom= '"+ParametreSystem.NomLocalPC+"') AND (F.idcltentreprise = E.idcliententreprise) "
                    + "WHERE (T.local_nom = '"+ParametreSystem.NomLocalPC+"') AND (T.id_factureclt = F.idfactureclt) "
                    + Where +" ;";            
        
        int sommme =0;
        try {
            ResultSet resultat = h2jdbc.selectFromDB(req);
            resultat.next();
            sommme = resultat.getInt(1);
        } catch(SQLException ex){
            System.err.println("nbrSearchTraiteClt Erreur SQL ! \n"+ex.getMessage());
            System.out.println(req);
            if(ParametreSystem.ErrorShowLogger)
            {
                logger.error("TraiteCltGestionDB  : nbrSearchTraiteClt :" + ex.getMessage());
            }
            if(ParametreSystem.ErrorShowDialog)
            {
                ShowDialog.setTitre("Erreur SQL !");
                ShowDialog.setDetail(ex.getMessage()+"\n"+ex.getSQLState());
                SD.ShowAletDialog();
            }
        }
        return sommme ;
    }
    
    
}
