package Models.VenteRapideClt;

import Controllers.Dialog.ShowDialog;
import Controllers.Traitement.Adaptateur;
import Controllers.Traitement.ParametreSystem;
import Controllers.Traitement.contro;
import Models.Caisse.CaisseClt;
import Models.Caisse.CaisseDB;
import Models.Caisse.CarteBancaireClt;
import Models.Caisse.CarteBancaireCltDB;
import Models.ChequeClt.ChequeCltDB;
import Models.H2JDBC;
import Models.Produit.ListeProduit;
import Models.Stock.StockDetail;
import Models.Stock.StockDetailDB;
import Models.User.User;
import java.sql.ResultSet;
import java.sql.SQLException;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import org.apache.log4j.Logger;

/**
 * @author Maher
 */
public class VenteSansFactureDB {
    
    H2JDBC h2jdbc = new H2JDBC();
    ShowDialog SD = new ShowDialog();
    Logger logger = Logger.getLogger(VenteSansFactureDB.class.getName());
    
    contro clt = new contro();
    
    public boolean DeleteVenteSansFacture(VenteSansFacture Vente)
    {
        String IdVenteSansFacture = Vente.getIdVenteSansFacture();
        
        String req = "UPDATE vente_sans_facture SET operation = '1', date_operation = now() WHERE vente_sans_facture.id_vente_sans_facture = "+IdVenteSansFacture+";" ;
        int updateVSF = 0;
        try {
            updateVSF = h2jdbc.InsertUpdateDeleteInTable(req);
        }catch(SQLException ex){
            System.err.println("DeleteVenteSansFacture Erreur SQL ! \n"+ex.getMessage());
            System.out.println(req);
            if(ParametreSystem.ErrorShowLogger)
            {
                logger.error("VenteSansFactureDB  : DeleteVenteSansFacture :" + ex.getMessage());
            }
            if(ParametreSystem.ErrorShowDialog)
            {
                ShowDialog.setTitre("Erreur SQL !");
                ShowDialog.setDetail(ex.getMessage()+"\n"+ex.getSQLState());
                SD.ShowAletDialog();
            }
        }
        if(updateVSF>0){
            ObservableList<StockDetail> ListStockDetail = FXCollections.observableArrayList();
            for(ListeProduit listeprod : Vente.getListProduit()){
                if(listeprod.getReference() != ""){
                   ListStockDetail.add(new StockDetail(listeprod.getReference(), Adaptateur.StringToFloat(listeprod.getQuantite()), null, null, null, null, null, IdVenteSansFacture, Vente.getDateVente()));
                }
            }
            new StockDetailDB().InsertStockDetail(ListStockDetail);
            CaisseClt Caisse = new CaisseClt();
            Caisse.setTypeMouvement("6");
            Caisse.setIdVenteSansFactureClt(IdVenteSansFacture);
            Caisse.setMontant(Vente.getMontant().replace(",","."));
            new CaisseDB().AddCaisse(Caisse);
            return true;
        }
        return false;
    }
    
    public VenteSansFacture SetVenteSansFacture(VenteSansFacture Vente)
    {
        CaisseClt Caisse = new CaisseClt();
        Caisse.setTypeMouvement("5");
        
        String IdCarteBancaire = "null";
        String IdChequeClt = "null";
        if(Vente.getPaiement().equals("2")){
            CarteBancaireCltDB CarteBancaireDB = new CarteBancaireCltDB();
            CarteBancaireClt CarteBancaire = CarteBancaireDB.SetCarteBancaire(Vente.getCarteBancaire());
            Vente.setCarteBancaire(CarteBancaire);
            IdCarteBancaire = "'"+CarteBancaire.getIdCarteBancaire()+"'";
        }else if(Vente.getPaiement().equals("1")){
            ChequeCltDB ChequeDB = new ChequeCltDB();
            IdChequeClt = "'"+ChequeDB.AddChequeClt(Vente.getCheque())+"'";
        }
        
        String DateVente = "now()";
        if(!clt.isStringNull(Vente.getDateVente())){
            DateVente = "'"+Vente.getDateVente()+"'"; 
        }
        
        
        String NomPrenomClient = "null";
        if(Vente.getNomPrenomClient() != null){
            NomPrenomClient = "'"+Vente.getNomPrenomClient()+"'";
        }
        
        String Montant = Vente.getMontant().replace(",",".");
        
        String Query ="INSERT INTO vente_sans_facture (date_vente, paiement, nom_prenom_client, operation, montant, id_chequeclt, id_carte_bancaire, id_profile, local_nom) VALUES ("+DateVente+", '"+Vente.getPaiement()+"', "+NomPrenomClient+", null, '"+Montant+"', "+IdChequeClt+", "+IdCarteBancaire+", '"+User.idprofile+"', '"+ParametreSystem.NomLocalPC+"');";
        
        String IdVenteSansFacture = null;
        try {
            IdVenteSansFacture = h2jdbc.InsertGetLastId(Query);
        }catch(SQLException ex){
            System.err.println("Erreur SQL ! \n"+ex.getMessage());
            System.out.println(Query);
            if(ParametreSystem.ErrorShowLogger)
            {
                logger.error("VenteSansFactureDB  : SetVenteSansFacture :" + ex.getMessage());
            }
            if(ParametreSystem.ErrorShowDialog)
            {
                ShowDialog.setTitre("SetVenteSansFacture Erreur SQL !");
                ShowDialog.setDetail(ex.getMessage()+"\n"+ex.getSQLState());
                SD.ShowAletDialog();
            }
        }
        
        if(IdVenteSansFacture != null)
        {
            Vente.setIdVenteSansFacture(IdVenteSansFacture);
            
            ObservableList<StockDetail> ListStockDetail = FXCollections.observableArrayList();
        
            String QueryProd = "INSERT INTO liste_prod_vente_sans_facture (id_vente_sans_facture, produit_reference, designation_produit, quantite, p_u_h_t, remise, p_u_h_t_net, tva, montant, local_nom) VALUES  ";
            String req = "";  
            for(ListeProduit listeprod : Vente.getListProduit())
            {
                if(listeprod.getReference() != ""){
                   String PrixHT ; String Remise ; String TotalHT ; String TVA ; String TotalTTC ;
                    PrixHT = listeprod.getPrixHT().replace(",",".");
                    Remise= listeprod.getRemise().replace("%","").replace(",",".");
                    TotalHT= listeprod.getTotalHT().replace(",",".");
                    TVA=listeprod.getTVA().replace("%","").replace(",",".");
                    TotalTTC= listeprod.getTotalTTC().replace(",","."); 

                    req += "('"+IdVenteSansFacture+"', '"+listeprod.getReference()+"', '"+Adaptateur.addSlashes(listeprod.getDesignation())+"', '"+listeprod.getQuantite()+"', "+PrixHT+", '"+Remise+"', '"+TotalHT+"', '"+TVA+"', '"+TotalTTC+"', '"+ParametreSystem.NomLocalPC+"'),";
                    ListStockDetail.add(new StockDetail(listeprod.getReference(), Adaptateur.StringToFloat(listeprod.getQuantite())* -1, null, null, null, null, null, IdVenteSansFacture, Vente.getDateVente()));
                }
            }
            if(req != "")
            {
                req = req.substring(0, req.length()-1) + ";";
                try {
                    int nbr = h2jdbc.InsertUpdateDeleteInTable(QueryProd+req);
                    if(nbr>0){
                        new StockDetailDB().InsertStockDetail(ListStockDetail);
                        Caisse.setIdVenteSansFactureClt(IdVenteSansFacture);
                        Caisse.setMontant(Montant);
                        new CaisseDB().AddCaisse(Caisse);
                    }
                }catch(SQLException ex){
                    System.err.println("Erreur SQL ! \n"+ex.getMessage());
                    System.out.println(req);
                    if(ParametreSystem.ErrorShowLogger)
                    {
                        logger.error("VenteSansFactureDB  : SetVenteSansFacture :" + ex.getMessage());
                    }
                    if(ParametreSystem.ErrorShowDialog)
                    {
                        ShowDialog.setTitre("Erreur SQL !");
                        ShowDialog.setDetail(ex.getMessage()+"\n"+ex.getSQLState());
                        SD.ShowAletDialog();
                    }
                }
            }
        }
        return Vente;
    }
    
    
    
    public VenteSansFacture getVenteSansFacture(String IdVenteSansFacture)
    {
        VenteSansFacture venteSansFacture = new VenteSansFacture();
        
        String req = "SELECT *, to_char(date_vente, 'dd/mm/yyyy hh:ii:ss') as datetime_vente FROM vente_sans_facture WHERE id_vente_sans_facture =  "+IdVenteSansFacture+";";
        
        try {
            ResultSet resultat = h2jdbc.selectFromDB(req);
            while (resultat.next()){
                venteSansFacture.setIdVenteSansFacture(IdVenteSansFacture);
                    
                // 0:espèce | 1:chèque | 2:Carte bancaire
                venteSansFacture.setPaiement(resultat.getString("paiement"));
                if(venteSansFacture.getPaiement().equals("1")){
                    venteSansFacture.setCheque(new ChequeCltDB().getChequeClt(resultat.getString("id_chequeclt")));
                }else if(venteSansFacture.getPaiement().equals("2")){
                    venteSansFacture.setCarteBancaire(new CarteBancaireCltDB().getCarteBancaireClt(resultat.getString("id_carte_bancaire")));
                }
                
                venteSansFacture.setDateVente(resultat.getString("datetime_vente"));
                venteSansFacture.setFMontant(resultat.getFloat("montant"));
                venteSansFacture.setIdProfile(resultat.getInt("id_profile"));
                venteSansFacture.setLocalNom(resultat.getString("local_nom"));
                venteSansFacture.setMontant(resultat.getString("montant"));
                venteSansFacture.setNomPrenomClient(resultat.getString("nom_prenom_client"));
                
                venteSansFacture.setOperation(resultat.getString("operation"));
                venteSansFacture.setDateOperation(resultat.getString("date_operation"));
                        
                venteSansFacture.setListProduit(this.getListProduit(IdVenteSansFacture));
            }
        } catch(SQLException ex){
            System.err.println("getVenteSansFacture Erreur SQL ! \n"+ex.getMessage());
            System.out.println(req);
            if(ParametreSystem.ErrorShowLogger)
            {
                logger.error("VenteSansFactureDB  : getVenteSansFacture :" + ex.getMessage());
            }
            if(ParametreSystem.ErrorShowDialog)
            {
                ShowDialog.setTitre("Erreur SQL !");
                ShowDialog.setDetail(ex.getMessage()+"\n"+ex.getSQLState());
                SD.ShowAletDialog();
            }
        }
        return venteSansFacture;
    }
    
    
    
    
    public ObservableList<ListeProduit> getListProduit(String IdVenteSansFacture)
    {
        ObservableList<ListeProduit> ListProd = FXCollections.observableArrayList();
        
        String req = "SELECT * FROM liste_prod_vente_sans_facture WHERE id_vente_sans_facture = "+IdVenteSansFacture+";";
        
        try {
            ResultSet ResultListProd = h2jdbc.selectFromDB(req);
            while (ResultListProd.next()){
                String  reference = ResultListProd.getString("produit_reference");
                String  designation = ResultListProd.getString("designation_produit");
                String  quantite = ResultListProd.getString("quantite").replace(",",".");
                String  PrixHT = ResultListProd.getString("p_u_h_t").replace(",",".");
                String  Remise = ResultListProd.getString("remise").replace(",",".").replace("%","");
                String  TotalHT = ResultListProd.getString("p_u_h_t_net").replace(",",".");
                String  TVA = ResultListProd.getString("tva").replace(",",".").replace("%","");
                String  TotalTTC= ResultListProd.getString("montant").replace(",",".");
                ListProd.add(new ListeProduit(reference, designation, quantite, PrixHT, Remise, TotalHT, TVA, TotalTTC));
            }
        } catch(SQLException ex){
            System.err.println("getListProduit Erreur SQL ! \n"+ex.getMessage());
            System.out.println(req);
            if(ParametreSystem.ErrorShowLogger)
            {
                logger.error("VenteSansFactureDB  : getListProduit :" + ex.getMessage());
            }
            if(ParametreSystem.ErrorShowDialog)
            {
                ShowDialog.setTitre("Erreur SQL !");
                ShowDialog.setDetail(ex.getMessage()+"\n"+ex.getSQLState());
                SD.ShowAletDialog();
            }
        }
        return ListProd;
    }
    
    public ObservableList<ListeVenteSansFacture> SearchVenteSansFactureGestion(Integer debut, Integer nbr, String Code, String Montant, String Date)
    {
        ObservableList<ListeVenteSansFacture> ListeVSF = FXCollections.observableArrayList();
        String WhereCondition  = "";
            
        if(!clt.isNumericNotnull(Code)){
            WhereCondition += " (VSF.id_vente_sans_facture = '"+Code+"') AND";
        }
        if(!clt.isStringNull(Date)){
            WhereCondition += " (CAST(VSF.date_vente AS DATE) = '"+Date+"' ) AND";
        }
        if(!clt.isFloatNotnull(Montant)){
            WhereCondition += " (VSF.montant LIKE '%"+Montant+"%') AND";
        }
        
        if(!WhereCondition.equals("")){
            WhereCondition = WhereCondition.substring(0, WhereCondition.length() - 4);
            WhereCondition = "WHERE  " + WhereCondition;
        }
        
        String Query = "SELECT VSF.id_vente_sans_facture, to_char(VSF.date_vente, 'dd/mm/yyyy hh:ii:ss') AS date_vente , VSF.paiement, VSF.nom_prenom_client, VSF.montant, VSF.operation, to_char(VSF.date_operation, 'dd/mm/yyyy hh:ii:ss') AS dateOperation, (SELECT COUNT(*) FROM liste_prod_vente_sans_facture LPVSF WHERE LPVSF.id_vente_sans_facture = VSF.id_vente_sans_facture) AS nbr_prod "
                        + " FROM vente_sans_facture  VSF "
                        + WhereCondition
                        + " ORDER BY VSF.date_vente DESC "
                        + " LIMIT "+debut+" , "+nbr+";";
        try {
            ResultSet ResultListeVSF = h2jdbc.selectFromDB(Query);
            while (ResultListeVSF.next()){
                String  id_vente_sans_facture = ResultListeVSF.getString("id_vente_sans_facture");
                String  date_vente = ResultListeVSF.getString("date_vente");
                String  nbr_prod= ResultListeVSF.getString("nbr_prod");
                String  paiement = ResultListeVSF.getString("paiement");
                String  nom_prenom_client = ResultListeVSF.getString("nom_prenom_client");
                String  montant = Adaptateur.FloatToStringEspace(ResultListeVSF.getFloat("montant"));
                String  operation = ResultListeVSF.getString("operation");
                String  date_operation = ResultListeVSF.getString("dateOperation");
                
                ListeVSF.add(new ListeVenteSansFacture(id_vente_sans_facture, date_vente, nbr_prod, paiement, nom_prenom_client, montant, operation, date_operation));
            }
        } catch(SQLException ex){
            System.err.println("SearchVenteSansFactureGestion Erreur SQL ! \n"+ex.getMessage());
            System.out.println(Query);
            if(ParametreSystem.ErrorShowLogger)
            {
                logger.error("VenteSansFactureDB  : SearchVenteSansFactureGestion :" + ex.getMessage());
            }
            if(ParametreSystem.ErrorShowDialog)
            {
                ShowDialog.setTitre("Erreur SQL !");
                ShowDialog.setDetail(ex.getMessage()+"\n"+ex.getSQLState());
                SD.ShowAletDialog();
            }
        }
        return ListeVSF;
    }
    
    public Integer nbrVenteSansFactureGestion(String Code, String Montant, String Date)
    {
        String WhereCondition  = "";
            
        if(!clt.isNumericNotnull(Code)){
            WhereCondition += " (VSF.id_vente_sans_facture = '"+Code+"') AND";
        }
        if(!clt.isStringNull(Date)){
            WhereCondition += " (CAST(VSF.date_vente AS DATE) = '"+Date+"' ) AND";
        }
        if(!clt.isFloatNotnull(Montant)){
            WhereCondition += " (VSF.montant LIKE '%"+Montant+"%') AND";
        }
        
        if(!WhereCondition.equals("")){
            WhereCondition = WhereCondition.substring(0, WhereCondition.length() - 4);
            WhereCondition = "WHERE  " + WhereCondition;
        }
        
        String req=" SELECT COUNT(VSF.id_vente_sans_facture) " 
                    + " FROM vente_sans_facture VSF "
                    + WhereCondition+ " ;"; 
        
        int sommme =0;
        try {
            ResultSet resultat = h2jdbc.selectFromDB(req);
            resultat.next();
            sommme = resultat.getInt(1);
        } catch(SQLException ex){
            System.err.println("nbrVenteSansFactureGestion Erreur SQL ! \n"+ex.getMessage());
            System.out.println(req);
            if(ParametreSystem.ErrorShowLogger)
            {
                logger.error("VenteSansFactureDB  : nbrVenteSansFactureGestion :" + ex.getMessage());
            }
            if(ParametreSystem.ErrorShowDialog)
            {
                ShowDialog.setTitre("Erreur SQL !");
                ShowDialog.setDetail(ex.getMessage()+"\n"+ex.getSQLState());
                SD.ShowAletDialog();
            }
        }
        return sommme ;
    }
    
}
