/*
 * 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.awt.Dimension;
import java.awt.Toolkit;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

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

    /**
     * Creates new form Client
     */
    public Client() {
        initComponents();
        Toolkit toolkit = getToolkit();
        Dimension size = toolkit.getScreenSize();
        setLocation(size.width/2 - getWidth()/2, 
        size.height/2 - getHeight()/2);
        this.setLocationRelativeTo(this); 
        this.setResizable(false); 
        rafraichir();
        
       // lblNomPharmacie.setText(String.valueOf(InterfaceLogin.nomPharmacie).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() {

        jLabel2 = new javax.swing.JLabel();
        txtNomClient = new javax.swing.JTextField();
        txtPrenomClient = new javax.swing.JTextField();
        txtTelephoneClient = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        btnAjoutClient = new javax.swing.JButton();
        btnSupprimerClient = new javax.swing.JButton();
        btnEffacerFormulaireClient = new javax.swing.JButton();
        btnModifierClient = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtbClient = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        txtRechercheClient = new javax.swing.JTextField();
        jLabel7 = new javax.swing.JLabel();
        btnRechercherClient = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jButton6 = new javax.swing.JButton();
        jLabel9 = new javax.swing.JLabel();
        jScrollPane3 = new javax.swing.JScrollPane();
        txtAdresseClient = new javax.swing.JTextArea();

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

        jLabel2.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
        jLabel2.setText("Nom: ");
        getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 200, 80, 30));

        txtNomClient.setFont(new java.awt.Font("Segoe UI Semibold", 1, 16)); // NOI18N
        txtNomClient.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtNomClientActionPerformed(evt);
            }
        });
        getContentPane().add(txtNomClient, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 150, 220, -1));

        txtPrenomClient.setFont(new java.awt.Font("Segoe UI Semibold", 1, 16)); // NOI18N
        getContentPane().add(txtPrenomClient, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 200, 220, -1));

        txtTelephoneClient.setFont(new java.awt.Font("Segoe UI Semibold", 1, 16)); // NOI18N
        getContentPane().add(txtTelephoneClient, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 250, 220, -1));

        jLabel3.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
        jLabel3.setText("Prénom: ");
        getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 150, 80, -1));

        jLabel4.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
        jLabel4.setText("Adresse:");
        getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 320, 80, -1));

        jLabel5.setFont(new java.awt.Font("Segoe UI", 1, 14)); // NOI18N
        jLabel5.setText("Téléphone: ");
        getContentPane().add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 250, 80, -1));

        btnAjoutClient.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Save-icon.png"))); // NOI18N
        btnAjoutClient.setText("Enregistrer");
        btnAjoutClient.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAjoutClientActionPerformed(evt);
            }
        });
        getContentPane().add(btnAjoutClient, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 440, 130, 40));

        btnSupprimerClient.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/delete_16x16.gif"))); // NOI18N
        btnSupprimerClient.setText("Supprimer");
        btnSupprimerClient.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSupprimerClientActionPerformed(evt);
            }
        });
        getContentPane().add(btnSupprimerClient, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 440, 130, 40));

        btnEffacerFormulaireClient.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/erase-128.png"))); // NOI18N
        btnEffacerFormulaireClient.setText("Effacer");
        btnEffacerFormulaireClient.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEffacerFormulaireClientActionPerformed(evt);
            }
        });
        getContentPane().add(btnEffacerFormulaireClient, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 500, 130, 40));

        btnModifierClient.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/update icon.png"))); // NOI18N
        btnModifierClient.setText("Modifier");
        btnModifierClient.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnModifierClientActionPerformed(evt);
            }
        });
        getContentPane().add(btnModifierClient, new org.netbeans.lib.awtextra.AbsoluteConstraints(240, 500, 130, 40));

        jtbClient.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jtbClient.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"
            }
        ));
        jtbClient.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jtbClientMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jtbClient);

        getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(470, 110, 580, 290));

        jLabel1.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Ajout Nouvel Utilisateur", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Segoe UI", 3, 18))); // NOI18N
        getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 100, 430, 310));
        getContentPane().add(txtRechercheClient, new org.netbeans.lib.awtextra.AbsoluteConstraints(100, 40, 180, -1));
        getContentPane().add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 40, -1, -1));

        btnRechercherClient.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/loop.png"))); // NOI18N
        btnRechercherClient.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnRechercherClientMouseClicked(evt);
            }
        });
        getContentPane().add(btnRechercherClient, new org.netbeans.lib.awtextra.AbsoluteConstraints(330, 30, 50, 40));

        jLabel6.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Recherche Client", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 16))); // NOI18N
        getContentPane().add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 10, 430, 80));

        jLabel8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/ACCUEIL.png"))); // NOI18N
        jLabel8.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        jLabel8.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jLabel8MouseClicked(evt);
            }
        });
        getContentPane().add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(990, 10, 50, 50));

        jButton6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/achat.png"))); // NOI18N
        jButton6.setBorder(new javax.swing.border.SoftBevelBorder(javax.swing.border.BevelBorder.RAISED));
        jButton6.setContentAreaFilled(false);
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton6, new org.netbeans.lib.awtextra.AbsoluteConstraints(890, 10, 60, 40));
        getContentPane().add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 650, 1090, 70));

        txtAdresseClient.setColumns(20);
        txtAdresseClient.setFont(new java.awt.Font("Segoe UI Black", 0, 16)); // NOI18N
        txtAdresseClient.setRows(5);
        jScrollPane3.setViewportView(txtAdresseClient);

        getContentPane().add(jScrollPane3, new org.netbeans.lib.awtextra.AbsoluteConstraints(110, 290, 310, 100));

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

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

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
       new Vente().setVisible(true);
        dispose();
    }//GEN-LAST:event_jButton6ActionPerformed

    private void jLabel8MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel8MouseClicked
            new AccueilPharmacie().setVisible(true);  
            dispose();// TODO add your handling code here:
    }//GEN-LAST:event_jLabel8MouseClicked

    
        public void viderChampsClient (){
            
        txtAdresseClient.setText("");
        txtNomClient.setText("");
        txtTelephoneClient.setText("");
        txtPrenomClient.setText("");
        txtRechercheClient.setText("");
        
        }
    private void btnAjoutClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAjoutClientActionPerformed
        
              // TODO add your handling code here:
        String nom = txtNomClient.getText();
        String prenom = txtPrenomClient.getText();
        String adresse = txtAdresseClient.getText();
        String telephone = txtTelephoneClient.getText();
        

        if (nom.isEmpty() || prenom.isEmpty() || adresse.isEmpty() || telephone.isEmpty()){
            JOptionPane.showMessageDialog(this, "Veuillez remplir les champs");
            return;
        }

        BDPharmacie bd = new BDPharmacie();
          String resultat = bd.checkTelephoneClient(telephone);
        if(resultat !=null){
            JOptionPane.showMessageDialog(this, "Numéro de téléphone déjà attribué à un client, veuillez en choisir un autre");
            return;
        }
        
        boolean result = bd.saveClient(nom, prenom, adresse, telephone, InterfaceLogin.idPharmacie);

        if (result) {
            JOptionPane.showMessageDialog(this, "Nouveau client enregistré");
            rafraichir();
            viderChampsClient(); //vider les
        } else {
            JOptionPane.showMessageDialog(this, "Erreur enregistrement");
        }
    }//GEN-LAST:event_btnAjoutClientActionPerformed

    private void btnSupprimerClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSupprimerClientActionPerformed
        
        try {

             BDPharmacie bd=new BDPharmacie();
             Connection connex=bd.connectToBD();
             String sql="DELETE FROM client WHERE (id_client =? AND id_pharmacie = ?)";
             PreparedStatement stm=connex.prepareStatement(sql);
             int id=Integer.parseInt(idClient);
             stm.setInt(1, id);
             stm.setInt(2, InterfaceLogin.idPharmacie);

  
            int choix=JOptionPane.showConfirmDialog(this, "Voulez-vous supprimer ce client de votre liste ?" , "Suppression", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
  
                 if(choix==JOptionPane.YES_OPTION)
                 {
                      stm.executeUpdate();
                         
                          viderChampsClient();
                      JOptionPane.showMessageDialog(this, "Client supprimé");
                      rafraichir();
                     }
                 
  
        } catch (Exception e) {
            e.printStackTrace();
        }
    }//GEN-LAST:event_btnSupprimerClientActionPerformed
    String idClient;
    private void jtbClientMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtbClientMouseClicked
        int ligne=jtbClient.getSelectedRow();
            idClient=jtbClient.getValueAt(ligne, 0).toString();
            String nom=jtbClient.getValueAt(ligne, 1).toString();
            String prenom=jtbClient.getValueAt(ligne, 2).toString();
            String telephone=jtbClient.getValueAt(ligne, 3).toString();
            String adresse=jtbClient.getValueAt(ligne, 4).toString();
            

                txtNomClient.setText(nom);
                txtPrenomClient.setText(prenom);
                txtTelephoneClient.setText(telephone);
                jLabel1.setText(adresse);
                
    }//GEN-LAST:event_jtbClientMouseClicked
 public void rafraichir()
    {
       
        try {
             BDPharmacie bd=new BDPharmacie();
             Connection connex= bd.connectToBD();
             String sql="SELECT * FROM client WHERE id_pharmacie = '"+InterfaceLogin.idPharmacie+"'  ORDER BY nom ASC";
             PreparedStatement stm=connex.prepareStatement(sql);
             ResultSet rs=stm.executeQuery();
             DefaultTableModel dftm=new DefaultTableModel();
             String columns[]={"ID", "NOM", "PRENOM","TELEPHONE", "ADRESSE"};
             dftm.setColumnIdentifiers(columns); 
             
             while(rs.next())
             { 
                 String id=rs.getString("id_client");
                 String prenom=rs.getString("prenom");
                 String nom=rs.getString("nom");
                 String adresse=rs.getString("adresse");
                 String telephone=rs.getString("telephone");
                 
                 
                 Vector v=new Vector();
                 v.add(id);
                 v.add(prenom);
                 v.add(nom);
                 v.add(telephone);
                 v.add(adresse);
                 dftm.addRow(v); 
                 
             }
             
             jtbClient.setModel(dftm); 
        
        } catch (Exception e) {
            e.printStackTrace();
        }
          
    }
    private void btnRechercherClientMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_btnRechercherClientMouseClicked
            rechercherClient();        // TODO add your handling code here:
    }//GEN-LAST:event_btnRechercherClientMouseClicked

    private void btnEffacerFormulaireClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEffacerFormulaireClientActionPerformed
        
        viderChampsClient();
    }//GEN-LAST:event_btnEffacerFormulaireClientActionPerformed

    private void btnModifierClientActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnModifierClientActionPerformed
     String prenom=txtPrenomClient.getText().toString();
     String nom=txtNomClient.getText().toString();
     String telephone=txtTelephoneClient.getText().toString();
     String adresse=txtAdresseClient.getText().toString();

     int id=Integer.parseInt(idClient);
                int p = JOptionPane.showConfirmDialog(null, "Voulez-vous vraiment modifier le client?","Modification Information Client",JOptionPane.YES_NO_OPTION);
        if(p==0){
                   try {
                BDPharmacie bd=new BDPharmacie();
                Connection connex=bd.connectToBD();
                String sql="UPDATE client set prenom=?, nom=?, telephone=?, adresse=?  WHERE (id_client = ? AND id_pharmacie = ?)";
                PreparedStatement stm=connex.prepareStatement(sql);
                stm.setString(1, prenom);
                stm.setString(2, nom);
                stm.setString(3, telephone); 
                stm.setString(4, adresse); 
                stm.setInt(5, id); 
                stm.setInt(6, InterfaceLogin.idPharmacie);
                stm.executeUpdate();
                rafraichir();
                viderChampsClient();
            
                JOptionPane.showMessageDialog(this, "Utilisateur modifié"); 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }//GEN-LAST:event_btnModifierClientActionPerformed
    }
   public void rechercherClient () {
            
            String nomSearch="%"+txtRechercheClient.getText()+"%";
       
        try {
             BDPharmacie bd=new BDPharmacie();
             Connection connex= bd.connectToBD();
             String sql="SELECT * FROM client WHERE (telephone LIKE ? AND id_pharmacie ='"+InterfaceLogin.idPharmacie+"' )";
             PreparedStatement stm=connex.prepareStatement(sql);
             
             stm.setString(1, nomSearch);
             
             
             ResultSet rs=stm.executeQuery();
             DefaultTableModel dftm=new DefaultTableModel();
             String columns[]={"ID", "NOM","PRENOM", "TELEPHONE", "ADRESSE"};
             dftm.setColumnIdentifiers(columns); 
             
             while(rs.next())
             { 
                 String id=rs.getString("id_client");
                 String prenom=rs.getString("nom");
                 String nom=rs.getString("prenom");
                 String telephone =rs.getString("telephone");
                 String adresse =rs.getString("adresse");
                 
                
                 Vector v=new Vector();
                 v.add(id);
                 v.add(nom);
                 v.add(prenom);
                 v.add(telephone);
                 v.add(adresse);
                 
                 
                 dftm.addRow(v); 
                 
             }
             
             jtbClient.setModel(dftm); 
        
        } 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(Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Client.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Client.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 Client().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAjoutClient;
    private javax.swing.JButton btnEffacerFormulaireClient;
    private javax.swing.JButton btnModifierClient;
    private javax.swing.JButton btnRechercherClient;
    private javax.swing.JButton btnSupprimerClient;
    private javax.swing.JButton jButton6;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    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.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane3;
    private javax.swing.JTable jtbClient;
    private javax.swing.JTextArea txtAdresseClient;
    private javax.swing.JTextField txtNomClient;
    private javax.swing.JTextField txtPrenomClient;
    private javax.swing.JTextField txtRechercheClient;
    private javax.swing.JTextField txtTelephoneClient;
    // End of variables declaration//GEN-END:variables
}
