/*
 * 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 interfacePharmacie;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

/**
 *
 * @author awn27
 */
public class Commande extends javax.swing.JFrame {

    /**
     * Creates new form Commande
     */
    HashMap <Integer, Integer> map = new HashMap<>();
    public Commande() {
        initComponents();
        ActualisationSolde.refreshSolde();
        chargerFournisseur();
        this.setLocationRelativeTo(this);
        this.setResizable(false);
        lblSoldeActuel.setText(String.valueOf(InterfaceLogin.soldePharmacie).toString());
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        cbxFournisseur = new javax.swing.JComboBox<>();
        btnSearchFournisseur = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtbFournisseur = new javax.swing.JTable();
        jScrollPane2 = new javax.swing.JScrollPane();
        jtbFournisseurProduitSelect = new javax.swing.JTable();
        txtQuantite = new javax.swing.JTextField();
        btnAdd = new javax.swing.JButton();
        btnRemove = new javax.swing.JButton();
        lblTotal = new javax.swing.JLabel();
        btnSaveCmd = new javax.swing.JButton();
        radioValide = new javax.swing.JRadioButton();
        radioAttente = new javax.swing.JRadioButton();
        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        lblSoldeActuel = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        getContentPane().setLayout(new org.netbeans.lib.awtextra.AbsoluteLayout());

        cbxFournisseur.setFont(new java.awt.Font("Arial Black", 1, 16)); // NOI18N
        cbxFournisseur.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cbxFournisseur.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbxFournisseurActionPerformed(evt);
            }
        });
        getContentPane().add(cbxFournisseur, new org.netbeans.lib.awtextra.AbsoluteConstraints(90, 60, 210, 30));

        btnSearchFournisseur.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/refresh.png"))); // NOI18N
        btnSearchFournisseur.setContentAreaFilled(false);
        btnSearchFournisseur.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSearchFournisseurActionPerformed(evt);
            }
        });
        getContentPane().add(btnSearchFournisseur, new org.netbeans.lib.awtextra.AbsoluteConstraints(310, 50, 80, 50));

        jtbFournisseur.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jtbFournisseur.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane1.setViewportView(jtbFournisseur);

        getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 130, 400, 350));

        jtbFournisseurProduitSelect.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jtbFournisseurProduitSelect.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null},
                {null, null, null, null}
            },
            new String [] {
                "Title 1", "Title 2", "Title 3", "Title 4"
            }
        ));
        jScrollPane2.setViewportView(jtbFournisseurProduitSelect);

        getContentPane().add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(582, 130, 440, 360));
        getContentPane().add(txtQuantite, new org.netbeans.lib.awtextra.AbsoluteConstraints(460, 230, 80, -1));

        btnAdd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/panier.png"))); // NOI18N
        btnAdd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAddActionPerformed(evt);
            }
        });
        getContentPane().add(btnAdd, new org.netbeans.lib.awtextra.AbsoluteConstraints(460, 270, -1, -1));

        btnRemove.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/remove.png"))); // NOI18N
        btnRemove.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnRemoveActionPerformed(evt);
            }
        });
        getContentPane().add(btnRemove, new org.netbeans.lib.awtextra.AbsoluteConstraints(460, 340, 80, 60));

        lblTotal.setFont(new java.awt.Font("Arial", 1, 24)); // NOI18N
        lblTotal.setForeground(new java.awt.Color(255, 0, 0));
        lblTotal.setText("0000000");
        getContentPane().add(lblTotal, new org.netbeans.lib.awtextra.AbsoluteConstraints(820, 560, 100, 40));

        btnSaveCmd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/btnPassCommande.png"))); // NOI18N
        btnSaveCmd.setContentAreaFilled(false);
        btnSaveCmd.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSaveCmdActionPerformed(evt);
            }
        });
        getContentPane().add(btnSaveCmd, new org.netbeans.lib.awtextra.AbsoluteConstraints(740, 610, 190, 70));

        radioValide.setFont(new java.awt.Font("Arial Black", 0, 16)); // NOI18N
        radioValide.setText("Validé");
        radioValide.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                radioValideActionPerformed(evt);
            }
        });
        getContentPane().add(radioValide, new org.netbeans.lib.awtextra.AbsoluteConstraints(910, 520, -1, -1));

        radioAttente.setFont(new java.awt.Font("Arial Black", 0, 16)); // NOI18N
        radioAttente.setText("Attente Paiement");
        radioAttente.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                radioAttenteActionPerformed(evt);
            }
        });
        getContentPane().add(radioAttente, new org.netbeans.lib.awtextra.AbsoluteConstraints(700, 520, -1, -1));

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/ACCUEIL.png"))); // NOI18N
        jLabel1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jLabel1MouseClicked(evt);
            }
        });
        getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(960, 30, 50, 60));

        jLabel3.setFont(new java.awt.Font("Arial", 1, 18)); // NOI18N
        jLabel3.setText("CFA");
        getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(940, 560, 60, 40));

        jLabel4.setFont(new java.awt.Font("Arial Black", 1, 18)); // NOI18N
        jLabel4.setText("TOTAL");
        getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(700, 560, 80, 30));

        jLabel5.setFont(new java.awt.Font("Arial Black", 1, 18)); // NOI18N
        jLabel5.setForeground(new java.awt.Color(0, 153, 51));
        jLabel5.setText("Quantité");
        getContentPane().add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(460, 180, 110, 30));

        lblSoldeActuel.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        lblSoldeActuel.setForeground(new java.awt.Color(0, 153, 102));
        lblSoldeActuel.setText("jLabel3");
        getContentPane().add(lblSoldeActuel, new org.netbeans.lib.awtextra.AbsoluteConstraints(560, 10, 80, 30));

        jLabel6.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel6.setText("Votre solde actuel est de ");
        getContentPane().add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(370, 10, 190, 30));

        jLabel7.setFont(new java.awt.Font("Tahoma", 1, 12)); // NOI18N
        jLabel7.setForeground(new java.awt.Color(0, 153, 102));
        jLabel7.setText("CFA");
        getContentPane().add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(650, 20, -1, -1));

        pack();
    }// </editor-fold>//GEN-END:initComponents

    
    BDPharmacie bd = new BDPharmacie();
        Connection connex;
        String tabeColumnProduitFournisseur[] = {"ID","Médicament","PU","Stock", "Fabriquant"};
        String tabeColumnProduitSelect[] = {"ID","Médicament", "Fabriquant", "Quantite","Montant"};
        DefaultTableModel dftmProduitFournisseur, dftmProduitSelect;
        
    public void chargerFournisseur (){
              bd = new BDPharmacie();
              connex=bd.connectToBD();

        try {
            String sql ="SELECT * FROM fournisseur";
            PreparedStatement stm=connex.prepareStatement(sql);
            ResultSet rs = stm.executeQuery();
            cbxFournisseur.removeAllItems();
            
            while (rs.next()){
                String id = rs.getString("id_fournisseur");
                String nom = rs.getString("nom_fournisseur");
                  
                  String client = id+" "+nom;
                  cbxFournisseur.addItem(client);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public void chargerProduitFournisseur () {
        try {
                connex = bd.connectToBD();
                String sql ="SELECT id_medicament_f, nom_medicament_f, stock_f, pu_f, fabriquant_medicament_f FROM medicament_f ORDER BY nom_medicament_f ASC";
                PreparedStatement stm = connex.prepareStatement(sql);
                ResultSet rs = stm.executeQuery();
                dftmProduitFournisseur = new DefaultTableModel();
                dftmProduitSelect = new DefaultTableModel();
                
                dftmProduitFournisseur.setColumnIdentifiers(tabeColumnProduitFournisseur);
               dftmProduitSelect.setColumnIdentifiers(tabeColumnProduitSelect);
                
                while (rs.next())
                {
                    String id = rs.getString("id_medicament_f");
                    
                    String medicament = rs.getString("nom_medicament_f");
                    String pu = rs.getString("pu_f");
                    String stock = rs.getString("stock_f");
                    String fabriquant = rs.getString("fabriquant_medicament_f");
                    
                    Vector v = new Vector();
                    v.add(id);
                    v.add(medicament);
                    v.add(pu);
                    v.add(stock);
                    v.add(fabriquant);
                    
                    dftmProduitFournisseur.addRow(v);
                   
                }
                jtbFournisseur.setModel(dftmProduitFournisseur);
            } catch (Exception e) {
                e.printStackTrace();
            }
        
    }
    double total;
    public void calculTotal () {
        
       total = 0; //initialisation de la valeur à zero ce qu'on avait déclaré au début
       for (int i = 0; i<jtbFournisseurProduitSelect.getRowCount(); i++){
     
     
     String montant = jtbFournisseurProduitSelect.getValueAt(i, 4).toString();// le 4 est le numéro de la colonne
     total = total + Double.parseDouble(montant);
     
 }
         lblTotal.setText(total+ " "); //conversion de total en text
  
        
    }
    private void cbxFournisseurActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbxFournisseurActionPerformed
       
    }//GEN-LAST:event_cbxFournisseurActionPerformed

    private void btnSearchFournisseurActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearchFournisseurActionPerformed
        chargerFournisseur();
        chargerProduitFournisseur();
    }//GEN-LAST:event_btnSearchFournisseurActionPerformed

    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
      
        int ligne = jtbFournisseur.getSelectedRow();
        String id = jtbFournisseur.getValueAt(ligne, 0).toString();
        String medicament = jtbFournisseur.getValueAt(ligne, 1).toString();
        String prix = jtbFournisseur.getValueAt(ligne, 2).toString();
        String stock = jtbFournisseur.getValueAt(ligne, 3).toString();
        String fabriquant = jtbFournisseur.getValueAt(ligne, 4).toString();//
                       
        double pu = Double.parseDouble(prix);
        int stockActuel = Integer.parseInt(stock);
        
        String quantite = txtQuantite.getText();
         if(quantite.isEmpty() ){
            JOptionPane.showMessageDialog(this, "Veuillez remplir la quantité du produit");
            return;}   
         
        int qte = Integer.parseInt(quantite);
        
        if (qte > stockActuel) {
            JOptionPane.showMessageDialog(this, "Veuillez choisir un stock inférieur à " + qte+ " ");
            return;
          }
        int idProduit = Integer.parseInt(id);
        int stockFinal = stockActuel - qte;
        map.put(idProduit, stockFinal);
        
        double montant = pu*qte;
              
        
        Vector v = new Vector();
        v.add(id);
        v.add(medicament);
        v.add(fabriquant);
        v.add(quantite);
        v.add(montant);
        
        //mettre le vecteur sur l'autre table
        dftmProduitSelect.addRow(v);
        jtbFournisseurProduitSelect.setModel(dftmProduitSelect);

        txtQuantite.setText("");
        
            calculTotal();
    }//GEN-LAST:event_btnAddActionPerformed

    private void btnRemoveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveActionPerformed
        
          int ligne = jtbFournisseurProduitSelect.getSelectedRow();
        String id = jtbFournisseurProduitSelect.getValueAt(ligne, 0).toString();
        int idProduit= Integer.parseInt(id);
        
       map.remove(idProduit);
        
        dftmProduitSelect.removeRow(ligne);
        calculTotal();
    }//GEN-LAST:event_btnRemoveActionPerformed
   
    public void updateStockFournisseur (int id, int stockFinal) {
         try {
            
            String sql ="UPDATE medicament_f SET stock_f = ? WHERE id_medicament_f = ?";
            PreparedStatement stm = connex.prepareStatement(sql);
            stm.setInt(1, stockFinal);
            stm.setInt(2, id);
            stm.executeUpdate();
            
        } catch (Exception e) {
        e.printStackTrace();
        }
        
    }
    
    String etat;
    private void btnSaveCmdActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSaveCmdActionPerformed
        
         LocalDate date = LocalDate.now();
        String fournisseur = cbxFournisseur.getSelectedItem().toString();
        String id = fournisseur.substring(0, fournisseur.indexOf(" "));
        int idFourn = Integer.parseInt(id);
        
        double total = Double.parseDouble(lblTotal.getText());
             
        
        try {
            
            String sql = "INSERT INTO commande (date, id_fournisseur, montant, etat, id_pharmacie) VALUES (?,?,?,?,?)";
            PreparedStatement stm = connex.prepareStatement(sql);
            stm.setString(1,date+"");
            stm.setInt(2, idFourn);
            stm.setDouble(3, total);
            stm.setString(4, etat);
            stm.setInt(5, InterfaceLogin.idPharmacie);
            stm.executeUpdate();
          
            for (int i = 0; i<jtbFournisseurProduitSelect.getRowCount(); i++){
            String idP = jtbFournisseurProduitSelect.getValueAt(i, 0).toString();
            int idProduit = Integer.parseInt(idP);
            int stockFinal = map.get(idProduit);
              updateStockFournisseur(idProduit, stockFinal);
              
        }
          
          chargerProduitFournisseur();
          saveCommande();
          
          
          dftmProduitSelect = new DefaultTableModel();
          dftmProduitSelect.setColumnIdentifiers(tabeColumnProduitSelect);
          jtbFournisseurProduitSelect.setModel(dftmProduitSelect);
            
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "Commande non enregistré, veuillez contacter l'administrateur");
        }
    }//GEN-LAST:event_btnSaveCmdActionPerformed

    private void radioValideActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radioValideActionPerformed
       etat ="Valide";
        radioValide.setSelected(true);
        radioAttente.setSelected(false);
    }//GEN-LAST:event_radioValideActionPerformed

    private void radioAttenteActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_radioAttenteActionPerformed
        etat ="Attente";
        radioValide.setSelected(false);
        radioAttente.setSelected(true);
    }//GEN-LAST:event_radioAttenteActionPerformed

    private void jLabel1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel1MouseClicked
         
            dispose();
    }//GEN-LAST:event_jLabel1MouseClicked

    public void saveCommande() {
        
        try {
                String sql = "SELECT MAX(id_cmd) AS id FROM commande WHERE id_pharmacie = '"+InterfaceLogin.idPharmacie+"'";
                PreparedStatement stm = connex.prepareStatement(sql);
                ResultSet rs = stm.executeQuery();
                rs.next();//placement curseur au début
                int id_cmd = rs.getInt("id");
                               
                    for (int i = 0; i < jtbFournisseurProduitSelect.getRowCount(); i++){
                        
                        String idProduit = jtbFournisseurProduitSelect.getValueAt(i, 0).toString();
                        String quantite = jtbFournisseurProduitSelect.getValueAt(i, 3).toString();
                        
                        int idP = Integer.parseInt(idProduit);
                        int qte = Integer.parseInt(quantite);
                            String soldePharm = String.valueOf(InterfaceLogin.soldePharmacie);
                            double solde = Double.parseDouble(soldePharm);
          
          if (etat=="Valide" && solde > total){
              /*Mise à jour du solde de la table pharmacie*/
           double reste = solde-total;
            String sql0 ="UPDATE pharmacie set montant_pharmacie=? \n"
                       + "WHERE id_pharmacie =?";
            PreparedStatement stm0 = connex.prepareStatement(sql0);
            stm0.setDouble(1,reste);
            stm0.setInt(2, InterfaceLogin.idPharmacie);
            stm0.executeUpdate();
            
             JOptionPane.showMessageDialog(this, "Commande enregistré avec succès");
         
     }     else {
         JOptionPane.showMessageDialog(this, "Credit Insuffisant. Veuillez recharger votre compte");
         return;
     }
                        sql = "INSERT INTO detail_commande (id_medicament_f, quantite, id_cmd) VALUES (?,?,?)";
                        stm = connex.prepareStatement(sql);
                        stm.setInt(1, idP);
                        stm.setInt(2, qte);
                        stm.setInt(3, id_cmd);
                        stm.executeUpdate();
                        
        /*Ajout des médicaments dans la nouvelle table*/
         String sqla = "INSERT INTO medicament (nom_medicament, code, type_medicament, description_medicament, personne, contenance_medicament,"
                    + "posologie_medicament, fabriquant_medicament, date_expiration, pu, stock, image, id_pharmacie) "
                    + "SELECT DISTINCT m.nom_medicament_f, m.code_f, m.type_medicament_f, m.description_medicament_f, m.personne_f, m.contenance_medicament_f,"
                    + "m.posologie_medicament_f, m.fabriquant_medicament_f, m.date_expiration_f, m.pu_f, d.quantite, m.image_f, ? "
                    + "FROM medicament_f m, detail_commande d \n"
                    + "WHERE d.id_cmd=?";
            PreparedStatement stma = connex.prepareStatement(sqla);
            stma.setInt(1, InterfaceLogin.idPharmacie);
            stma.setInt(2, id_cmd);
            
            stma.executeUpdate();
            
            ActualisationSolde.refreshSolde();
            JOptionPane.showMessageDialog(this, "Médicament ajouter dans la base avec succès");
            

                    }
            
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Commande.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Commande.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Commande.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Commande.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Commande().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAdd;
    private javax.swing.JButton btnRemove;
    private javax.swing.JButton btnSaveCmd;
    private javax.swing.JButton btnSearchFournisseur;
    private javax.swing.JComboBox<String> cbxFournisseur;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jtbFournisseur;
    private javax.swing.JTable jtbFournisseurProduitSelect;
    private javax.swing.JLabel lblSoldeActuel;
    private javax.swing.JLabel lblTotal;
    private javax.swing.JRadioButton radioAttente;
    private javax.swing.JRadioButton radioValide;
    private javax.swing.JTextField txtQuantite;
    // End of variables declaration//GEN-END:variables
}
