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

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import net.proteanit.sql.DbUtils;



/**
 *
 * @author Sabit
 */
public class AdminPanel extends javax.swing.JFrame {

    /**
     * Creates new form adminPanel
     */
    public AdminPanel() {
        initComponents();
        setTitle("Admin Panel");
        updateTable();
        idFld.setEnabled(false);
        deleteUserBtn.setVisible(false);
        updateUserBtn.setVisible(false);
        userNameFld.setVisible(false);
        passwordFld.setVisible(false);
        
        usertypeFld.setVisible(false);
        idLbl.setVisible(false);
        idFld.setVisible(false);
        userNameLbl.setVisible(false);
        passwordLbl.setVisible(false);
        userTypeLbl.setVisible(false);
        userTypeBox.setVisible(false);
    }

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

        jLabel1 = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        deleteUserBtn = new javax.swing.JButton();
        updateUserBtn = new javax.swing.JButton();
        addUserBtn = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        adminTable = new javax.swing.JTable();
        jPanel1 = new javax.swing.JPanel();
        idLbl = new javax.swing.JLabel();
        idFld = new javax.swing.JTextField();
        userNameLbl = new javax.swing.JLabel();
        userNameFld = new javax.swing.JTextField();
        passwordLbl = new javax.swing.JLabel();
        passwordFld = new javax.swing.JTextField();
        userTypeLbl = new javax.swing.JLabel();
        userTypeBox = new javax.swing.JComboBox<>();
        usertypeFld = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel1.setText("                                                                       Admin Panel");

        deleteUserBtn.setText("Del User");
        deleteUserBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteUserBtnActionPerformed(evt);
            }
        });

        updateUserBtn.setText("Update User");
        updateUserBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                updateUserBtnActionPerformed(evt);
            }
        });

        addUserBtn.setText("Add User ");
        addUserBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addUserBtnActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(deleteUserBtn, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(updateUserBtn)
                    .addComponent(addUserBtn, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(0, 0, Short.MAX_VALUE))
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel2Layout.createSequentialGroup()
                .addGap(0, 14, Short.MAX_VALUE)
                .addComponent(addUserBtn)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(updateUserBtn)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(deleteUserBtn))
        );

        adminTable.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "User Name", "Password", "User Type"
            }
        ));
        adminTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                adminTableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(adminTable);

        idLbl.setText("Id");

        idFld.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                idFldActionPerformed(evt);
            }
        });

        userNameLbl.setText("User Name");

        userNameFld.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                userNameFldActionPerformed(evt);
            }
        });

        passwordLbl.setText("Password");

        userTypeLbl.setText("User Type");

        userTypeBox.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "Select", "User", "Admin" }));
        userTypeBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                userTypeBoxActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(passwordFld, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(userNameFld, javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(idFld)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(passwordLbl)
                            .addComponent(userTypeLbl))
                        .addGap(0, 0, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(userNameLbl)
                            .addComponent(idLbl, javax.swing.GroupLayout.PREFERRED_SIZE, 27, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(119, 119, 119))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addComponent(userTypeBox, 0, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addGap(18, 18, 18)
                        .addComponent(usertypeFld, javax.swing.GroupLayout.PREFERRED_SIZE, 28, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap())
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(idLbl)
                .addGap(16, 16, 16)
                .addComponent(idFld, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(userNameLbl)
                .addGap(18, 18, 18)
                .addComponent(userNameFld, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(passwordLbl)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(passwordFld, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(userTypeLbl)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(userTypeBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(usertypeFld, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap())
        );

        jButton1.setText("Back");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 796, Short.MAX_VALUE)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jButton1))))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jScrollPane1)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 86, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jPanel2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(jButton1))
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(0, 12, Short.MAX_VALUE))
        );

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

    private void addUserBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addUserBtnActionPerformed
        
        ProfileForm pf = new ProfileForm();
        dispose();
        pf.setVisible(true);
        

    }//GEN-LAST:event_addUserBtnActionPerformed

    private void updateUserBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_updateUserBtnActionPerformed
        updateUser();
        
    }//GEN-LAST:event_updateUserBtnActionPerformed

    private void adminTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_adminTableMouseClicked
        
        int i = adminTable.getSelectedRow();
        DefaultTableModel model = (DefaultTableModel) adminTable.getModel();
        userNameFld.setEnabled(true);
        passwordFld.setEnabled(true);
        idFld.setText(model.getValueAt(i, 0).toString());
        userNameFld.setText(model.getValueAt(i, 1).toString());
        passwordFld.setText(model.getValueAt(i, 2).toString());
        addUserBtn.setVisible(false);
        deleteUserBtn.setEnabled(true);
        updateUserBtn.setEnabled(true);
        idFld.setVisible(false);
        userNameLbl.setVisible(true);
        passwordLbl.setVisible(true);
        userTypeLbl.setVisible(true);
        userTypeBox.setVisible(true);
        userNameFld.setVisible(true);
        passwordFld.setVisible(true);
        deleteUserBtn.setVisible(true);
        updateUserBtn.setVisible(true);
        

    }//GEN-LAST:event_adminTableMouseClicked

    private void deleteUserBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteUserBtnActionPerformed
        
        deleteUser();
    }//GEN-LAST:event_deleteUserBtnActionPerformed

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        
        MainPage mp = new MainPage();
        dispose();
        mp.wcLbl.setText("Welcome: " +GlobalConstant.name);
        mp.setVisible(true);
    }//GEN-LAST:event_jButton1ActionPerformed

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

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

    private void userTypeBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_userTypeBoxActionPerformed
        // TODO add your handling code here:
        
        if (userTypeBox.getSelectedItem().equals("User")) {
            usertypeFld.setText("0");
        } else if (userTypeBox.getSelectedItem().equals("Admin")) {
            usertypeFld.setText("1");
        }
        
    }//GEN-LAST:event_userTypeBoxActionPerformed

    /**
     * @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(AdminPanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(AdminPanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(AdminPanel.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(AdminPanel.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 AdminPanel().setVisible(true);
            }
        });
    }
    
    public void updateTable() {
        Connection con;
        
        PreparedStatement ps;
        try {
            con = DriverManager.getConnection("jdbc:mysql://localhost/medical_store", "root", "root");
            ps = con.prepareStatement("SELECT * FROM users");
            
            ResultSet rs = ps.executeQuery();
            adminTable.setModel(DbUtils.resultSetToTableModel(rs));
            
        } catch (SQLException ex) {
            
            Logger.getLogger(LoginForm.class.getName()).log(Level.SEVERE, null, ex);
            
        }
    }
    
    public void deleteUser() {
        AdminPanel ap = new AdminPanel();

        String sql = "DELETE FROM  users  WHERE id='" + idFld.getText() + "'";
        
        Connection con;
        PreparedStatement ps;
        try {
            
            con = DriverManager.getConnection("jdbc:mysql://localhost/medical_store", "root", "root");
            ps = con.prepareStatement(sql);
            
            int save = ps.executeUpdate();

            System.out.println("executeQuery");
            
            if (save > 0) {
                System.out.println("Deleted");
                JOptionPane.showMessageDialog(null, "Deleted");
                dispose();
                ap.updateTable();
                ap.setVisible(true);
                dispose();
                
            } else {
                System.out.println("Not Deleted");
                JOptionPane.showMessageDialog(null, "Not Deleted");
                
            }
            
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Deleted Valid Data");
            dispose();
            ap.setVisible(true);
        }
        
    }
    
    public void updateUser() {
        AdminPanel ap = new AdminPanel();

        String sql = "UPDATE users SET 	user_type='" + usertypeFld.getText() + "',username='" + userNameFld.getText() + "',password='" + passwordFld.getText() + "' WHERE id='" + idFld.getText() + "'";
        
        Connection con;
        PreparedStatement ps;
        try {
            
            con = DriverManager.getConnection("jdbc:mysql://localhost/medical_store", "root", "root");
            ps = con.prepareStatement(sql);
            
            int save = ps.executeUpdate();

            System.out.println("executeQuery");
            
            if (save > 0) {
                System.out.println("Inserted");
                JOptionPane.showMessageDialog(null, "User Updated");
                dispose();
                ap.updateTable();
                ap.setVisible(true);
                dispose();
                
            } else {
                System.out.println("Not Inserted");
                JOptionPane.showMessageDialog(null, "Not saved");
                
            }
            
        } catch (SQLException ex) {
            JOptionPane.showMessageDialog(null, "Insert Valid Data");
            dispose();
            ap.setVisible(true);
        }
        
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addUserBtn;
    private javax.swing.JTable adminTable;
    private javax.swing.JButton deleteUserBtn;
    private javax.swing.JTextField idFld;
    private javax.swing.JLabel idLbl;
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField passwordFld;
    private javax.swing.JLabel passwordLbl;
    private javax.swing.JButton updateUserBtn;
    private javax.swing.JTextField userNameFld;
    private javax.swing.JLabel userNameLbl;
    private javax.swing.JComboBox<String> userTypeBox;
    private javax.swing.JLabel userTypeLbl;
    private javax.swing.JTextField usertypeFld;
    // End of variables declaration//GEN-END:variables

}
