
package Controllers.Reglement;

import Controllers.Traitement.Adaptateur;
import Controllers.Traitement.contro;
import Models.ChequeClt.ChequeList;
import Models.TraiteClt.DatePickerCell;
import Models.ChequeClt.DatePickerCellCheque;
import Models.FactureFrs.FactureFrs;
import Models.Reglement.CarteElectroniqueFrs;
import Models.Reglement.ChequeFrs;
import Models.Reglement.Reglement;
import Models.Reglement.TraiteFrs;
import Models.TraiteClt.TraiteList;
import java.io.IOException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;
import java.util.ResourceBundle;

import org.apache.log4j.Logger;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.fxml.Initializable;
import javafx.scene.Parent;
import javafx.scene.control.DatePicker;
import javafx.scene.control.TableCell;
import javafx.scene.control.TableColumn;
import javafx.scene.control.TableView;
import javafx.scene.control.TextField;
import javafx.scene.control.cell.PropertyValueFactory;
import javafx.scene.control.cell.TextFieldTableCell;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.GridPane;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.util.Callback;

/**
 * FXML Controller class
 * @author Maher
 */
public class ReglementAjouter2Controller implements Initializable {

    Logger logger = Logger.getLogger(ReglementAjouter2Controller.class.getName());
    
    @FXML private AnchorPane AnchorPaneReglementAjouter2;
    @FXML private AnchorPane PaneComptant;
    @FXML private AnchorPane PaneFacilite;
    
    @FXML private AnchorPane PaneFaciliteCheque;
    @FXML private AnchorPane PaneFaciliteTraite;
    
    @FXML private Text TextNbrFacture;
    @FXML private Text TextTotalFacture;
    
    @FXML private GridPane GridPaneCheque;
    @FXML private GridPane GridPaneCarte;
    
    @FXML private TextField TextFieldNbrEcheance;
    @FXML private Text TextCtlNbrEcheance;
    @FXML private Text TotalEcheance;
    
    @FXML private TextField TextFieldChequeNomBanque;
    @FXML private TextField TextFieldChequeNumero;
    @FXML private TextField TextFieldChequeNomComple;
    @FXML private DatePicker DatePickerChequeDate;
    @FXML private Text TextCtlChequeNomBanque;
    @FXML private Text TextCtlChequeNumero;
    @FXML private Text TextCtlChequeNomComple;
    @FXML private Text TextCtlChequeDate;
    
    @FXML private TextField TextFieldCarteNomBanque;
    @FXML private TextField TextFieldCarteNumeroCart;
    @FXML private TextField TextFieldCarteNumeroTransaction;
    @FXML private TextField TextFieldCarteHeurTransaction;
    @FXML private DatePicker DatePickerCarteDate;
    @FXML private Text TextCtlCartNomBanque;
    @FXML private Text TextCtlCartNumeroCart;
    @FXML private Text TextCtlCartNumeroTransaction;
    @FXML private Text TextCtlCartDateHeurTransaction;
    
    @FXML public TableView<TraiteList> TableViewListeTraite ;
    @FXML public TableColumn TabColDateTraite;
    @FXML public TableColumn<TraiteList ,String> TabColMontantTraite;
    
    @FXML public TableView<ChequeList> TableViewListeCheque ;
    @FXML public TableColumn TabColDateCheque;
    @FXML public TableColumn<ChequeList ,String> TabColNumeroCheque;
    @FXML public TableColumn<ChequeList ,String> TabColBanqueCheque;
    @FXML public TableColumn<ChequeList ,String> TabColMontantCheque;
    
    float TotalFact = 0;
    boolean clt_total_echeance = true;
    private int SelectComptantFacilite ; // 0 Comptant | 1 Facilité
    private int PayerEesCheqCar  = 0;  //Payer en:  0 espèce |  1 Chéque  |  2 Carte électronique
    private int facilite_traite_cheque = 0; // 0 traite |  1 cheque
    
    ObservableList<FactureFrs> DataFacture = FXCollections.observableArrayList();
    
    public ObservableList<TraiteList> ListT = FXCollections.observableArrayList();
    public ObservableList<ChequeList> ListCheque = FXCollections.observableArrayList();
    
    Reglement reglement = new Reglement();
    
    contro clt = new contro();
    
    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        TableViewListeTraite.setEditable(true);
        TabColMontantTraite.setStyle( "-fx-alignment: CENTER;");
        TabColMontantTraite.getStyleClass().add("Center");
        TabColMontantTraite.setCellValueFactory(new PropertyValueFactory<TraiteList, String>("MontantTraite"));
        TabColMontantTraite.setCellFactory(TextFieldTableCell.<TraiteList>forTableColumn());  //Ajouter l'option textfield
        //Valier l'opertion
        TabColMontantTraite.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<TraiteList, String>>() {
            @Override
            public void handle(TableColumn.CellEditEvent<TraiteList, String> t) {
                String NewMontant = t.getNewValue().replace('.',',');
                ((TraiteList) t.getTableView().getItems().get(t.getTablePosition().getRow())).setMontantTraite(NewMontant);
                CalculeTotalTrait();
            }
        });
        
        TabColDateTraite.setStyle( "-fx-alignment: CENTER; -fx-font-weight:bold; -fx-font-size: 10pt;");
        TabColDateTraite.getStyleClass().add("Center");
        TabColDateTraite.setCellValueFactory(new PropertyValueFactory<TraiteList, Date>("date"));
        TabColDateTraite.setCellFactory(new Callback<TableColumn, TableCell>() {
            @Override
            public TableCell call(TableColumn p) {
                DatePickerCell datePick = new DatePickerCell(ListT);
                return datePick;
            }
        });
        TableViewListeTraite.setItems(ListT);
        
        
        
        //Cheque
        TabColNumeroCheque.setStyle( "-fx-alignment: CENTER;");
        TabColNumeroCheque.getStyleClass().add("Center");
        TabColNumeroCheque.setCellValueFactory(new PropertyValueFactory<ChequeList, String>("NumeroCheque"));
        TabColNumeroCheque.setCellFactory(TextFieldTableCell.<ChequeList>forTableColumn());  //Ajouter l'option textfield
        //Valier l'opertion
        TabColNumeroCheque.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<ChequeList, String>>() {
            @Override
            public void handle(TableColumn.CellEditEvent<ChequeList, String> t) {
                String NewNumeroCheque = t.getNewValue();
                contro clt = new contro();
                if(!clt.isNumeric(NewNumeroCheque)){
                    if(t.getTablePosition().getRow() == 0){
                        Integer NumeroCheque = Integer.valueOf(NewNumeroCheque);
                        int indise = 0; 
                        while(indise<ListCheque.size()){
                            ((ChequeList) t.getTableView().getItems().get(indise)).setNumeroCheque(NumeroCheque.toString());
                            indise++;NumeroCheque++;
                        }
                    }else{
                        ((ChequeList) t.getTableView().getItems().get(t.getTablePosition().getRow())).setNumeroCheque(NewNumeroCheque);
                    }
                }else{
                    ((ChequeList) t.getTableView().getItems().get(t.getTablePosition().getRow())).setNumeroCheque(null);
                }
            }
        });
        
        TabColBanqueCheque.setStyle( "-fx-alignment: CENTER;");
        TabColBanqueCheque.getStyleClass().add("Center");
        TabColBanqueCheque.setCellValueFactory(new PropertyValueFactory<ChequeList, String>("BanqueCheque"));
        TabColBanqueCheque.setCellFactory(TextFieldTableCell.<ChequeList>forTableColumn());  //Ajouter l'option textfield
        //Valier l'opertion
        TabColBanqueCheque.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<ChequeList, String>>() {
            @Override
            public void handle(TableColumn.CellEditEvent<ChequeList, String> t) {
                String NewBanque = t.getNewValue();
                if(t.getTablePosition().getRow() == 0){
                    int indise = 0; 
                    while(indise<ListCheque.size()){
                        ((ChequeList) t.getTableView().getItems().get(indise)).setBanqueCheque(NewBanque);
                        indise++;
                    }
                }else{
                    ((ChequeList) t.getTableView().getItems().get(t.getTablePosition().getRow())).setBanqueCheque(NewBanque);
                }
            }
        });
        
        TabColMontantCheque.setStyle( "-fx-alignment: CENTER;");
        TabColMontantCheque.getStyleClass().add("Center");
        TabColMontantCheque.setCellValueFactory(new PropertyValueFactory<ChequeList, String>("MontantCheque"));
        TabColMontantCheque.setCellFactory(TextFieldTableCell.<ChequeList>forTableColumn());  //Ajouter l'option textfield
        //Valier l'opertion
        TabColMontantCheque.setOnEditCommit(new EventHandler<TableColumn.CellEditEvent<ChequeList, String>>() {
            @Override
            public void handle(TableColumn.CellEditEvent<ChequeList, String> t) {
               String NewQuantite = t.getNewValue();
               ((ChequeList) t.getTableView().getItems().get(t.getTablePosition().getRow())).setMontantCheque(NewQuantite);
               CalculeTotalCheque();
            }
        });
        
        TabColDateCheque.setStyle( "-fx-alignment: CENTER; -fx-font-weight:bold; -fx-font-size: 10pt;");
        TabColDateCheque.getStyleClass().add("Center");
        TabColDateCheque.setCellValueFactory(new PropertyValueFactory<ChequeList, Date>("date"));
        TabColDateCheque.setEditable(true);
        TabColDateCheque.setCellFactory(new Callback<TableColumn, TableCell>() {
            @Override
            public TableCell call(TableColumn p) {
                DatePickerCellCheque datePick = new DatePickerCellCheque(ListCheque);
                return datePick;
            }
        });
        
        TableViewListeCheque.setItems(ListCheque);
        
    }
    
    @FXML
    private void DetailRelementSuitButtonAction(ActionEvent event) throws IOException {
        final Reglement reglement = new Reglement();
        boolean clt_reglement = true;
        
        if(SelectComptantFacilite == 0){
            reglement.setTypePaiement("0");
            
            //0 espèce |  1 Chéque  |  2 Carte électronique
            if(PayerEesCheqCar == 0){
                reglement.setModePaiement("0");
            }else if(PayerEesCheqCar == 1){
                reglement.setModePaiement("1");
                if(clt.ContrNull(TextFieldChequeNomBanque, TextCtlChequeNomBanque) &&
                    clt.ContrNumeriqueNotnull(TextFieldChequeNumero, TextCtlChequeNumero) && 
                    clt.ContrNull(TextFieldChequeNomComple, TextCtlChequeNomComple)&& 
                    clt.ContrNullDatePicker(DatePickerChequeDate, TextCtlChequeDate) ){
                    
                    ChequeFrs Cheque = new ChequeFrs();
                    Cheque.setBanqueChequeFrs(TextFieldChequeNomBanque.getText());
                    Cheque.setNumeroChequeFrs(TextFieldChequeNumero.getText());
                    Cheque.setNomCompletChequeFrs(TextFieldChequeNomComple.getText());
                    Cheque.setDatePaiement(DatePickerChequeDate.getValue().toString());
                    Cheque.setMontantChequeFrs(Adaptateur.ArrondFloatToString(TotalFact));
                    reglement.setCheque(Cheque);
                }else{ clt_reglement = false; }
            
            }else if(PayerEesCheqCar == 2){
                reglement.setModePaiement("2");
                if(clt.ContrNull(TextFieldCarteNomBanque, TextCtlCartNomBanque) &&
                    clt.ContrNumeriqueNotnull(TextFieldCarteNumeroCart, TextCtlCartNumeroCart) && 
                    clt.ContrNumeriqueNotnull(TextFieldCarteNumeroTransaction, TextCtlCartNumeroTransaction)&& 
                    clt.ContrNullDatePicker(DatePickerCarteDate, TextCtlCartDateHeurTransaction) &&
                    clt.ContrHour(TextFieldCarteHeurTransaction, TextCtlCartDateHeurTransaction) ){
                    CarteElectroniqueFrs CarteElectronique = new CarteElectroniqueFrs();
                    CarteElectronique.setBanque(TextFieldCarteNomBanque.getText());
                    CarteElectronique.setNumeroTransaction(TextFieldCarteNumeroTransaction.getText());
                    CarteElectronique.setCodeCarte(TextFieldCarteNumeroCart.getText());
                    CarteElectronique.setDateTransaction(DatePickerCarteDate.getValue().toString());
                    CarteElectronique.setHeurTransaction(TextFieldCarteHeurTransaction.getText());
                    CarteElectronique.setMantant(Adaptateur.ArrondFloatToString(TotalFact));
                    reglement.setCarte(CarteElectronique);
                }else{ clt_reglement = false; }
            }
        }else if(SelectComptantFacilite == 1){
            reglement.setTypePaiement("1");
            
            //1 Chéque  | 3 Traite
            if(facilite_traite_cheque == 0){
                if(clt_total_echeance){
                    reglement.setModePaiement("3");
                    ObservableList<TraiteFrs> TraitFrs =  FXCollections.observableArrayList();
                    for(TraiteList List : ListT ) {
                       String DatePaiement = new SimpleDateFormat("yyyy-MM-dd").format(List.getDate());
                       TraitFrs.add(new TraiteFrs("", DatePaiement, null, List.getMontantTraite().replace(",", "."), null));
                    }  
                    reglement.setListTraite(TraitFrs);
                }else{ clt_reglement = false; }
                
            }else if(facilite_traite_cheque == 1){
                if(clt_total_echeance){
                    reglement.setModePaiement("1");
                    ObservableList<ChequeFrs> CollCheque =  FXCollections.observableArrayList();
                    for(ChequeList List : ListCheque ) {
                        String CodeChequeFrs = "";
                        String NumeroChequeFrs = List.getNumeroCheque();
                        String BanqueChequeFrs = List.getBanqueCheque();
                        String MontantChequeFrs = List.getMontantCheque();
                        String DateCreation = LocalDateTime.now().toString();
                        String DatePaiement = new SimpleDateFormat("yyyy-MM-dd").format(List.getDate());
                        //controle numero chéque et nom banque
                        if(NumeroChequeFrs.equals("") || BanqueChequeFrs.equals("")){
                            clt_reglement = false;
                        }
                        CollCheque.add(new ChequeFrs(CodeChequeFrs, NumeroChequeFrs, BanqueChequeFrs, MontantChequeFrs, null, DatePaiement, DateCreation));
                    }
                    reglement.setListCheque(CollCheque); 
                }else{ clt_reglement = false; }
            }
        }
        
        if(clt_reglement){
            reglement.setMontant(Adaptateur.ArrondFloatToString(TotalFact));
            reglement.setListFacture(DataFacture);
            reglement.setDateTimeCreation(LocalDateTime.now().toString());
            reglement.setFournisseur(DataFacture.get(0).getFournisseur());
            reglement.setEtatReglement("0");
            
            final ReglementDialogConfirmationController  ReglementDialogConfirmation = new  ReglementDialogConfirmationController();
            ReglementDialogConfirmation.Enregister.setOnAction(new EventHandler<ActionEvent>(){
                @Override
                public void handle(ActionEvent t) {
                    try {
                        ReglementDialogConfirmation.AnchorPrincipal.setVisible(false);
                        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/Views/Reglement/ReglementAjouter3.fxml"));
                        Parent NodeReglementAjouter3 = (Parent)fxmlLoader.load();

                        ReglementAjouter3Controller ReglementAjouter3 = fxmlLoader.getController();
                        ReglementAjouter3.setDataReglement(reglement);

                        AnchorPaneReglementAjouter2.getChildren().clear();
                        AnchorPaneReglementAjouter2.getChildren().add(NodeReglementAjouter3);
                    } catch (IOException ex) {
                        logger.error("ReglementAjouter2Controller  : ReglementAjouter3.fxml :" + ex.getMessage());
                    }
                }
            });
            ReglementDialogConfirmation.setReglement(reglement);
            ReglementDialogConfirmation.Show();
        }
        
    }
    
    @FXML
    private void AjouterTraitementButtonAction(ActionEvent event) throws IOException {
        Date date= new Date();
        Calendar cal = Calendar.getInstance();
        if(clt.ContrNumeriqueNotnull(TextFieldNbrEcheance, TextCtlNbrEcheance)){
            ListT.clear();
            Integer IntegerNbrEcheance = Adaptateur.Diviseur(Adaptateur.StringToFloat(TextFieldNbrEcheance.getText()));
            float Value = (float) TotalFact / IntegerNbrEcheance;
            Integer div = Adaptateur.Diviseur(Value);
            float Somme = 0;
            if(facilite_traite_cheque == 0){
                PaneFaciliteCheque.setVisible(false);
                PaneFaciliteTraite.setVisible(true);
                for(int i=0; i<IntegerNbrEcheance; i++){
                    cal.setTime(date);
                    cal.add(Calendar.MONTH, i+1);
                    Somme += div;
                    if(i == IntegerNbrEcheance-1){
                        float reste = div + (TotalFact - Somme) ;
                        ListT.add(new TraiteList(Adaptateur.ArrondFloatToString(reste),  cal.getTime()));
                    }else{
                        ListT.add(new TraiteList(Adaptateur.floatDeleZero(div),  cal.getTime()));
                    }
                }
                TableViewListeTraite.setItems(ListT);
                CalculeTotalTrait();
            }else if(facilite_traite_cheque == 1){
                for(int i=0; i<IntegerNbrEcheance; i++){
                    cal.setTime(date);
                    cal.add(Calendar.MONTH, i+1);
                    Somme += div;
                    if(i == IntegerNbrEcheance-1){
                        float reste = div + (TotalFact - Somme) ;
                        ListCheque.add(new ChequeList(cal.getTime(),"","",Adaptateur.ArrondFloatToString(reste)));
                    }else{
                        ListCheque.add(new ChequeList(cal.getTime(),"","",Adaptateur.floatDeleZero(div)));
                     }
                }
                CalculeTotalCheque();
            }
        }
    }
    
    
    public void SetDataFactureFrs(ObservableList<FactureFrs> DataFact){
        DataFacture = DataFact;
        for( FactureFrs Facture : DataFact ) {
            TotalFact += Adaptateur.StringToFloat(Facture.getNetAPayer());
        }
        TextTotalFacture.setText(Adaptateur.FloatToStringEspaceCurrency(TotalFact));
        TotalEcheance.setText("0 / "+Adaptateur.ArrondFloatToString(TotalFact));
        
        TotalFact  = Adaptateur.ArrondFloatToFloat(TotalFact);
        
        TextNbrFacture.setText(DataFact.size()+"");
    }
    
    
    public void CalculeTotalTrait(){
        float Somme = 0;
        for(TraiteList List : ListT ) {
            Somme += Adaptateur.StringToFloat(List.getMontantTraite());
        }
        TotalEcheance.setText(Adaptateur.ArrondFloatToString(Somme)+" / "+Adaptateur.ArrondFloatToString(TotalFact));
        
        if(Adaptateur.ArrondFloatToString(Somme).equals(Adaptateur.ArrondFloatToString(TotalFact))){
            TotalEcheance.setFill(Color.web("#000000"));
            clt_total_echeance = true;
        }else{
            TotalEcheance.setFill(Color.web("#f20606"));
            clt_total_echeance = false;
        }
       
    }
    
    public void CalculeTotalCheque(){
        float Somme = 0;
        for(ChequeList List : ListCheque ) {
            Somme += Adaptateur.StringToFloat(List.getMontantCheque());
        }
        TotalEcheance.setText(Adaptateur.ArrondFloatToString(Somme)+" / "+Adaptateur.ArrondFloatToString(TotalFact));
        
        if(Adaptateur.ArrondFloatToString(Somme).equals(Adaptateur.ArrondFloatToString(TotalFact))){
            TotalEcheance.setFill(Color.web("#000000"));
            clt_total_echeance = true;
        }else{
            TotalEcheance.setFill(Color.web("#f20606"));
            clt_total_echeance = false;
        }
       
    }
    
    @FXML
    private void ReglementAjouter1ButtonAction(ActionEvent event) throws IOException {
        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/Views/Reglement/ReglementAjouter1.fxml"));
        Parent NodeReglementAjouter1 = (Parent)fxmlLoader.load();
        
        ReglementAjouter1Controller ReglementAjouter1 = fxmlLoader.getController();
        ReglementAjouter1.setDataFactureFrs(DataFacture);
                
        AnchorPaneReglementAjouter2.getChildren().clear();
        AnchorPaneReglementAjouter2.getChildren().add(NodeReglementAjouter1);
    }
    
    @FXML
    public void RadioComptantAction(ActionEvent event) throws IOException {
        SelectComptantFacilite = 0;
        PaneComptant.setVisible(true);
        PaneFacilite.setVisible(false);
    }
    
    
    @FXML
    public void RadioEspeceAction(ActionEvent event) throws IOException {
        PayerEesCheqCar = 0;
        GridPaneCheque.setVisible(false);
        GridPaneCarte.setVisible(false);
    }
    
    @FXML
    public void RadioChequeAction(ActionEvent event) throws IOException {
        PayerEesCheqCar = 1;
        GridPaneCheque.setVisible(true);
        GridPaneCarte.setVisible(false);
    }
    
    @FXML
    public void RadioCarteAction(ActionEvent event) throws IOException {
        PayerEesCheqCar = 2;
        GridPaneCheque.setVisible(false);
        GridPaneCarte.setVisible(true);
    }
    
    @FXML
    public void RadioFaciliteAction(ActionEvent event) throws IOException {
        SelectComptantFacilite = 1;
        PaneComptant.setVisible(false);
        PaneFacilite.setVisible(true);
    }
    
    @FXML
    public void RadioFaciliteTraiteAction(ActionEvent event) throws IOException {
        facilite_traite_cheque = 0;
        PaneFaciliteCheque.setVisible(false);
        PaneFaciliteTraite.setVisible(true);
    }
    
    @FXML
    public void RadioFaciliteChequeAction(ActionEvent event) throws IOException {
        facilite_traite_cheque = 1;
        PaneFaciliteCheque.setVisible(true);
        PaneFaciliteTraite.setVisible(false);
    }
    
}
