
package Models.Caisse;

import Controllers.Dialog.ShowDialog;
import Controllers.Traitement.Adaptateur;
import Controllers.Traitement.ParametreSystem;
import Controllers.Traitement.contro;
import Models.H2JDBC;
import Models.User.Profile;
import Models.User.ProfileDB;
import java.sql.ResultSet;
import java.sql.SQLException;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import org.apache.log4j.Logger;

/**
 * @author Maher Ben Tili
 */
public class FraisDB {
    
    H2JDBC h2jdbc = new H2JDBC();
    ShowDialog SD = new ShowDialog();
    Logger logger = Logger.getLogger(FraisDB.class.getName()); 
    contro clt = new contro();
    
    public Frais getFrais(String IdFrais)
    {
        Frais frais = new Frais();
        String req = "SELECT *, to_char(date_cheque, 'dd/mm/yyyy') as datecheque, to_char(date_creation, 'dd/mm/yyyy hh:ii') as datecreation FROM frais WHERE id_frais = "+IdFrais+" ;";
        try {
            ResultSet resultat = h2jdbc.selectFromDB(req);
            while (resultat.next()){
                frais.setIdFrais(resultat.getString("id_frais"));
                frais.setMontant(Adaptateur.FloatToStringEspaceCurrency(resultat.getFloat("montant")));
                frais.setObject(resultat.getString("object"));
                frais.setContext(resultat.getString("context"));
                frais.setPersonne(resultat.getString("personne"));
                frais.setPaiement(resultat.getString("mode_paiement"));
                frais.setNumero(resultat.getString("numero"));
                frais.setBanque(resultat.getString("banque"));
                frais.setDateCheque(resultat.getString("datecheque"));
                frais.setLocalNom(resultat.getString("local_nom"));
                frais.setDateCreation(resultat.getString("datecreation"));
                
                Profile profile = new ProfileDB().getpro(resultat.getInt("id_profile"));
                frais.setProfile(profile.getNom()+" "+profile.getPrenom());
            }
        } catch(SQLException ex){
            System.err.println("getFrais Erreur SQL ! \n"+ex.getMessage());
            System.out.println(req);
            if(ParametreSystem.ErrorShowLogger)
            {
                logger.error("FraisDB  : getFrais :" + ex.getMessage());
            }
            if(ParametreSystem.ErrorShowDialog)
            {
                ShowDialog.setTitre("Erreur SQL !");
                ShowDialog.setDetail(ex.getMessage()+"\n"+ex.getSQLState());
                SD.ShowAletDialog();
            }
        }
        return frais;
    }
    
    public Frais setFrais(Frais frais)
    {
        String Context = "NULL";
        if(frais.getContext() != null){
            Context = "'"+frais.getContext().replace("'", "''").replace("'", "''")+"'";
        }
        String Personne = "NULL";
        if(frais.getPersonne() != null){
            Personne = "'"+frais.getPersonne()+"'";
        }
        
        String Numero = "NULL";
        if(frais.getNumero() != null){
            Numero = "'"+frais.getNumero()+"'";
        }
        
        String Banque = "NULL";
        if(frais.getBanque()!= null){
            Banque = "'"+frais.getBanque()+"'";
        }
        
        String DateCheque = "NULL";
        if(frais.getDateCheque()!= null){
            DateCheque = "'"+frais.getDateCheque()+"'";
        }
        
        String req = "INSERT INTO frais (montant, object, context, personne, mode_paiement, numero, banque, date_cheque, id_profile, local_nom, date_creation) VALUES ('"+frais.getMontant()+"', '"+frais.getObject()+"', "+Context+", "+Personne+", '"+frais.getPaiement()+"', "+Numero+", "+Banque+", "+DateCheque+", '"+frais.getProfile()+"', '"+frais.getLocalNom()+"', '"+frais.getDateCreation()+"');";
        
        String  IdFrais = null;
        try {
            IdFrais = h2jdbc.InsertGetLastId(req);
            frais.setIdFrais(IdFrais);
        }catch(SQLException ex){
            System.err.println("setFrais Erreur SQL ! \n"+ex.getMessage());
            System.out.println(req);
            if(ParametreSystem.ErrorShowLogger)
            {
                logger.error("FraisDB  : setFrais :" + ex.getMessage());
            }
            if(ParametreSystem.ErrorShowDialog)
            {
                ShowDialog.setTitre("Erreur SQL !");
                ShowDialog.setDetail(ex.getMessage()+"\n"+ex.getSQLState());
                SD.ShowAletDialog();
            }
        }
        return frais;
    }
    
    public ObservableList<Frais> SearchFraisGestion(Integer debut, Integer nbr, String CodeFrais, String ObjectFrais, String Presonne, String Locale, String Paiement, String DateCreation )
    {
        ObservableList<Frais> ListFrais =FXCollections.observableArrayList();
        
        String Where = "";
        
        if(!clt.isNumericNotnull(CodeFrais)){
            Where += " (id_frais = '"+CodeFrais+"') AND ";
        }
        
        if(!clt.isStringNull(ObjectFrais)){
            Where += " (object LIKE '%"+Adaptateur.addSlashes(ObjectFrais)+"%') AND ";
        }
        
        if(!clt.isStringNull(Presonne)){
            Where += " (personne LIKE '%"+Adaptateur.addSlashes(Presonne)+"%') AND ";
        }
        
        if(!clt.isStringNull(Locale)){
            Where += " (local_nom LIKE '"+Adaptateur.addSlashes(Locale)+"') AND ";
        }
        
        if(!clt.isStringNull(Paiement)){
            if(Paiement.equals("Espèces")){
                Where += " (mode_paiement = '0') AND ";
            }else if(Paiement.equals("Chèque")){
                Where += " (mode_paiement = '1') AND ";
            }else if(Paiement.equals("Carte Bancaire")){
                Where += " (mode_paiement = '2') AND ";
            }
        }
        
        if(!clt.isStringNull(DateCreation)){
            Where += " (CAST(frais.date_creation AS DATE) = '"+DateCreation+"') AND ";
        }
        
       
        if(!Where.equals("")){
            Where = Where.substring(0, Where.length() - 4);
            Where = "WHERE  (id_profile = idprofile) AND " + Where;
        }else{
            Where = " WHERE (id_profile = idprofile) ";
        }
        
        String req = "SELECT  *, to_char(frais.date_creation, 'dd/mm/yyyy hh:ii') as date_creat "
                + " FROM frais, profile "
                + Where
                + "ORDER BY id_frais DESC "
                + "LIMIT "+debut+" , "+nbr+" ;";
        
        try {
            ResultSet resultat = h2jdbc.selectFromDB(req);
            while (resultat.next()){
                Frais frais = new Frais();
                frais.setIdFrais(resultat.getString("id_frais"));
                frais.setMontant(Adaptateur.FloatToStringEspace(resultat.getFloat("montant")));
                frais.setObject(resultat.getString("object"));
                frais.setContext(resultat.getString("context"));
                frais.setPersonne(resultat.getString("personne"));
                frais.setPaiement(resultat.getString("mode_paiement"));
                frais.setNumero(resultat.getString("numero"));
                frais.setBanque(resultat.getString("banque"));
                frais.setLocalNom(resultat.getString("local_nom"));
                frais.setDateCreation(resultat.getString("date_creat"));
                frais.setProfile(resultat.getString("prenom")+" "+resultat.getString("nom"));
                ListFrais.add(frais);
            }
        } catch(SQLException ex){
            System.err.println("SearchFraisGestion Erreur SQL ! \n"+ex.getMessage());
            System.out.println(req);
            if(ParametreSystem.ErrorShowLogger)
            {
                logger.error("FraisDB  : SearchFraisGestion :" + ex.getMessage());
            }
            if(ParametreSystem.ErrorShowDialog)
            {
                ShowDialog.setTitre("Erreur SQL !");
                ShowDialog.setDetail(ex.getMessage()+"\n"+ex.getSQLState());
                SD.ShowAletDialog();
            }
        }  
        return ListFrais;
    }
    
    public Integer nbrFraisGestion(String CodeFrais, String ObjectFrais, String Presonne, String Locale, String Paiement, String DateCreation )
    {
        String Where = "";
        
        if(!clt.isNumericNotnull(CodeFrais)){
            Where += " (id_frais = '"+CodeFrais+"') AND ";
        }
        
        if(!clt.isStringNull(ObjectFrais)){
            Where += " (object LIKE '%"+Adaptateur.addSlashes(ObjectFrais)+"%') AND ";
        }
        
        if(!clt.isStringNull(Presonne)){
            Where += " (personne LIKE '%"+Adaptateur.addSlashes(Presonne)+"%') AND ";
        }
        
        if(!clt.isStringNull(Locale)){
            Where += " (local_nom LIKE '"+Adaptateur.addSlashes(Locale)+"') AND ";
        }
        
        if(!clt.isStringNull(Paiement)){
            if(Paiement.equals("Espèces")){
                Where += " (mode_paiement = '0') AND ";
            }else if(Paiement.equals("Chèque")){
                Where += " (mode_paiement = '1') AND ";
            }else if(Paiement.equals("Carte Bancaire")){
                Where += " (mode_paiement = '2') AND ";
            }
        }
        
        if(!clt.isStringNull(DateCreation)){
            Where += " (CAST(date_creation AS DATE) = '"+DateCreation+"') AND ";
        }
        
       
        if(!Where.equals("")){
            Where = Where.substring(0, Where.length() - 4);
            Where = "WHERE " + Where;
        }
        
        String req = "SELECT  COUNT(id_frais) "
                + " FROM frais "
                + Where +" ;";
        
        int sommme =0;
        
        try {
            ResultSet resultat = h2jdbc.selectFromDB(req);
            resultat.next();
            sommme = resultat.getInt(1);
        } catch(SQLException ex){
            System.err.println("Erreur SQL ! \n"+ex.getMessage());
            System.out.println(req);
            if(ParametreSystem.ErrorShowLogger)
            {
                logger.error("FraisDB  : nbrFraisGestion :" + ex.getMessage());
            }
            if(ParametreSystem.ErrorShowDialog)
            {
                ShowDialog.setTitre("Erreur SQL !");
                ShowDialog.setDetail(ex.getMessage()+"\n"+ex.getSQLState());
                SD.ShowAletDialog();
            }
        }
        return sommme ;
    }
   
    
    
}
