/*
 * 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 pakaian;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.awt.event.KeyEvent;
import java.sql.*;
import java.text.SimpleDateFormat;
import javax.swing.JOptionPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import koneksi.Koneksi;
/**
 *
 * @author Hp
 */
public class pelanggan extends javax.swing.JFrame {
    private final Connection conn = new Koneksi().connect();

    /**
     * Creates new form pelanggan
     */
    public pelanggan() {
        initComponents();
        table();
        tengah();
    }
    
     public void tengah()
    {
        Dimension dimmax = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension dimframe=this.getSize();
        this.setLocation((dimmax.width-dimframe.width)/2,
                        (dimmax.height-dimframe.height)/2);
    }
    protected void aktif(){
        nohpp.setEnabled(true);
        nma.setEnabled(true);
        jkel.setEnabled(true);
        almt.setEnabled(true);
        nohpp.requestFocus();
    }
    
   protected void kosong(){
    nohpp.setEnabled(true);
    nma.setText("");
    jkel.setSelectedIndex(0);
    almt.setText("");
}
   public void table() {
    DefaultTableModel model = new DefaultTableModel();
    model.addColumn("No HP");
    model.addColumn("Nama");
    model.addColumn("Jenis Kelamin");
    model.addColumn("Alamat");

    try {
        String sql = "SELECT * FROM pelanggan";
        java.sql.Statement stm = conn.createStatement();
        java.sql.ResultSet res = stm.executeQuery(sql);

        while (res.next()) {
            model.addRow(new Object[]{
                res.getString("nohp"), 
                res.getString("nama"), 
                res.getString("jk"), 
                res.getString("alamat")
            });
        }

        Jtable.setModel(model);
    } catch (Exception e) {
        JOptionPane.showMessageDialog(null, "Error: " + e.getMessage());
    }
}


    /**
     * 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();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        nohpp = new javax.swing.JTextField();
        nma = new javax.swing.JTextField();
        almt = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        Jtable = new javax.swing.JTable();
        jButton5 = new javax.swing.JButton();
        jkel = new javax.swing.JComboBox<>();
        jLabel6 = new javax.swing.JLabel();

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

        jLabel1.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
        jLabel1.setText("No HP");
        getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(24, 100, 100, -1));

        jLabel2.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
        jLabel2.setText("Nama");
        getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(24, 146, 71, -1));

        jLabel3.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
        jLabel3.setText("Alamat");
        getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(24, 242, 108, -1));

        jLabel4.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
        jLabel4.setText("Jenis Kelamin");
        getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(24, 194, 155, -1));

        nohpp.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                nohppKeyPressed(evt);
            }
        });
        getContentPane().add(nohpp, new org.netbeans.lib.awtextra.AbsoluteConstraints(203, 100, 279, -1));

        nma.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                nmaKeyPressed(evt);
            }
        });
        getContentPane().add(nma, new org.netbeans.lib.awtextra.AbsoluteConstraints(203, 152, 279, -1));
        getContentPane().add(almt, new org.netbeans.lib.awtextra.AbsoluteConstraints(203, 248, 279, -1));

        jButton1.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
        jButton1.setText("SAVE");
        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(549, 151, 83, -1));

        jButton2.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
        jButton2.setText("EDIT");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton2, new org.netbeans.lib.awtextra.AbsoluteConstraints(646, 199, 110, -1));

        jButton3.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
        jButton3.setText("DELETE");
        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(549, 199, -1, -1));

        jButton4.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
        jButton4.setText("KEMBALI");
        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(646, 151, 110, -1));

        Jtable.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 [] {
                "No HP", "NAMA", "JENIS KELAMIN", "ALAMAT"
            }
        ));
        Jtable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                JtableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(Jtable);

        getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(24, 290, 751, 389));

        jButton5.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
        jButton5.setText("CETAK DATA PELANGGAN");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });
        getContentPane().add(jButton5, new org.netbeans.lib.awtextra.AbsoluteConstraints(549, 247, -1, -1));

        jkel.setModel(new javax.swing.DefaultComboBoxModel<>(new String[] { "LAKI - LAKI", "PEREMPUAN" }));
        jkel.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jkelKeyPressed(evt);
            }
        });
        getContentPane().add(jkel, new org.netbeans.lib.awtextra.AbsoluteConstraints(203, 194, 146, 30));

        jLabel6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/bg/PELANGGAN-03.jpg"))); // NOI18N
        getContentPane().add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 790, 780));

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

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        // TODO add your handling code here:
      try {
    // Validasi input
    if (nohpp.getText().isEmpty() || nma.getText().isEmpty() || 
        jkel.getSelectedItem() == null || almt.getText().isEmpty()) {
        JOptionPane.showMessageDialog(null, "Silakan lengkapi data.");
    } else {
        String sql = "INSERT INTO pelanggan (nohp, nama, jk, alamat) VALUES (?, ?, ?, ?)";
        PreparedStatement stat = conn.prepareStatement(sql);
        stat.setString(1, nohpp.getText());
        stat.setString(2, nma.getText());
        stat.setString(3, jkel.getSelectedItem().toString());
        stat.setString(4, almt.getText());
        stat.executeUpdate();
        JOptionPane.showMessageDialog(null, "Data Berhasil Disimpan");
        table(); // refresh tabel
    }
} catch (SQLException e) {
    JOptionPane.showMessageDialog(null, "Gagal menyimpan data: " + e.getMessage());
}

    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        // TODO add your handling code here:
        // Tombol Edit
try {
    // Validasi input
    if (nohpp.getText().isEmpty() || nma.getText().isEmpty() || 
        jkel.getSelectedItem() == null || almt.getText().isEmpty()) {
        JOptionPane.showMessageDialog(null, "Silakan lengkapi data.");
    } else {
        String sql = "UPDATE pelanggan SET nama = ?, jk = ?, alamat = ? WHERE nohp = ?";
        PreparedStatement stat = conn.prepareStatement(sql);
        stat.setString(1, nma.getText());
        stat.setString(2, jkel.getSelectedItem().toString());
        stat.setString(3, almt.getText());
        stat.setString(4, nohpp.getText());
        int rowsUpdated = stat.executeUpdate();

        if (rowsUpdated > 0) {
            JOptionPane.showMessageDialog(null, "Data Berhasil Diperbarui");
            table(); // refresh tabel
        } else {
            JOptionPane.showMessageDialog(null, "Data tidak ditemukan.");
        }
    }
} catch (SQLException e) {
    JOptionPane.showMessageDialog(null, "Gagal memperbarui data: " + e.getMessage());
}

    }//GEN-LAST:event_jButton2ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        // TODO add your handling code here:
        // Tombol Delete
try {
    // Memastikan ada baris yang dipilih
    int row = Jtable.getSelectedRow();
    if (row == -1) {
        JOptionPane.showMessageDialog(null, "Pilih data yang ingin dihapus.");
    } else {
        // Mendapatkan nilai nohp dari baris yang dipilih
        String nohp = Jtable.getValueAt(row, 0).toString();

        // Konfirmasi penghapusan
        int confirm = JOptionPane.showConfirmDialog(null, "Apakah Anda yakin ingin menghapus data ini?", "Konfirmasi", JOptionPane.YES_NO_OPTION);
        
        if (confirm == JOptionPane.YES_OPTION) {
            // Query delete
            String sql = "DELETE FROM pelanggan WHERE nohp = ?";
            PreparedStatement stat = conn.prepareStatement(sql);
            stat.setString(1, nohp);
            int rowsDeleted = stat.executeUpdate();

            if (rowsDeleted > 0) {
                JOptionPane.showMessageDialog(null, "Data berhasil dihapus.");
                table(); // refresh tabel
            } else {
                JOptionPane.showMessageDialog(null, "Data tidak ditemukan atau gagal dihapus.");
            }
        }
    }
} catch (SQLException e) {
    JOptionPane.showMessageDialog(null, "Gagal menghapus data: " + e.getMessage());
}

    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        // TODO add your handling code here:
        new menu().show();
        this.dispose();
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        // TODO add your handling code here:
         if (Jtable.getRowCount() == 0) {
        JOptionPane.showMessageDialog(null, "Data tidak ada yang ingin di print.");
        return;
    }

    try {
        // Mencetak tabel dengan header dan footer
        boolean printComplete = Jtable.print(JTable.PrintMode.FIT_WIDTH, 
                new java.text.MessageFormat("Laporan Data Pelanggan"), 
                new java.text.MessageFormat("Page {0}"));
        
        if (printComplete) {
            JOptionPane.showMessageDialog(null, "Cetak berhasil.");
        } else {
            JOptionPane.showMessageDialog(null, "Cetak dibatalkan.");
        }
    } catch (java.awt.print.PrinterException e) {
        JOptionPane.showMessageDialog(null, "Gagal mencetak: " + e.getMessage());
    }
    }//GEN-LAST:event_jButton5ActionPerformed

    private void JtableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_JtableMouseClicked
        // TODO add your handling code here:
        // Mendapatkan baris yang diklik
int row = Jtable.getSelectedRow();

// Memastikan ada baris yang dipilih
if (row != -1) {
    // Mengambil data dari tabel berdasarkan kolom
    String nohp = Jtable.getValueAt(row, 0).toString();
    String nama = Jtable.getValueAt(row, 1).toString();
    String jk = Jtable.getValueAt(row, 2).toString();
    String alamat = Jtable.getValueAt(row, 3).toString();

    // Mengisi form input dengan data dari tabel
    nohpp.setText(nohp);
    nma.setText(nama);
    jkel.setSelectedItem(jk);
    almt.setText(alamat);
}

    }//GEN-LAST:event_JtableMouseClicked

    private void nmaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_nmaKeyPressed
        // TODO add your handling code here:
         if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
    jkel.requestFocus();
}

    }//GEN-LAST:event_nmaKeyPressed

    private void nohppKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_nohppKeyPressed
        // TODO add your handling code here:
         if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
       nma.requestFocus();
         }
    }//GEN-LAST:event_nohppKeyPressed

    private void jkelKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jkelKeyPressed
        // TODO add your handling code here:
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
    almt.requestFocus();
}

    }//GEN-LAST:event_jkelKeyPressed

    /**
     * @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(pelanggan.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(pelanggan.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(pelanggan.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(pelanggan.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 pelanggan().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTable Jtable;
    private javax.swing.JTextField almt;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JComboBox<String> jkel;
    private javax.swing.JTextField nma;
    private javax.swing.JTextField nohpp;
    // End of variables declaration//GEN-END:variables
}
