/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Models.TraiteClt;

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.User.User;
import Models.connexion;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;

/**
 *
 * @author PC-Maher
 */
public class TraiteCltDB {
    
    connexion cnx = new connexion();
    contro clt = new contro();
    
    public Map GetChequePaiementTraite(String  IdTraitePaiementCheque){
        
        Map<String, String> map = new HashMap<>();
        
        String Query  = " SELECT t_p_c_clt.numero, t_p_c_clt.banque, t_clt.id_traite, " +
                        " CASE " +
                        "    WHEN f_clt.typeclt = 0 THEN c.nom " +
                        "    WHEN f_clt.typeclt = 1 THEN e_clt.nomentrepise " +
                        "    WHEN f_clt.typeclt = 2 THEN p_clt.nom " +
                        " END AS Nom, " +
                        " CASE " +
                        "    WHEN f_clt.typeclt = 0 THEN c.prenom " +
                        "    WHEN f_clt.typeclt = 1 THEN e_clt.matricule_fiscale " +
                        "    WHEN f_clt.typeclt = 2 THEN p_clt.prenom " +
                        " END AS Prenom " +
                        " FROM traite_paiement_cheque_clt t_p_c_clt, traite_clt t_clt, factureclt f_clt " +
                        " LEFT JOIN cltentreprise e_clt ON (f_clt.idcltentreprise = e_clt.idcliententreprise) AND (e_clt.local_nom = '"+ParametreSystem.NomLocalPC+"')" +
                        " LEFT JOIN client c ON (f_clt.idcltexiste = c.codeclient) AND (c.local_nom = '"+ParametreSystem.NomLocalPC+"')" +
                        " LEFT JOIN cltpassageur p_clt ON (f_clt.idcltpassageur = p_clt.idcltpassageur) AND (p_clt.local_nom = '"+ParametreSystem.NomLocalPC+"')" +
                        " WHERE (t_p_c_clt.id_traite_paiement_cheque = "+IdTraitePaiementCheque+")   AND (t_clt.id_traite = t_p_c_clt.id_traite) AND (t_clt.id_factureclt = f_clt.idfactureclt) AND (t_p_c_clt.local_nom = '"+ParametreSystem.NomLocalPC+"');";
        
        if(cnx.ouverture()){
            try {
                
                ResultSet resultat= cnx.Fetch(Query);
                
                map.put("IdTraite", resultat.getString("id_traite"));
                map.put("Nom", resultat.getString("nom"));
                map.put("Prenom", resultat.getString("prenom"));
                map.put("numero", resultat.getString("numero"));
                map.put("banque", resultat.getString("banque"));
                
            } catch (SQLException ex) {
                System.err.println("Erreur SQL ! \n"+ex.getMessage());
                System.out.println("req "+Query);
            }
        }
        
        return map;
    }
    
    public Map GetCartePaiementTraite(String  id_traite_paiement_carte){
        
        Map<String, String> map = new HashMap<>();
        
        String Query  = " SELECT t_p_c_clt.numero_carte, t_p_c_clt.banque, t_clt.id_traite," +
                        " CASE " +
                        "    WHEN f_clt.typeclt = 0 THEN c.nom " +
                        "    WHEN f_clt.typeclt = 1 THEN e_clt.nomentrepise " +
                        "    WHEN f_clt.typeclt = 2 THEN p_clt.nom " +
                        " END AS Nom, " +
                        " CASE " +
                        "    WHEN f_clt.typeclt = 0 THEN c.prenom " +
                        "    WHEN f_clt.typeclt = 1 THEN e_clt.matricule_fiscale " +
                        "    WHEN f_clt.typeclt = 2 THEN p_clt.prenom " +
                        " END AS Prenom " +
                        " FROM traite_paiement_carte_clt t_p_c_clt, traite_clt t_clt, factureclt f_clt " +
                        " LEFT JOIN cltentreprise e_clt ON (f_clt.idcltentreprise = e_clt.idcliententreprise) AND (e_clt.local_nom = '"+ParametreSystem.NomLocalPC+"')" +
                        " LEFT JOIN client c ON (f_clt.idcltexiste = c.codeclient) AND (c.local_nom = '"+ParametreSystem.NomLocalPC+"')" +
                        " LEFT JOIN cltpassageur p_clt ON (f_clt.idcltpassageur = p_clt.idcltpassageur) AND (p_clt.local_nom = '"+ParametreSystem.NomLocalPC+"')" +
                        " WHERE (t_p_c_clt.id_traite_paiement_carte = "+id_traite_paiement_carte+")  AND (t_clt.id_traite = t_p_c_clt.id_traite) AND (t_clt.id_factureclt = f_clt.idfactureclt) AND (t_p_c_clt.local_nom = '"+ParametreSystem.NomLocalPC+"');";
        
        if(cnx.ouverture()){
            try {
                
                ResultSet resultat= cnx.Fetch(Query);
                
                map.put("IdTraite", resultat.getString("id_traite"));
                map.put("Nom", resultat.getString("nom"));
                map.put("Prenom", resultat.getString("prenom"));
                map.put("numero_carte", resultat.getString("numero_carte"));
                map.put("banque", resultat.getString("banque"));
                
            } catch (SQLException ex) {
                System.err.println("Erreur SQL ! \n"+ex.getMessage());
                System.out.println("req "+Query);
            }
        }
        
        return map;
    }
    
    public Map GetEspacePaiementTraite(String  id_traite_paiement_espace){
        
        Map<String, String> map = new HashMap<>();
        
        String Query  = " SELECT " +
                        " t_clt.id_traite, " +    
                        " CASE " +
                        "    WHEN f_clt.typeclt = 0 THEN c.nom " +
                        "    WHEN f_clt.typeclt = 1 THEN e_clt.nomentrepise " +
                        "    WHEN f_clt.typeclt = 2 THEN p_clt.nom " +
                        " END AS Nom, " +
                        " CASE " +
                        "    WHEN f_clt.typeclt = 0 THEN c.prenom " +
                        "    WHEN f_clt.typeclt = 1 THEN e_clt.matricule_fiscale " +
                        "    WHEN f_clt.typeclt = 2 THEN p_clt.prenom " +
                        " END AS Prenom " +
                        " FROM traite_paiement_espace_clt t_p_e_clt, traite_clt t_clt, factureclt f_clt " +
                        " LEFT JOIN cltentreprise e_clt ON (f_clt.idcltentreprise = e_clt.idcliententreprise) AND (e_clt.local_nom = '"+ParametreSystem.NomLocalPC+"')" +
                        " LEFT JOIN client c ON (f_clt.idcltexiste = c.codeclient) AND (c.local_nom = '"+ParametreSystem.NomLocalPC+"')" +
                        " LEFT JOIN cltpassageur p_clt ON (f_clt.idcltpassageur = p_clt.idcltpassageur) AND (p_clt.local_nom = '"+ParametreSystem.NomLocalPC+"')" +
                        " WHERE (t_p_e_clt.id_traite_paiement_espace = "+id_traite_paiement_espace+")  AND (t_clt.id_traite = t_p_e_clt.id_traite) AND (t_clt.id_factureclt = f_clt.idfactureclt) AND (t_p_e_clt.local_nom = '"+ParametreSystem.NomLocalPC+"');";
        
        if(cnx.ouverture()){
            try {
                
                ResultSet resultat= cnx.Fetch(Query);
                
                map.put("IdTraite", resultat.getString("id_traite"));
                map.put("Nom", resultat.getString("nom"));
                map.put("Prenom", resultat.getString("prenom"));
                
            } catch (SQLException ex) {
                System.err.println("Erreur SQL ! \n"+ex.getMessage());
                System.out.println("req "+Query);
            }
        }
        
        return map;
    }
    
    public void AddListeTraiteClt(ArrayList<TraiteClt> ListTraites, String CodeFactureClt){
        String ReqTraiClt = "INSERT INTO traite_clt (`date_traite`,  `montant_traite`, `date_creation`, `id_factureclt`, `local_nom`, id_profile) VALUES ";    
        String Req = "";  
        
        for(int i=0; i<ListTraites.size(); i++){
           String montant_traite = ListTraites.get(i).getMontantTraiteClt().replace(",",".");
                String date_traite =  Adaptateur.DatabaseDateFormat(ListTraites.get(i).getDateTraiteClt());
                String code_facture = ListTraites.get(i).getCodeFactureClt();
            if(code_facture == null){
                code_facture = CodeFactureClt;
            }
            Req = Req + "( '"+date_traite+"',  "+montant_traite+", CURTIME(), "+code_facture+", '"+ParametreSystem.NomLocalPC+"', "+User.idprofile+"),";
        }
        if(Req != null){
            ReqTraiClt = ReqTraiClt + Req.substring(0, Req.length()-1) + ";";
            cnx.insertion(ReqTraiClt);
        }
    }
    
    public String SetPayerTraiteEnEspaceDB(String IdTraite, Float NewMontantPayer, Float OldMontantPayer){
        String QueryTraitePayementEspace = "INSERT INTO `traite_paiement_espace_clt` (`id_traite`, `montant_payer`, `local_nom`, `id_profile`) VALUES ('"+IdTraite+"', '"+NewMontantPayer+"', '"+ParametreSystem.NomLocalPC+"', "+User.idprofile+")";
        String IdTraitePayement = cnx.InsertGetLastId(QueryTraitePayementEspace);
        
        CaisseClt Caisse = new CaisseClt();
        Caisse.setIdTraitePaiementEspace(IdTraitePayement);
        Caisse.setTypeMouvement("3");
        Caisse.setMontant(NewMontantPayer.toString());
        new CaisseDB().AddCaisse(Caisse);
        
        Float TotalMontantPayer = NewMontantPayer + OldMontantPayer;
        String QueryTraite = "UPDATE traite_clt SET date_paiement = CURTIME(), `montant_payer` = '"+TotalMontantPayer+"' WHERE (`id_traite` = '"+IdTraite+"') AND (`local_nom` LIKE '"+ParametreSystem.NomLocalPC+"') ";
        cnx.MettreAJour(QueryTraite);
        
        return IdTraitePayement;
    }
    
    
    public String SetPayerTraiteEnChequeDB(String IdTraite, Float NewMontantPayer, Float OldMontantPayer, String Banque, String NumerCheque, String DateCheque){
        String QueryTraitePayementCheque = "INSERT INTO `traite_paiement_cheque_clt` (`id_traite`, `montant_payer`, `numero`,  `banque`, `local_nom`, `id_profile`, `date_payer`) VALUES ('"+IdTraite+"', '"+NewMontantPayer+"', '"+NumerCheque+"', '"+Banque+"',  '"+ParametreSystem.NomLocalPC+"', "+User.idprofile+",  '"+DateCheque+"')";
        String IdTraitePayement = cnx.InsertGetLastId(QueryTraitePayementCheque);
        
        CaisseClt Caisse = new CaisseClt();
        Caisse.setIdTraitePaiementCheque(IdTraitePayement);
        Caisse.setTypeMouvement("3");
        Caisse.setMontant(NewMontantPayer.toString());
        new CaisseDB().AddCaisse(Caisse);
        
        
        Float TotalMontantPayer = NewMontantPayer + OldMontantPayer;
        String QueryTraite = "UPDATE traite_clt SET date_paiement = CURTIME(), `montant_payer` = '"+TotalMontantPayer+"' WHERE (`id_traite` = '"+IdTraite+"') AND (`local_nom` LIKE '"+ParametreSystem.NomLocalPC+"') ";
        cnx.MettreAJour(QueryTraite);
        
        return IdTraitePayement;
    }
    
    public String SetPayerTraiteEnCarteDB(String IdTraite, Float NewMontantPayer, Float OldMontantPayer, String Banque, String NumerCarte){
        String QueryTraitePayementCarte = "INSERT INTO `traite_paiement_carte_clt` (`id_traite`, `montant_payer`, `numero_carte`,  `banque`, `local_nom`, `id_profile`) VALUES ('"+IdTraite+"', '"+NewMontantPayer+"', '"+NumerCarte+"', '"+Banque+"',  '"+ParametreSystem.NomLocalPC+"', "+User.idprofile+")";
        String IdTraitePayement = cnx.InsertGetLastId(QueryTraitePayementCarte);
        
        CaisseClt Caisse = new CaisseClt();
        Caisse.setIdTraitePaiementCarte(IdTraitePayement);
        Caisse.setTypeMouvement("3");
        Caisse.setMontant(NewMontantPayer.toString());
        new CaisseDB().AddCaisse(Caisse);
        
        
        Float TotalMontantPayer = NewMontantPayer + OldMontantPayer;
        String QueryTraite = "UPDATE traite_clt SET date_paiement = CURTIME(), `montant_payer` = '"+TotalMontantPayer+"' WHERE (`id_traite` = '"+IdTraite+"') AND (`local_nom` LIKE '"+ParametreSystem.NomLocalPC+"') ";
        cnx.MettreAJour(QueryTraite);
        
        return IdTraitePayement;
    }
    
    public ObservableList<TraiteCltPaiementListe> getListPaiementTraiteClt(String IdTraite){
        
        ObservableList<TraiteCltPaiementListe> DataPaiementList = FXCollections.observableArrayList();
        
        String QueryEspace = "SELECT id_traite_paiement_espace AS id_traite_paiement, 'espace' AS 'type', '' AS banque, '' AS numero, DATE_FORMAT(date_payer, '%d/%m/%Y') AS date_paiement, DATE_FORMAT(date_payer, '%H:%i:%s') AS heur_paiement, montant_payer FROM `traite_paiement_espace_clt` WHERE (`id_traite` = '"+IdTraite+"') AND (local_nom = '"+ParametreSystem.NomLocalPC+"')" +
        " UNION ALL " +
        "SELECT id_traite_paiement_cheque AS id_traite_paiement, 'chèque' AS 'type', banque, numero, DATE_FORMAT(date_payer, '%d/%m/%Y') AS date_paiement, DATE_FORMAT(date_payer, '%H:%i:%s') AS heur_paiement, montant_payer FROM traite_paiement_cheque_clt WHERE (`id_traite` = '"+IdTraite+"') AND (local_nom = '"+ParametreSystem.NomLocalPC+"')" +
        " UNION ALL " +
        "SELECT id_traite_paiement_carte AS id_traite_paiement, 'carte bancaire' AS 'type', banque, numero_carte AS numero, DATE_FORMAT(date_payer, '%d/%m/%Y') AS date_paiement, DATE_FORMAT(date_payer, '%H:%i:%s') AS heur_paiement, montant_payer FROM traite_paiement_carte_clt WHERE (`id_traite` = '"+IdTraite+"') AND (local_nom = '"+ParametreSystem.NomLocalPC+"');";
        if(cnx.ouverture()){
            try{
                ResultSet Resultat = cnx.excutionquery(QueryEspace);
                Resultat.last();
                int nombreLignes = Resultat.getRow();
                if(nombreLignes>0){
                    Resultat.beforeFirst();
                    while (Resultat.next()){
                        String id_paiement = Resultat.getString("id_traite_paiement");
                        String montant_paiement = Resultat.getString("montant_payer");
                        String date_paiement = Resultat.getString("date_paiement");
                        String heur_paiement = Resultat.getString("heur_paiement");
                        String type = Resultat.getString("type");
                        String banque = Resultat.getString("banque");
                        String numero = Resultat.getString("numero");
                        DataPaiementList.add(new TraiteCltPaiementListe( id_paiement, type,  montant_paiement,  date_paiement, heur_paiement, banque, numero));
                    }
                }
            }catch(SQLException ex){
                System.err.println("Erreur SQL ! \n"+ex.getMessage());
                System.out.println(QueryEspace);
            }
        }
        return DataPaiementList;
    }
    
    public ObservableList SearchTraiteCltRetard(Integer debut, Integer nbr, String DateDebut, String IdFacture, String NomLocal, String CodeClt, String CINClt, String NomClt, boolean All)
    {
        String WhereReq1 = " WHERE (T.date_paiement IS NULL) AND (T.date_traite < now()) AND (T.id_factureclt = F.idfactureclt) AND ";
        
        if(!clt.isStringNull(NomLocal)){
            WhereReq1 += " (T.local_nom = \""+NomLocal+"\") AND ";
        }
        
        if(!clt.isStringNull(IdFacture)){
            WhereReq1 += " (T.id_factureclt = \""+IdFacture+"\") AND ";
        }
        
        if(!clt.isStringNull(DateDebut)){
            WhereReq1 += " (T.date_traite >= \""+DateDebut+"\") AND ";
        }
        
        if(!clt.isStringNull(CodeClt)){
            WhereReq1 += " ( (C.codeclient = \""+CodeClt+"\") OR (E.idcliententreprise = \""+CodeClt+"\" ) ) AND ";
        }
        
        if(!clt.isStringNull(CINClt)){
            WhereReq1 += " ( (C.cin LIKE \"%"+CINClt+"%\") OR (E.matricule_fiscale LIKE \"%"+CINClt+"%\") ) AND ";
        }
        
        if(!clt.isStringNull(NomClt)){
            WhereReq1 += " ( (C.nom LIKE \"%"+NomClt+"%\") OR (E.nomentrepise LIKE \"%"+NomClt+"%\") OR (C.prenom LIKE \"%"+NomClt+"%\") OR (C.prenom LIKE \"%"+NomClt+"%\") OR (E.matricule_fiscale LIKE \"%"+NomClt+"%\") ) AND ";
        }
        
        WhereReq1 = WhereReq1.substring(0, WhereReq1.length() - 4);
        
        ObservableList<TraiteCltGestionListe> DataListTraiteClt = FXCollections.observableArrayList();
        
        String Limit = "";
        if(All == false){
            Limit = " LIMIT "+debut+" , "+nbr+" ;";
        }
        String req= "SELECT T.*, F.typeclt, DATE_FORMAT(T.date_traite, '%d/%m/%Y') AS DateTraite, "
                    + " 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  (F.idcltexiste = C.codeclient) "
                    + " LEFT JOIN `cltentreprise` E ON (F.idcltentreprise = E.idcliententreprise) "
                    + WhereReq1
                    + Limit ;
        
        ResultSet resultat= cnx.FetchALL(req);
            
        try{
                
            while ( resultat.next() ) {
                String NumTraite = resultat.getString("id_traite");
                String Facture  = resultat.getString("id_factureclt");
                String DateTraite = resultat.getString("DateTraite");
                String MontantTraite = Adaptateur.StringToStringEspace(resultat.getString("montant_traite"));
                String LocalNom = resultat.getString("local_nom");
                float FMontant = resultat.getFloat("montant_traite");
                
                //0 Personne  1 Entreprise
                Integer Typeclt = resultat.getInt("typeclt");
                 
                String CodeClient = ""; 
                String NomPrenom = "";
                if(Typeclt == 0){
                    CodeClient = resultat.getString("codeclient");
                    NomPrenom = resultat.getString("nom_prenom_client");
                }if(Typeclt == 1){
                    CodeClient = resultat.getString("idcliententreprise");
                    NomPrenom = resultat.getString("nomentrepise");
                }
                
                DataListTraiteClt.add(new TraiteCltGestionListe(NumTraite, "", Facture, CodeClient, LocalNom, NomPrenom, DateTraite, "", MontantTraite, FMontant));
            }
        } catch(SQLException ex){
                ShowDialog.setTitre("Erreur SQL !");
                ShowDialog.setDetail(ex.getMessage()+"\n"+ex.getSQLState());
                ShowDialog SD = new ShowDialog();
                SD.ShowAletDialog();
        }
        return DataListTraiteClt;
    }
    
    
    public Integer nbrTraiteCltRetard(String DateDebut, String IdFacture, String NomLocal, String CodeClt, String CINClt, String NomClt)
    {
        String WhereReq1 = " WHERE (T.date_paiement IS NULL) AND (T.date_traite < now()) AND (T.id_factureclt = F.idfactureclt) AND ";
        
        if(!clt.isStringNull(NomLocal)){
            WhereReq1 += " (T.local_nom = \""+NomLocal+"\") AND ";
        }
        
        if(!clt.isStringNull(IdFacture)){
            WhereReq1 += " (T.id_factureclt = \""+IdFacture+"\") AND ";
        }
        
        if(!clt.isStringNull(DateDebut)){
            WhereReq1 += " (T.date_traite >= \""+DateDebut+"\") AND ";
        }
        
        if(!clt.isStringNull(CodeClt)){
            WhereReq1 += " ( (C.codeclient = \""+CodeClt+"\") OR (E.idcliententreprise = \""+CodeClt+"\" ) ) AND ";
        }
        
        if(!clt.isStringNull(CINClt)){
            WhereReq1 += " ( (C.cin LIKE \"%"+CINClt+"%\") OR (E.matricule_fiscale LIKE \"%"+CINClt+"%\") ) AND ";
        }
        
        if(!clt.isStringNull(NomClt)){
            WhereReq1 += " ( (C.nom LIKE \"%"+NomClt+"%\") OR (E.nomentrepise LIKE \"%"+NomClt+"%\") OR (C.prenom LIKE \"%"+NomClt+"%\") OR (C.prenom LIKE \"%"+NomClt+"%\") OR (E.matricule_fiscale LIKE \"%"+NomClt+"%\") ) AND ";
        }
        
        WhereReq1 = WhereReq1.substring(0, WhereReq1.length() - 4);
        
        
        String req =  " SELECT COUNT(T.id_traite) "
                    + " FROM `traite_clt` T, `factureclt` F "
                    + " LEFT JOIN `client` C ON  (F.idcltexiste = C.codeclient) "
                    + " LEFT JOIN `cltentreprise` E ON (F.idcltentreprise = E.idcliententreprise) "
                    + WhereReq1 + " ; "; 
        
        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 ;
    }
    
    
}
