package Models.VenteRapideClt;

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.Produit.ListeProduit;
import Models.Stock.StockDetail;
import Models.Stock.StockDetailDB;
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
 */
public class VenteSansFactureDB {
    
    connexion cnx = new connexion();
    
    contro clt = new contro();
    
    public boolean DeleteVenteSansFacture(VenteSansFacture Vente){
        
        String IdVenteSansFacture = Vente.getIdVenteSansFacture();
        String req = "UPDATE `vente_sans_facture` SET `operation` = '1', `date_operation` = CURTIME() WHERE `vente_sans_facture`.`id_vente_sans_facture` = "+IdVenteSansFacture+";" ;
        int updateVSF = cnx.MettreAJour(req);
        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));
                }
            }
            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 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 (CURTIME(), '"+Vente.getPaiement()+"', "+NomPrenomClient+", NULL, '"+Montant+"', "+IdChequeClt+", "+IdCarteBancaire+", '"+User.idprofile+"', '"+ParametreSystem.NomLocalPC+"');";
        
        String IdVenteSansFacture = cnx.InsertGetLastId(Query);
        
        Vente.setIdVenteSansFacture(IdVenteSansFacture);
        
        ObservableList<StockDetail> ListStockDetail = FXCollections.observableArrayList();
        
        String QueryProd = "INSERT INTO `liste_prod_vente_sans_facture` (`id_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 += "(NULL, '"+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));
            }
        }
        if(req != ""){
            req = req.substring(0, req.length()-1) + ";";
            if(cnx.insertion(QueryProd+req)){
                new StockDetailDB().InsertStockDetail(ListStockDetail);
                Caisse.setIdVenteSansFactureClt(IdVenteSansFacture);
                Caisse.setMontant(Montant);
                new CaisseDB().AddCaisse(Caisse);
            }
        }
        return Vente;
    }
    
    
    
    public VenteSansFacture getVenteSansFacture(String IdVenteSansFacture){
        VenteSansFacture venteSansFacture = new VenteSansFacture();
        
        String Query = "SELECT *, DATE_FORMAT(date_vente, '%d/%m/%Y %H:%i:%s') as datetime_vente FROM `vente_sans_facture` WHERE `id_vente_sans_facture` =  "+IdVenteSansFacture+";";
        
        if(cnx.ouverture()){
            try{
               ResultSet resultat = cnx.excutionquery(Query);
                //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){
                    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("Erreur SQL ! \n"+ex.getMessage());
                System.out.println(Query);
            }
        }
        
        return venteSansFacture;
    }
    
    
    
    
    public ObservableList<ListeProduit> getListProduit(String IdVenteSansFacture){
        ObservableList<ListeProduit> ListProd = FXCollections.observableArrayList();
        if(cnx.ouverture()){
            try{
                String Query = "SELECT * FROM `liste_prod_vente_sans_facture` WHERE `id_vente_sans_facture` = "+IdVenteSansFacture+";";
                ResultSet ResultListProd = cnx.excutionquery(Query);
                ResultListProd.beforeFirst();
                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("Erreur SQL ! \n"+ex.getMessage());
            }
        }
        return ListProd;
    }
    
    public ObservableList<ListeVenteSansFacture> SearchVenteSansFactureGestion(Integer debut, Integer nbr, String Code, String Montant, String Date){
        
        ObservableList<ListeVenteSansFacture> ListeVSF = FXCollections.observableArrayList();
        
        if(cnx.ouverture()){
            
            String WhereCondition  = "";
            
            if(!clt.isStringNull(Code)){
                WhereCondition += " (VSF.`id_vente_sans_facture` = '"+Code+"') AND";
            }
            if(!clt.isStringNull(Date)){
                WhereCondition += " (DATE(VSF.`date_vente`) = '"+Date+"' ) AND";
            }
            if(!clt.isStringNull(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`, DATE_FORMAT(VSF.`date_vente`, '%d/%m/%Y %H:%i:%s') AS `date_vente` , VSF.`paiement`, VSF.`nom_prenom_client`, VSF.`montant`, VSF.`operation`, DATE_FORMAT(VSF.`date_operation`, '%d/%m/%Y %H:%i:%s') 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 = cnx.excutionquery(Query);
                ResultListeVSF.beforeFirst();
                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("Erreur SQL ! \n"+Query);
                System.err.println("Erreur SQL ! \n"+ex.getMessage());
            }
        }
        return ListeVSF;
    }
    
    public Integer nbrVenteSansFactureGestion(String Code, String Montant, String Date)
    {
        String WhereCondition  = "";
            
        if(!clt.isStringNull(Code)){
            WhereCondition += " (VSF.`id_vente_sans_facture` = '"+Code+"') AND";
        }
        if(!clt.isStringNull(Date)){
            WhereCondition += " (DATE(VSF.`date_vente`) = '"+Date+"' ) AND";
        }
        if(!clt.isStringNull(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;
        
        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 ;
    }
    
}
