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

    /**
     * Creates new form User
     */
    public User() {
        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); 
        lblNomPharmacie.setText(String.valueOf(InterfaceLogin.nomPharmacie).toString());
        raffraichir_user();
    }

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

        jPanel1 = new javax.swing.JPanel();
        jLabel3 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        txtNom = new javax.swing.JTextField();
        txtLogin = new javax.swing.JTextField();
        txtPassword = new javax.swing.JPasswordField();
        txtPassword1 = new javax.swing.JPasswordField();
        cbxFonction = new javax.swing.JComboBox<>();
        btnAjoutUser = new javax.swing.JButton();
        btnSupprimerUser = new javax.swing.JButton();
        btnModifierUser = new javax.swing.JButton();
        btnEffacer = new javax.swing.JButton();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel1 = new javax.swing.JLabel();
        lblNomPharmacie = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtbUser = new javax.swing.JTable();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jPanel1.setLayout(null);

        jLabel3.setFont(new java.awt.Font("Trebuchet MS", 1, 16)); // NOI18N
        jLabel3.setText("Identifiant :");
        jPanel1.add(jLabel3);
        jLabel3.setBounds(40, 210, 120, 40);

        jLabel2.setFont(new java.awt.Font("Trebuchet MS", 1, 16)); // NOI18N
        jLabel2.setText("Nom :");
        jPanel1.add(jLabel2);
        jLabel2.setBounds(40, 160, 90, 19);

        jLabel4.setFont(new java.awt.Font("Trebuchet MS", 1, 16)); // NOI18N
        jLabel4.setText("Mot de passe :");
        jPanel1.add(jLabel4);
        jLabel4.setBounds(40, 270, 110, 19);
        jPanel1.add(txtNom);
        txtNom.setBounds(230, 160, 200, 30);
        jPanel1.add(txtLogin);
        txtLogin.setBounds(230, 210, 200, 30);

        txtPassword.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                txtPasswordActionPerformed(evt);
            }
        });
        jPanel1.add(txtPassword);
        txtPassword.setBounds(230, 260, 200, 30);
        jPanel1.add(txtPassword1);
        txtPassword1.setBounds(230, 320, 200, 30);

        cbxFonction.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Vendeur", "Comptable", "Pharmacien", "Administrateur" }));
        jPanel1.add(cbxFonction);
        cbxFonction.setBounds(230, 110, 200, 30);

        btnAjoutUser.setFont(new java.awt.Font("Tw Cen MT", 1, 16)); // NOI18N
        btnAjoutUser.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Save-icon.png"))); // NOI18N
        btnAjoutUser.setText("Ajout");
        btnAjoutUser.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAjoutUserActionPerformed(evt);
            }
        });
        jPanel1.add(btnAjoutUser);
        btnAjoutUser.setBounds(480, 139, 140, 40);

        btnSupprimerUser.setFont(new java.awt.Font("Tw Cen MT", 1, 16)); // NOI18N
        btnSupprimerUser.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/delete_16x16.gif"))); // NOI18N
        btnSupprimerUser.setText("Supprimer");
        btnSupprimerUser.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSupprimerUserActionPerformed(evt);
            }
        });
        jPanel1.add(btnSupprimerUser);
        btnSupprimerUser.setBounds(480, 189, 140, 40);

        btnModifierUser.setFont(new java.awt.Font("Tw Cen MT", 1, 16)); // NOI18N
        btnModifierUser.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/update icon.png"))); // NOI18N
        btnModifierUser.setText("Modifier");
        btnModifierUser.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnModifierUserActionPerformed(evt);
            }
        });
        jPanel1.add(btnModifierUser);
        btnModifierUser.setBounds(480, 239, 140, 40);

        btnEffacer.setFont(new java.awt.Font("Tw Cen MT", 1, 16)); // NOI18N
        btnEffacer.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/erase-128.png"))); // NOI18N
        btnEffacer.setText("Effacer");
        btnEffacer.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEffacerActionPerformed(evt);
            }
        });
        jPanel1.add(btnEffacer);
        btnEffacer.setBounds(480, 289, 140, 40);

        jLabel5.setFont(new java.awt.Font("Trebuchet MS", 1, 16)); // NOI18N
        jLabel5.setText("Re-tapez le mot de passe");
        jPanel1.add(jLabel5);
        jLabel5.setBounds(40, 330, 220, 19);

        jLabel6.setFont(new java.awt.Font("Trebuchet MS", 1, 16)); // NOI18N
        jLabel6.setText("Fonction :");
        jPanel1.add(jLabel6);
        jLabel6.setBounds(41, 100, 80, 30);

        jLabel1.setBorder(javax.swing.BorderFactory.createTitledBorder(javax.swing.BorderFactory.createTitledBorder("Nouveau utilisateur"), "", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 1, 18))); // NOI18N
        jPanel1.add(jLabel1);
        jLabel1.setBounds(20, 60, 450, 350);

        lblNomPharmacie.setFont(new java.awt.Font("Tahoma", 1, 24)); // NOI18N
        lblNomPharmacie.setForeground(new java.awt.Color(51, 204, 0));
        lblNomPharmacie.setText("Nom Pharmacie");
        jPanel1.add(lblNomPharmacie);
        lblNomPharmacie.setBounds(330, 20, 220, 30);

        jLabel7.setFont(new java.awt.Font("Vivaldi", 1, 24)); // NOI18N
        jLabel7.setText("Gestion personnel de");
        jPanel1.add(jLabel7);
        jLabel7.setBounds(110, 20, 200, 30);

        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);
            }
        });
        jPanel1.add(jLabel8);
        jLabel8.setBounds(550, 10, 60, 60);

        jtbUser.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"
            }
        ));
        jtbUser.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jtbUserMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(jtbUser);

        jPanel1.add(jScrollPane1);
        jScrollPane1.setBounds(640, 80, 410, 300);

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 1069, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 593, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents
public void viderChampsUser (){
            
        
        txtNom.setText("");
        txtLogin.setText("");
        txtPassword.setText("");
        txtPassword1.setText("");
        
        }
    private void btnSupprimerUserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSupprimerUserActionPerformed
        // TODO add your handling code here:
         try {

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

  
            int choix=JOptionPane.showConfirmDialog(this, "Voulez-vous supprimer cet utilisateur de votre liste ?" , "Suppression", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
  
                 if(choix==JOptionPane.YES_OPTION)
                 {
                      stm.executeUpdate();
                         
                      viderChampsUser();
                      JOptionPane.showMessageDialog(this, "Client supprimé");
                     raffraichir_user();
                     }
                 
  
        } catch (Exception e) {
            e.printStackTrace();
        }
    }//GEN-LAST:event_btnSupprimerUserActionPerformed
    
    private void btnAjoutUserActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAjoutUserActionPerformed
        // TODO add your handling code here:
        String login = txtLogin.getText();
        String nom = txtNom.getText();
        String password = txtPassword.getText();
        String password1 = txtPassword1.getText();
        if (login.isEmpty() || nom.isEmpty() || password.isEmpty() || password1.isEmpty()){
            JOptionPane.showMessageDialog(this, "Veuillez remplir les champs");
            return;
        }
        if (password.equals(password1)==false){
          JOptionPane.showMessageDialog(this, "Mot de passe non conforme");
          return;
        }
        String profil = cbxFonction.getSelectedItem().toString();

        BDPharmacie bd = new BDPharmacie();
        String resultat = bd.checkLoginPharmacie(login);
        if(resultat !=null){
            JOptionPane.showMessageDialog(this, "Le login existe déjà, veuillez choisir un autre");
            return;
        }
        
        boolean result = bd.saveUser(login, password, nom, profil, InterfaceLogin.idPharmacie);

        if (result) {
            JOptionPane.showMessageDialog(this, "Utilisateur enregistré");
            raffraichir_user();
        } else {
            JOptionPane.showMessageDialog(this, "Erreur enregistrement");
        }
        
        
        
    }//GEN-LAST:event_btnAjoutUserActionPerformed

    private void jLabel8MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel8MouseClicked
    dispose();        // TODO add your handling code here:
    }//GEN-LAST:event_jLabel8MouseClicked
    String idUser;
    private void jtbUserMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtbUserMouseClicked
        // TODO add your handling code here:
            int ligne=jtbUser.getSelectedRow();
            idUser=jtbUser.getValueAt(ligne, 0).toString();
            String nom=jtbUser.getValueAt(ligne, 1).toString();
            String login=jtbUser.getValueAt(ligne, 2).toString();
            String fonction=jtbUser.getValueAt(ligne, 3).toString();
                        

                txtNom.setText(nom);
                txtLogin.setText(login);
                cbxFonction.setSelectedItem(fonction);
                
    }//GEN-LAST:event_jtbUserMouseClicked

    private void btnEffacerActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEffacerActionPerformed
                    viderChampsUser();       
    }//GEN-LAST:event_btnEffacerActionPerformed

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

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

    public final void raffraichir_user(){
        try {
             BDPharmacie bd=new BDPharmacie();
             Connection connex= bd.connectToBD();
             String sql="SELECT * FROM user  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", "IDENTIFIANT","FONCTION"};
             dftm.setColumnIdentifiers(columns); 
             
             while(rs.next())
             { 
                 String id=rs.getString("id_user");
                 String nom=rs.getString("nom");
                 String login=rs.getString("login");
                 String fonction=rs.getString("profil");
                 
                 Vector v=new Vector();
                 v.add(id);
                 v.add(nom);
                 v.add(login);
                 v.add(fonction);
                 dftm.addRow(v); 
                 
             }
             
             jtbUser.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(User.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(User.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(User.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(User.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 User().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAjoutUser;
    private javax.swing.JButton btnEffacer;
    private javax.swing.JButton btnModifierUser;
    private javax.swing.JButton btnSupprimerUser;
    private javax.swing.JComboBox<String> cbxFonction;
    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.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jtbUser;
    private javax.swing.JLabel lblNomPharmacie;
    private javax.swing.JTextField txtLogin;
    private javax.swing.JTextField txtNom;
    private javax.swing.JPasswordField txtPassword;
    private javax.swing.JPasswordField txtPassword1;
    // End of variables declaration//GEN-END:variables
}
