/*
 * 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 final class Vente extends javax.swing.JFrame {

    /**
     * Creates new form Vente
     */
    HashMap <Integer, Integer> map = new HashMap<>();
    public Vente() {
        initComponents();
        this.setLocationRelativeTo(this);
        this.setResizable(false);
        chargerClient();
        chargerProduit();
    }

    /**
     * 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() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jtbCProduit = new javax.swing.JTable();
        jScrollPane2 = new javax.swing.JScrollPane();
        jtbCProduitSelect = new javax.swing.JTable();
        btnAdd = new javax.swing.JButton();
        btnRemove = new javax.swing.JButton();
        txtQuantite = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        lblTotal = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();
        cbClient = new javax.swing.JComboBox<>();
        btnSaveCmd = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        txtSommeAvance = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        lblReste = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jButton3 = new javax.swing.JButton();
        jRadioButton2 = new javax.swing.JRadioButton();
        jRadioButton1 = new javax.swing.JRadioButton();
        jLabel10 = new javax.swing.JLabel();
        txtSerchMedicament = new javax.swing.JTextField();
        jButton4 = new javax.swing.JButton();
        jLabel11 = new javax.swing.JLabel();
        btnSearchMedicament = new javax.swing.JButton();
        jLabel12 = new javax.swing.JLabel();

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

        jtbCProduit.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 [] {
                "ID", "Médicament", "Prix Unitaire", "Stock"
            }
        ));
        jScrollPane1.setViewportView(jtbCProduit);

        getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(37, 111, 460, 390));

        jtbCProduitSelect.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 [] {
                "ID", "Médicament", "Quantité", "Montant"
            }
        ));
        jScrollPane2.setViewportView(jtbCProduitSelect);

        getContentPane().add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(649, 111, -1, 280));

        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(520, 210, 70, 40));

        btnRemove.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/remove.png"))); // NOI18N
        btnRemove.setContentAreaFilled(false);
        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(510, 260, 100, 60));
        getContentPane().add(txtQuantite, new org.netbeans.lib.awtextra.AbsoluteConstraints(507, 151, 98, 34));

        jLabel1.setFont(new java.awt.Font("Segoe UI", 1, 18)); // NOI18N
        jLabel1.setText("Quantité");
        getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(507, 108, 98, -1));

        lblTotal.setFont(new java.awt.Font("Segoe UI Black", 1, 18)); // NOI18N
        lblTotal.setText("00000000");
        getContentPane().add(lblTotal, new org.netbeans.lib.awtextra.AbsoluteConstraints(890, 430, 118, 41));

        jLabel3.setFont(new java.awt.Font("Segoe Print", 1, 24)); // NOI18N
        jLabel3.setText("CFA");
        getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(1020, 430, 59, 34));

        jLabel6.setFont(new java.awt.Font("Segoe Print", 1, 24)); // NOI18N
        jLabel6.setText("TOTAL");
        getContentPane().add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(790, 430, 124, 41));

        jButton1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/refresh.png"))); // NOI18N
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(430, 0, 60, 40));

        cbClient.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        cbClient.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cbClient.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbClientActionPerformed(evt);
            }
        });
        getContentPane().add(cbClient, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 10, 290, 30));

        btnSaveCmd.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/btnPassCommande.png"))); // NOI18N
        btnSaveCmd.setText("jButton2");
        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(930, 610, 120, 50));

        jButton2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/ACCUEIL.png"))); // NOI18N
        jButton2.setContentAreaFilled(false);
        jButton2.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton2MouseClicked(evt);
            }
        });
        getContentPane().add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(1020, 30, 60, 50));
        getContentPane().add(txtSommeAvance, new org.netbeans.lib.awtextra.AbsoluteConstraints(900, 480, 97, -1));

        jLabel4.setFont(new java.awt.Font("Myanmar Text", 3, 18)); // NOI18N
        jLabel4.setForeground(new java.awt.Color(255, 0, 0));
        jLabel4.setText("Reste");
        getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(800, 520, 109, -1));

        jLabel7.setFont(new java.awt.Font("Segoe Print", 1, 18)); // NOI18N
        jLabel7.setText("CFA");
        getContentPane().add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(1030, 470, 59, 34));

        jLabel8.setFont(new java.awt.Font("Myanmar Text", 3, 18)); // NOI18N
        jLabel8.setText("Avance");
        getContentPane().add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(790, 470, 109, 30));

        lblReste.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
        lblReste.setForeground(new java.awt.Color(255, 0, 0));
        lblReste.setText("0000000");
        getContentPane().add(lblReste, new org.netbeans.lib.awtextra.AbsoluteConstraints(900, 520, 107, -1));

        jLabel9.setFont(new java.awt.Font("Segoe Print", 1, 14)); // NOI18N
        jLabel9.setText("CFA");
        getContentPane().add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(1030, 510, 59, 34));

        jButton3.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        jButton3.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/arg.png"))); // NOI18N
        jButton3.setText("Avance");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton3, new org.netbeans.lib.awtextra.AbsoluteConstraints(930, 550, 140, 50));

        jRadioButton2.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
        jRadioButton2.setText("Payé une partie");
        jRadioButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButton2ActionPerformed(evt);
            }
        });
        getContentPane().add(jRadioButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(930, 400, -1, -1));

        jRadioButton1.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
        jRadioButton1.setText("Payé la totalité");
        jRadioButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jRadioButton1ActionPerformed(evt);
            }
        });
        getContentPane().add(jRadioButton1, new org.netbeans.lib.awtextra.AbsoluteConstraints(760, 400, -1, -1));

        jLabel10.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel10.setText("Médicament");
        getContentPane().add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 60, 80, 20));

        txtSerchMedicament.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtSerchMedicamentActionPerformed(evt);
            }
        });
        getContentPane().add(txtSerchMedicament, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 50, 290, 30));

        jButton4.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/addUser.png"))); // NOI18N
        jButton4.setContentAreaFilled(false);
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton4, new org.netbeans.lib.awtextra.AbsoluteConstraints(930, 30, 60, 50));

        jLabel11.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel11.setText("Client");
        getContentPane().add(jLabel11, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 10, 50, 20));

        btnSearchMedicament.setText("Rechercher");
        btnSearchMedicament.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSearchMedicamentActionPerformed(evt);
            }
        });
        getContentPane().add(btnSearchMedicament, new org.netbeans.lib.awtextra.AbsoluteConstraints(420, 50, -1, 30));

        jLabel12.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel12.setText("Client");
        getContentPane().add(jLabel12, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 10, 50, 20));

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

   
        
        BDPharmacie bd = new BDPharmacie();
        Connection connex;
        String tabeColumnProduit[] = {"ID","Médicament","PU","Stock"};
        String tabeColumnProduitSelect[] = {"ID","Médicament","Quantite","Montant"};
        DefaultTableModel dftmProduit, dftmProduitSelect;
        int quantite;
        double total;
        double reste;
        int numeroAchat;
        
         public void chargerClient (){
              bd=new BDPharmacie();
              connex=bd.connectToBD();

        try {
            String sql ="SELECT * FROM client WHERE id_pharmacie = '"+InterfaceLogin.idPharmacie+"' ORDER BY nom ASC";
            PreparedStatement stm=connex.prepareStatement(sql);
            ResultSet rs = stm.executeQuery();
            cbClient.removeAllItems();
            
            while (rs.next()){
                  String id = rs.getString("id_client");
                  String prenom = rs.getString("prenom");
                  String telephone = rs.getString("telephone");
                  String nom = rs.getString("nom");
                  
                  String client = id+" "+prenom+" "+nom+" "+telephone;
                  cbClient.addItem(client);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
        public void chargerProduit(){
            try {
                connex = bd.connectToBD();
                String sql ="SELECT id_medicament, nom_medicament, stock, pu FROM medicament"
                        + " WHERE id_pharmacie = '"+InterfaceLogin.idPharmacie+"' AND stock >0"
                        + " ORDER BY nom_medicament ASC";
                PreparedStatement stm = connex.prepareStatement(sql);
                ResultSet rs = stm.executeQuery();
                dftmProduit = new DefaultTableModel();
                dftmProduitSelect = new DefaultTableModel();
                
                dftmProduit.setColumnIdentifiers(tabeColumnProduit);
                dftmProduitSelect.setColumnIdentifiers(tabeColumnProduitSelect);
                
                while (rs.next())
                {
                    String id = rs.getString("id_medicament");
                    String medicament = rs.getString("nom_medicament");
                    String pu = rs.getString("pu");
                    String stock = rs.getString("stock");
                    
                    Vector v = new Vector();
                    v.add(id);
                    v.add(medicament);
                    v.add(pu);
                    v.add(stock);
                    
                    dftmProduit.addRow(v);
                   
                }
                jtbCProduit.setModel(dftmProduit);
            } catch (Exception e) {
                e.printStackTrace();
            }
            
        }
    
    
    
    private void btnAddActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAddActionPerformed
        int ligne = jtbCProduit.getSelectedRow();
        String id = jtbCProduit.getValueAt(ligne, 0).toString();
        String medicament = jtbCProduit.getValueAt(ligne, 1).toString();
        String prix = jtbCProduit.getValueAt(ligne, 2).toString();
        String stock = jtbCProduit.getValueAt(ligne, 3).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(quantite);
        v.add(montant);
        //mettre le vecteur sur l'autre table
        dftmProduitSelect.addRow(v);
        jtbCProduitSelect.setModel(dftmProduitSelect);

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

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
            chargerProduit(); 
            chargerClient();
    }//GEN-LAST:event_jButton1ActionPerformed

    private void btnRemoveActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnRemoveActionPerformed
        int ligne = jtbCProduitSelect.getSelectedRow();
        String id = jtbCProduitSelect.getValueAt(ligne, 0).toString();
        int idProduit= Integer.parseInt(id);
        
       map.remove(idProduit);
        
        dftmProduitSelect.removeRow(ligne);
        calculTotal();
        calculReste();
    }//GEN-LAST:event_btnRemoveActionPerformed
   
    public void saveProduitsAchat ()
    {
        try {
                String sql = "SELECT MAX(id_achat) AS id FROM achat WHERE id_pharmacie = '"+InterfaceLogin.idPharmacie+"'";
                PreparedStatement stm = connex.prepareStatement(sql);
                ResultSet rs = stm.executeQuery();
                rs.next();//placement curseur au début
                int id_achat = rs.getInt("id");
                
                numeroAchat = id_achat;
                    for (int i = 0; i < jtbCProduitSelect.getRowCount(); i++){
                        
                        String idProduit = jtbCProduitSelect.getValueAt(i, 0).toString();
                        String quantite = jtbCProduitSelect.getValueAt(i, 2).toString();
                        
                        int idP = Integer.parseInt(idProduit);
                        int qte = Integer.parseInt(quantite);
                        
                        sql = "INSERT INTO detail_achat (id_medicament, quantite, id_achat) VALUES (?,?,?)";
                        stm = connex.prepareStatement(sql);
                        stm.setInt(1, idP);
                        stm.setInt(2, qte);
                        stm.setInt(3, id_achat);
                        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 client = cbClient.getSelectedItem().toString();
        String id = client.substring(0, client.indexOf(" "));
        int idClient = Integer.parseInt(id);
        
        double total = Double.parseDouble(lblTotal.getText());
        double reste1 = Double.parseDouble(lblReste.getText());
        
        
        
        try {
            
            String sql = "INSERT INTO achat (date, id_client, montant, etat, somme_du, id_pharmacie) VALUES (?,?,?,?,?,?)";
            PreparedStatement stm = connex.prepareStatement(sql);
            stm.setString(1,date+"");
            stm.setInt(2, idClient);
            stm.setDouble(3, total);
            stm.setString(4, etat);
            stm.setDouble(5, reste1);
            stm.setInt(6, InterfaceLogin.idPharmacie);
            stm.executeUpdate();
          
          for (int i = 0; i<jtbCProduitSelect.getRowCount(); i++){
            String idP = jtbCProduitSelect.getValueAt(i, 0).toString();
            int idProduit = Integer.parseInt(idP);
            int stockFinal = map.get(idProduit);
              updateStockProduit(idProduit, stockFinal);
              
        }
          
          chargerProduit();
          saveProduitsAchat();
         
          JOptionPane.showMessageDialog(this, "Achat enregistré avec succès sous le numéro" +numeroAchat+" ");
          dftmProduitSelect = new DefaultTableModel();
          dftmProduitSelect.setColumnIdentifiers(tabeColumnProduitSelect);
          jtbCProduitSelect.setModel(dftmProduitSelect);
            
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(this, "Achat non enregistré, veuillez contacter l'administrateur");
        }
    }//GEN-LAST:event_btnSaveCmdActionPerformed

    private void jButton2MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton2MouseClicked

          
            dispose();
        // TODO add your handling code here:
    }//GEN-LAST:event_jButton2MouseClicked

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
                    calculReste();        
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jRadioButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton1ActionPerformed
        etat ="paye";
        jRadioButton1.setSelected(true);
        jRadioButton2.setSelected(false);
    }//GEN-LAST:event_jRadioButton1ActionPerformed

    private void jRadioButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jRadioButton2ActionPerformed
        etat ="somme_du";
        jRadioButton1.setSelected(false);
        jRadioButton2.setSelected(true);
    }//GEN-LAST:event_jRadioButton2ActionPerformed

    private void cbClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbClientActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_cbClientActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        new Client().setVisible(true);
        dispose();
    }//GEN-LAST:event_jButton4ActionPerformed

    public void rechercherMedicamentVente () {
            
            String nomSearch="%"+txtSerchMedicament.getText()+"%";
       
        try {
                connex = bd.connectToBD();
                String sql ="SELECT id_medicament, nom_medicament, stock, pu FROM medicament WHERE nom_medicament LIKE ? "
                           + " AND id_pharmacie = '"+InterfaceLogin.idPharmacie+"' AND stock >0"
                           + " ORDER BY nom_medicament ASC";
                PreparedStatement stm = connex.prepareStatement(sql);
                stm.setString(1, nomSearch);
                ResultSet rs = stm.executeQuery();
                dftmProduit = new DefaultTableModel();
                //dftmProduitSelect = new DefaultTableModel();
                
                dftmProduit.setColumnIdentifiers(tabeColumnProduit);
               // dftmProduitSelect.setColumnIdentifiers(tabeColumnProduitSelect);
             
             while(rs.next())
            {
                    String id = rs.getString("id_medicament");
                    String medicament = rs.getString("nom_medicament");
                    String pu = rs.getString("pu");
                    String stock = rs.getString("stock");
                    
                    Vector v = new Vector();
                    v.add(id);
                    v.add(medicament);
                    v.add(pu);
                    v.add(stock);
                    
                    dftmProduit.addRow(v);
                   
                }
             
             jtbCProduit.setModel(dftmProduit); 
        
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private void txtSerchMedicamentActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtSerchMedicamentActionPerformed
            // TODO add your handling code here:
            rechercherMedicamentVente();
            
    }//GEN-LAST:event_txtSerchMedicamentActionPerformed

    private void btnSearchMedicamentActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSearchMedicamentActionPerformed
        // TODO add your handling code here:
        rechercherMedicamentVente();
    }//GEN-LAST:event_btnSearchMedicamentActionPerformed

    public void updateStockProduit (int id, int stockFinal) {
        try {
            
            String sql ="UPDATE medicament SET stock = ? WHERE id_medicament = ?";
            PreparedStatement stm = connex.prepareStatement(sql);
            stm.setInt(1, stockFinal);
            stm.setInt(2, id);
            stm.executeUpdate();
            
        } catch (Exception e) {
        e.printStackTrace();
        }
       // saveProduitsAchat();
    }
       public void calculTotal(){
        //fonction pour calcul produit total
        total = 0; //initialisation de la valeur à zero ce qu'on avait déclaré au début
       for (int i = 0; i<jtbCProduitSelect.getRowCount(); i++){
     
     
     String montant = jtbCProduitSelect.getValueAt(i, 3).toString();// le 3 est le numéro de la colonne
     total = total + Double.parseDouble(montant);
     
 }
         lblTotal.setText(total+ " "); //conversion de total en text
   }
       
        public void calculReste(){
        //fonction pour calcul produit total
        reste = 0; //initialisation de la valeur à zero ce qu'on avait déclaré au début
 
     
     String montant = lblTotal.getText();
     String somme = txtSommeAvance.getText().toString();
     
     // le 3 est le numéro de la colonne
     reste = Double.parseDouble(montant) - Double.parseDouble(somme);
     
 
         lblReste.setText(reste+ " "); //conversion de total en text
   }
    
    /**
     * @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(Vente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Vente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Vente.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Vente.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 Vente().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 btnSearchMedicament;
    private javax.swing.JComboBox<String> cbClient;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JRadioButton jRadioButton1;
    private javax.swing.JRadioButton jRadioButton2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTable jtbCProduit;
    private javax.swing.JTable jtbCProduitSelect;
    private javax.swing.JLabel lblReste;
    private javax.swing.JLabel lblTotal;
    private javax.swing.JTextField txtQuantite;
    private javax.swing.JTextField txtSerchMedicament;
    private javax.swing.JTextField txtSommeAvance;
    // End of variables declaration//GEN-END:variables
}
