/*
 * 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 supp extends javax.swing.JFrame {
    private final Connection conn = new Koneksi().connect();

    /**
     * Creates new form pelanggan
     */
    public supp() {
        initComponents();
        tableSupplier();
        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() {
    tidSup.setEnabled(true);
    tnamaSup.setEnabled(true);
    tTlp.setEnabled(true);
    tAlamat.setEnabled(true);

    // Jika ada komponen lain yang perlu diaktifkan, tambahkan di sini
}

    protected void kosong() {
    tidSup.setText("");
    tnamaSup.setText("");
    tTlp.setText("");
    tAlamat.setText("");

    // Jika ada komponen lain yang perlu dikosongkan, tambahkan di sini
}
public void tableSupplier() {
    DefaultTableModel model = new DefaultTableModel();
    model.addColumn("ID Supplier");
    model.addColumn("Nama Supplier");
    model.addColumn("Telepon");
    model.addColumn("Alamat");

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

        while (res.next()) {
            model.addRow(new Object[]{
                res.getString("id_sup"), 
                res.getString("nama_sup"), 
                res.getString("tlp"), 
                res.getString("alamat")
            });
        }

        JtableSupplier.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();
        tidSup = new javax.swing.JTextField();
        tnamaSup = new javax.swing.JTextField();
        tTlp = new javax.swing.JTextField();
        tAlamat = 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();
        JtableSupplier = new javax.swing.JTable();
        jButton5 = new javax.swing.JButton();
        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("Id Supplier");
        getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(24, 100, -1, -1));

        jLabel2.setFont(new java.awt.Font("Times New Roman", 1, 24)); // NOI18N
        jLabel2.setText("Nama Supplier");
        getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(24, 146, -1, -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("Telephone");
        getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(24, 194, 155, -1));

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

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

        tTlp.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                tTlpKeyPressed(evt);
            }
        });
        getContentPane().add(tTlp, new org.netbeans.lib.awtextra.AbsoluteConstraints(203, 200, 279, -1));
        getContentPane().add(tAlamat, 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(660, 199, 97, -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(660, 151, -1, -1));

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

        getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 310, 751, 440));

        jButton5.setFont(new java.awt.Font("Times New Roman", 1, 14)); // NOI18N
        jButton5.setText("CETAK DATA SUPPLIER");
        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, 208, -1));

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

        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 (tidSup.getText().isEmpty() || tnamaSup.getText().isEmpty() || 
        tTlp.getText().isEmpty() || tAlamat.getText().isEmpty()) {
        JOptionPane.showMessageDialog(null, "Silakan lengkapi data.");
    } else {
        String sql = "INSERT INTO supplier (id_sup, nama_sup, tlp, alamat) VALUES (?, ?, ?, ?)";
        PreparedStatement stat = conn.prepareStatement(sql);
        stat.setString(1, tidSup.getText());
        stat.setString(2, tnamaSup.getText());
        stat.setString(3, tTlp.getText());
        stat.setString(4, tAlamat.getText());
        stat.executeUpdate();
        JOptionPane.showMessageDialog(null, "Data Berhasil Disimpan");
        tableSupplier(); // 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:
        try {
    // Validasi input
    if (tidSup.getText().isEmpty() || tnamaSup.getText().isEmpty() || 
        tTlp.getText().isEmpty() || tAlamat.getText().isEmpty()) {
        JOptionPane.showMessageDialog(null, "Silakan lengkapi data.");
    } else {
        String sql = "UPDATE supplier SET nama_sup = ?, tlp = ?, alamat = ? WHERE id_sup = ?";
        PreparedStatement stat = conn.prepareStatement(sql);
        stat.setString(1, tnamaSup.getText());
        stat.setString(2, tTlp.getText());
        stat.setString(3, tAlamat.getText());
        stat.setString(4, tidSup.getText());
        int rowsUpdated = stat.executeUpdate();

        if (rowsUpdated > 0) {
            JOptionPane.showMessageDialog(null, "Data Berhasil Diperbarui");
            tableSupplier(); // 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:
        try {
    // Memastikan ada baris yang dipilih
    int row = JtableSupplier.getSelectedRow();
    if (row == -1) {
        JOptionPane.showMessageDialog(null, "Pilih data yang ingin dihapus.");
    } else {
        // Mendapatkan nilai id_sup dari baris yang dipilih
        String id_sup = JtableSupplier.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 supplier WHERE id_sup = ?";
            PreparedStatement stat = conn.prepareStatement(sql);
            stat.setString(1, id_sup);
            int rowsDeleted = stat.executeUpdate();

            if (rowsDeleted > 0) {
                JOptionPane.showMessageDialog(null, "Data berhasil dihapus.");
                tableSupplier(); // 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 (JtableSupplier.getRowCount() == 0) {
        JOptionPane.showMessageDialog(null, "Data tidak ada yang ingin di print.");
        return;
    }

    try {
        // Mencetak tabel dengan header dan footer
        boolean printComplete = JtableSupplier.print(JTable.PrintMode.FIT_WIDTH, 
                new java.text.MessageFormat("Laporan Data Supplier Terbaru"), 
                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 JtableSupplierMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_JtableSupplierMouseClicked
        // TODO add your handling code here:
        // Mengambil model tabel dari JTable
DefaultTableModel model = (DefaultTableModel) JtableSupplier.getModel();

// Mendapatkan baris yang dipilih
int row = JtableSupplier.getSelectedRow();

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

    // Mengisi form input dengan data dari tabel
    tidSup.setText(nohp);
    tnamaSup.setText(nama);
    tTlp.setText(jk);
    tAlamat.setText(alamat);
}

    }//GEN-LAST:event_JtableSupplierMouseClicked

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

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

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

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

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

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTable JtableSupplier;
    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.JTextField tAlamat;
    private javax.swing.JTextField tTlp;
    private javax.swing.JTextField tidSup;
    private javax.swing.JTextField tnamaSup;
    // End of variables declaration//GEN-END:variables
}
