/*
 * 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.util.Vector;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

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

    /**
     * Creates new form User
     */
    public FirstUserPharma() {
        initComponents();
        this.setLocationRelativeTo(this); 
        this.setResizable(false);
       // lblNomPharmacie.setText(String.valueOf(InterfaceLogin.nomPharmacie).toString());
        raffraichir_user();
        chargerPharmacie();
    }
public static int idPharmacie;
    /**
     * 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();
        txtNomPharmacien = new javax.swing.JTextField();
        txtLoginPharmacien = new javax.swing.JTextField();
        txtPasswordPharmacien = new javax.swing.JPasswordField();
        txtPasswordPharmacien1 = new javax.swing.JPasswordField();
        btnAjoutFirstUserPharmacie = 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();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        jtbFirstUserPharma = new javax.swing.JTable();
        cbxNomPharmacie = new javax.swing.JComboBox<>();

        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, 160, 120, 40);

        jLabel2.setFont(new java.awt.Font("Trebuchet MS", 1, 16)); // NOI18N
        jLabel2.setText("Nom :");
        jPanel1.add(jLabel2);
        jLabel2.setBounds(40, 220, 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(txtNomPharmacien);
        txtNomPharmacien.setBounds(230, 210, 200, 30);
        jPanel1.add(txtLoginPharmacien);
        txtLoginPharmacien.setBounds(230, 160, 200, 30);

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

        btnAjoutFirstUserPharmacie.setFont(new java.awt.Font("Tw Cen MT", 1, 16)); // NOI18N
        btnAjoutFirstUserPharmacie.setIcon(new javax.swing.ImageIcon(getClass().getResource("/images/Save-icon.png"))); // NOI18N
        btnAjoutFirstUserPharmacie.setText("Ajout");
        btnAjoutFirstUserPharmacie.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAjoutFirstUserPharmacieActionPerformed(evt);
            }
        });
        jPanel1.add(btnAjoutFirstUserPharmacie);
        btnAjoutFirstUserPharmacie.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("Pharmacie:");
        jPanel1.add(jLabel6);
        jLabel6.setBounds(41, 100, 100, 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);

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

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

        cbxNomPharmacie.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Item 1", "Item 2", "Item 3", "Item 4" }));
        cbxNomPharmacie.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cbxNomPharmacieActionPerformed(evt);
            }
        });
        jPanel1.add(cbxNomPharmacie);
        cbxNomPharmacie.setBounds(230, 100, 180, 30);

        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 (){
            
        
        txtNomPharmacien.setText("");
        txtLoginPharmacien.setText("");
        txtPasswordPharmacien.setText("");
        txtPasswordPharmacien1.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 =?)";
             PreparedStatement stm=connex.prepareStatement(sql);
             int id=Integer.parseInt(idPharma);
             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 btnAjoutFirstUserPharmacieActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAjoutFirstUserPharmacieActionPerformed
        // TODO add your handling code here:
        
        String pharm = cbxNomPharmacie.getSelectedItem().toString();
        String idPharm = pharm.substring(0, pharm.indexOf(" "));
        int idPha = Integer.parseInt(idPharm);
        
        String login = txtLoginPharmacien.getText();
        String nom = txtNomPharmacien.getText();
        String password = txtPasswordPharmacien.getText();
        String password1 = txtPasswordPharmacien1.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;
        }
        

        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.saveFirstUserPharma(login, password, nom, idPha);

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

    private void jLabel8MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jLabel8MouseClicked
    dispose();        // TODO add your handling code here:
    }//GEN-LAST:event_jLabel8MouseClicked
    String idPharma;
    private void jtbFirstUserPharmaMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jtbFirstUserPharmaMouseClicked
        // TODO add your handling code here:
            int ligne=jtbFirstUserPharma.getSelectedRow();
             idPharma = jtbFirstUserPharma.getValueAt(ligne, 0).toString();
            String nomUser=jtbFirstUserPharma.getValueAt(ligne, 1).toString();
            String login=jtbFirstUserPharma.getValueAt(ligne, 2).toString();
            //String fonction = jtbFirstUserPharma.getValueAt(ligne, 3).toString();
            String nomPharmacie = jtbFirstUserPharma.getValueAt(ligne, 4).toString();
           
                        
                txtLoginPharmacien.setText(login);
                txtNomPharmacien.setText(nomUser);
                cbxNomPharmacie.setSelectedItem(nomPharmacie);
                
    }//GEN-LAST:event_jtbFirstUserPharmaMouseClicked

    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 txtPasswordPharmacienActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_txtPasswordPharmacienActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_txtPasswordPharmacienActionPerformed
    
    public void viderChampUser (){
        txtLoginPharmacien.setText("");
        txtNomPharmacien.setText("");
        txtPasswordPharmacien.setText("");
        txtPasswordPharmacien1.setText("");
        
    }  
    
    
    
    
    public void chargerPharmacie (){
      BDPharmacie  bd = new BDPharmacie();
      Connection connex = bd.connectToBD();
        try {
            String sql = "SELECT * FROM pharmacie WHERE profil IS NULL ORDER BY nom_pharmacie ";
            PreparedStatement stm = connex.prepareStatement(sql);
            ResultSet rs = stm.executeQuery();
            cbxNomPharmacie.removeAllItems();
            
            while (rs.next())
            {
                String id = rs.getString("id_pharmacie");
                String nomPharmacie = rs.getString("nom_pharmacie");
                                
                idPharmacie = Integer.parseInt(id);
                String pharma = id+" "+nomPharmacie;
                cbxNomPharmacie.addItem(pharma);
               
            }
            
            }
        
         catch (Exception e) {
            e.printStackTrace();
        }
        
        
    }
    
    
    private void cbxNomPharmacieActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cbxNomPharmacieActionPerformed
        // TODO add your handling code here:
    }//GEN-LAST:event_cbxNomPharmacieActionPerformed

    public void raffraichir_user(){
        try {
             BDPharmacie bd=new BDPharmacie();
             Connection connex= bd.connectToBD();
             String sql="SELECT u.id_user, u.login, u.nom, u.profil, p.nom_pharmacie AS nomPh\n" +
                        "FROM user u, pharmacie p\n" +
                        "WHERE u.id_pharmacie = p.id_pharmacie ORDER BY 5";
             PreparedStatement stm=connex.prepareStatement(sql);
             ResultSet rs=stm.executeQuery();
             DefaultTableModel dftm=new DefaultTableModel();
             String columns[]={"ID", "Nom", "Login","Fonction", "Pharmacie"};
             dftm.setColumnIdentifiers(columns); 
             
             while(rs.next())
             { 
                 String id=rs.getString("u.id_user");
                 String nom=rs.getString("u.nom");
                 String login=rs.getString("u.login");
                 String fonction=rs.getString("u.profil");
                 String nomPharmacie = rs.getString("nomPh");
                 
                 Vector v=new Vector();
                 v.add(id);
                 v.add(nom);
                 v.add(login);
                 v.add(fonction);
                 v.add(nomPharmacie);
                 dftm.addRow(v); 
                 
             }
             
             jtbFirstUserPharma.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(FirstUserPharma.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FirstUserPharma.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FirstUserPharma.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FirstUserPharma.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>

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

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btnAjoutFirstUserPharmacie;
    private javax.swing.JButton btnEffacer;
    private javax.swing.JButton btnModifierUser;
    private javax.swing.JButton btnSupprimerUser;
    private javax.swing.JComboBox<String> cbxNomPharmacie;
    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 jtbFirstUserPharma;
    private javax.swing.JTextField txtLoginPharmacien;
    private javax.swing.JTextField txtNomPharmacien;
    private javax.swing.JPasswordField txtPasswordPharmacien;
    private javax.swing.JPasswordField txtPasswordPharmacien1;
    // End of variables declaration//GEN-END:variables
}
