/*
 * 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.Color;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.awt.print.PageFormat;
import java.awt.print.Paper;
import java.awt.print.Printable;
import static java.awt.print.Printable.PAGE_EXISTS;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;
import java.util.Date;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import koneksi.Koneksi;
import java.sql.Statement;
import java.text.SimpleDateFormat;
import javax.swing.table.DefaultTableModel;
import java.sql.Timestamp;  // Tambahkan ini jika kamu ingin menggunakan Timestamp
import java.text.DecimalFormat;
import javax.swing.AbstractAction;
import javax.swing.InputMap;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.KeyStroke;
import javax.swing.table.DefaultTableModel;



import java.awt.GraphicsDevice;
import java.awt.GraphicsEnvironment;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import javax.swing.JFrame;


/**
 *
 * @author Hp
 */
public class jualan extends javax.swing.JFrame {
    private final Connection conn = new Koneksi().connect();
  //  private javax.swing.JTextField totalsemua;
    private DefaultTableModel modelBelanja;
    private int nomorUrut = 1;
    
     private boolean isFullScreen = false;
    private GraphicsDevice gd;
    
    

    /**
     * Creates new form jualan
     */
    public jualan() {
        // Set JFrame to fullscreen
        
        // Initialize components
        initComponents();
        
        // Setup components
        tengah();
        tabelPenjualan();
        setTanggal();
        
        // Setup txtCari
        setupCariField();
   
        // Initialize model table belanja
        modelBelanja = new DefaultTableModel();
        modelBelanja.addColumn("No");
        modelBelanja.addColumn("Kode Barang");
        modelBelanja.addColumn("Nama Barang");
        modelBelanja.addColumn("Jumlah Barang");
        modelBelanja.addColumn("Harga Barang");
        tabelbelanja.setModel(modelBelanja);
    }

     private void setupCariField() {
        // Asumsikan txtCari sudah diinisialisasi di initComponents()
        txtCari.addKeyListener(new KeyAdapter() {
            @Override
            public void keyReleased(KeyEvent e) {
                filterPenjualan(txtCari.getText());
            }
        });
    }
 
  
  
  

private void filterPenjualan(String query) {
        DefaultTableModel model = (DefaultTableModel) tabelpenjualan.getModel();
        model.setRowCount(0); // Kosongkan tabel sebelum mengisi data baru

        try {
            String sql = "SELECT * FROM penjualan WHERE nohp_pel LIKE ? OR tanggal LIKE ?";
            PreparedStatement pst = conn.prepareStatement(sql);
            pst.setString(1, "%" + query + "%");
            pst.setString(2, "%" + query + "%");
            ResultSet res = pst.executeQuery();

            while (res.next()) {
                model.addRow(new Object[]{
                    res.getDate("tanggal"),
                    res.getString("nohp_pel"),
                    res.getString("nama"),
                    res.getString("kd_brg"),
                    res.getString("nama_brg"),
                    res.getDouble("hrg"),
                    res.getInt("qty"),
                    res.getDouble("total"),
                    res.getDouble("bayar"),
                    res.getDouble("kembali")
                });
            }
            tabelpenjualan.setModel(model);
        } catch (SQLException e) {
            JOptionPane.showMessageDialog(null, "Error: " + e.getMessage());
        }
    }
    
    
    
    
    public void tengah()
    {
        Dimension dimmax = Toolkit.getDefaultToolkit().getScreenSize();
        Dimension dimframe=this.getSize();
        this.setLocation((dimmax.width-dimframe.width)/2,
                        (dimmax.height-dimframe.height)/2);
    }
    
    // Mengaktifkan field input pada form
  // Mengaktifkan field input pada form
protected void aktif() {
    // Field yang aktif
    nohp_pelanggan.setEnabled(true);
    kodebarang.setEnabled(true);
    jmlhbrg.setEnabled(true);
    uang.setEnabled(true);

    // Field yang tidak aktif (nonaktif)
    tgl.setEnabled(false); // Tanggal tidak dapat diedit
    namapelanggan.setEnabled(false); // Nama pelanggan tidak dapat diedit
    namabarang.setEnabled(false); // Nama barang tidak dapat diedit
    harga.setEnabled(false); // Harga tidak dapat diedit
    totalbelanja.setEnabled(false); // Total belanja tidak dapat diedit
    kembali.setEnabled(false); // Kembali tidak dapat diedit
}

// Mengosongkan field input pada form
protected void kosong() {
    nohp_pelanggan.setText("");
    namapelanggan.setText("");
    kodebarang.setText("");
    namabarang.setText("");
    harga.setText("");
    jmlhbrg.setText("");
    totalbelanja.setText("");
    uang.setText("");
    kembali.setText("");

    // Tetapkan ulang tanggal saat ini ke field tgl
    setTanggal();
}


    private void setTanggal() {
        SimpleDateFormat formatTanggal = new SimpleDateFormat("yyyy-MM-dd");
        Date tanggalSekarang = new Date();
        tgl.setText(formatTanggal.format(tanggalSekarang)); // Mengatur text field dengan tanggal saat ini
        tgl.setEnabled(false);
    }

    public void tabelPenjualan() {
        DefaultTableModel model = new DefaultTableModel();
        model.addColumn("Tanggal");
        model.addColumn("No HP Pelanggan");
        model.addColumn("Nama Pelanggan");
        model.addColumn("Kode Barang");
        model.addColumn("Nama Barang");
        model.addColumn("Harga");
        model.addColumn("Jumlah Barang");
        model.addColumn("Total Belanja");
        model.addColumn("Uang");
        model.addColumn("Kembali");

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

            while (res.next()) {
                model.addRow(new Object[]{
                    res.getDate("tanggal"),
                    res.getString("nohp_pel"),
                    res.getString("nama"),
                    res.getString("kd_brg"),
                    res.getString("nama_brg"),
                    res.getDouble("hrg"),
                    res.getInt("qty"),
                    res.getDouble("total"),
                    res.getDouble("bayar"),
                    res.getDouble("kembali")
                });
            }

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



// Fungsi untuk menghitung total belanja
private void hitungBelanja() {
    // Validasi input
    if (jmlhbrg.getText().trim().isEmpty() || harga.getText().trim().isEmpty()) {
        JOptionPane.showMessageDialog(null, "Lengkapi data sebelum menghitung total belanja.");
        return;
    }

    try {
        // Menghitung total belanja
        double hargaBarang = Double.parseDouble(harga.getText().replace(",", "."));
        int jumlahBarang = Integer.parseInt(jmlhbrg.getText());
        double totalBelanja = hargaBarang * jumlahBarang;

        // Menampilkan total belanja
        totalbelanja.setText(String.format("%.2f", totalBelanja));
    } catch (NumberFormatException e) {
        JOptionPane.showMessageDialog(null, "Format angka tidak valid: " + e.getMessage());
    }
}

// Fungsi untuk memasukkan belanjaan ke tabel belanja
private void masukkanKeTabel() {
    // Validasi input
    if (kodebarang.getText().trim().isEmpty() || namabarang.getText().trim().isEmpty() ||
        harga.getText().trim().isEmpty() || jmlhbrg.getText().trim().isEmpty()) {
        JOptionPane.showMessageDialog(null, "Lengkapi data sebelum memasukkan ke tabel belanja.");
        return;
    }

    try {
        double hargaBarang = Double.parseDouble(harga.getText().replace(",", "."));
        int jumlahBarang = Integer.parseInt(jmlhbrg.getText());
        
        modelBelanja.addRow(new Object[]{
            nomorUrut++,  // Menampilkan nomor urut
            kodebarang.getText(),
            namabarang.getText(),
            jumlahBarang,
            hargaBarang
        });

        // Mengosongkan field setelah memasukkan data
        kodebarang.setText("");
        namabarang.setText("");
        harga.setText("");
        jmlhbrg.setText("");
        totalbelanja.setText("");
    } catch (NumberFormatException e) {
        JOptionPane.showMessageDialog(null, "Format angka tidak valid: " + e.getMessage());
    }
}


// Fungsi untuk menghitung total semua belanjaan
private void totalSemuaBelanja() {
    double totalSemua = 0.0;
    for (int i = 0; i < modelBelanja.getRowCount(); i++) {
        totalSemua += (double) modelBelanja.getValueAt(i, 4) * (int) modelBelanja.getValueAt(i, 3); // Kolom harga * jumlah
    }
    totalbelanja.setText(String.format("%.2f", totalSemua));
}


  private void bayarBelanja() {
    // Periksa apakah tabel belanja kosong
    DefaultTableModel model = (DefaultTableModel) tabelbelanja.getModel();
    if (model.getRowCount() == 0) {
        JOptionPane.showMessageDialog(null, "Anda tidak belanja apapun.");
        return;
    }

    // Validasi input
    try {
        // Ambil dan validasi input total belanja dan uang bayar
        String totalBelanjaText = totalbelanja.getText().replace(",", ".");
        String uangBayarText = uang.getText().replace(",", ".");

        if (totalBelanjaText.isEmpty() || uangBayarText.isEmpty()) {
            JOptionPane.showMessageDialog(null, "Total belanja atau uang bayar tidak boleh kosong.");
            return;
        }

        double totalBelanja;
        double uangBayar;

        try {
            totalBelanja = Double.parseDouble(totalBelanjaText);
            uangBayar = Double.parseDouble(uangBayarText);
        } catch (NumberFormatException e) {
            JOptionPane.showMessageDialog(null, "Format angka tidak valid: " + e.getMessage());
            return;
        }

        if (uangBayar < totalBelanja) {
            JOptionPane.showMessageDialog(null, "Uang kurang, silahkan cukupi uang terlebih dahulu.");
            return;
        }

        double kembalian = uangBayar - totalBelanja;
        kembali.setText(String.format("%.2f", kembalian));

        // Ambil tanggal hari ini
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String tanggalTransaksi = sdf.format(new Date());

        // Menyimpan data belanjaan ke database
        String sqlInsert = "INSERT INTO penjualan (tanggal, nohp_pel, nama, kd_brg, nama_brg, hrg, qty, total, bayar, kembali) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
        PreparedStatement stat = conn.prepareStatement(sqlInsert);

        // Query untuk mengupdate stok barang dan tanggal transaksi
        String sqlUpdateStok = "UPDATE barang SET stok = stok - ?, tgl = ? WHERE kd_brg = ?";
        String sqlCheckStok = "SELECT stok FROM barang WHERE kd_brg = ?";

        // Start transaction
        conn.setAutoCommit(false); // Disable auto-commit

        try {
            for (int i = 0; i < model.getRowCount(); i++) {
                String kodeBarang = model.getValueAt(i, 1).toString();
                String namaBarang = model.getValueAt(i, 2).toString();
                String jumlahBarangText = model.getValueAt(i, 3).toString();
                String hargaBarangText = model.getValueAt(i, 4).toString();

                if (jumlahBarangText.isEmpty() || hargaBarangText.isEmpty()) {
                    JOptionPane.showMessageDialog(null, "Jumlah atau harga barang tidak boleh kosong.");
                    conn.rollback(); // Rollback transaksi jika input kosong
                    return;
                }

                int jumlahBarang;
                double hargaBarang;

                try {
                    jumlahBarang = Integer.parseInt(jumlahBarangText);
                    hargaBarang = Double.parseDouble(hargaBarangText);
                } catch (NumberFormatException e) {
                    JOptionPane.showMessageDialog(null, "Format angka tidak valid: " + e.getMessage());
                    conn.rollback();
                    return;
                }

                // Periksa stok barang
                PreparedStatement checkStok = conn.prepareStatement(sqlCheckStok);
                checkStok.setString(1, kodeBarang);
                ResultSet rs = checkStok.executeQuery();

                if (rs.next()) {
                    int stokTersedia = rs.getInt("stok");

                    if (stokTersedia < jumlahBarang) {
                        JOptionPane.showMessageDialog(null, "Stok untuk barang " + namaBarang + " kurang. Stok tersedia: " + stokTersedia);
                        conn.rollback(); // Rollback transaksi jika stok tidak mencukupi
                        return;
                    }
                }

                // Simpan data penjualan
                stat.setString(1, tgl.getText());
                stat.setString(2, nohp_pelanggan.getText());
                stat.setString(3, namapelanggan.getText());
                stat.setString(4, kodeBarang);
                stat.setString(5, namaBarang);
                stat.setDouble(6, hargaBarang);
                stat.setInt(7, jumlahBarang);
                stat.setDouble(8, totalBelanja);
                stat.setDouble(9, uangBayar);
                stat.setDouble(10, kembalian);

                stat.addBatch(); // Menambahkan batch query

                // Update stok barang dan tanggal transaksi
                PreparedStatement updateStok = conn.prepareStatement(sqlUpdateStok);
                updateStok.setInt(1, jumlahBarang); // Mengurangi stok dengan jumlah barang yang dibeli
                updateStok.setString(2, tanggalTransaksi); // Update tanggal transaksi
                updateStok.setString(3, kodeBarang); // Berdasarkan kode barang
                updateStok.executeUpdate(); // Eksekusi update stok
            }

            stat.executeBatch(); // Eksekusi batch query
            conn.commit(); // Commit transaksi
            JOptionPane.showMessageDialog(null, "PEMBAYARAN BERHASIL!!!");

            // Mengosongkan tabel belanja setelah pembayaran berhasil
            model.setRowCount(0);

            // Konfirmasi cetak nota
            int printOption = JOptionPane.showConfirmDialog(null, "Apakah Anda ingin mencetak nota?", "Cetak Nota", JOptionPane.YES_NO_OPTION);
            if (printOption == JOptionPane.YES_OPTION) {
                // Format nota yang ingin dicetak
                String nota = formatNota();
                printNota(nota); // Panggil metode untuk mencetak nota
            }

        } catch (SQLException e) {
            conn.rollback(); // Rollback transaksi jika terjadi error
            JOptionPane.showMessageDialog(null, "Gagal menyimpan data: " + e.getMessage());
        } finally {
            conn.setAutoCommit(true); // Enable auto-commit
        }

        // Mengosongkan form setelah menyimpan
        kosong();
        tabelPenjualan();
        aktif();

    } catch (NumberFormatException e) {
        JOptionPane.showMessageDialog(null, "Format angka tidak valid: " + e.getMessage());
    } catch (SQLException e) {
        JOptionPane.showMessageDialog(null, "Gagal menyimpan data: " + e.getMessage());
    }
}

// Method to format nota
private String formatNota() {
    StringBuilder nota = new StringBuilder();
    nota.append("Toko Baju\n");
    nota.append("------------------------------\n");
    nota.append("Tanggal: ").append(new SimpleDateFormat("yyyy-MM-dd").format(new Date())).append("\n");
    nota.append("No HP: ").append(nohp_pelanggan.getText()).append("\n");
    nota.append("Nama: ").append(namapelanggan.getText()).append("\n");
    nota.append("------------------------------\n");

    DefaultTableModel model = (DefaultTableModel) tabelbelanja.getModel();
    for (int i = 0; i < model.getRowCount(); i++) {
        String kodeBarang = model.getValueAt(i, 1).toString();
        String namaBarang = model.getValueAt(i, 2).toString();
        String jumlahBarang = model.getValueAt(i, 3).toString();
        String hargaBarang = model.getValueAt(i, 4).toString();
        nota.append(String.format("%s %s x%s @%s\n", kodeBarang, namaBarang, jumlahBarang, hargaBarang));
    }

    nota.append("------------------------------\n");
    nota.append("Total: ").append(totalbelanja.getText()).append("\n");
    nota.append("Bayar: ").append(uang.getText()).append("\n");
    nota.append("Kembali: ").append(kembali.getText()).append("\n");
    nota.append("------------------------------\n");
    nota.append("Terima Kasih\n");

    return nota.toString();
}

// Method to print nota
private void printNota(String nota) {
    try {
        PrinterJob printerJob = PrinterJob.getPrinterJob();
        PageFormat pageFormat = printerJob.defaultPage();
        Paper paper = pageFormat.getPaper();

        // Set paper size to 100mm x (dynamic height based on content)
        double width = 100 / 25.4 * 72; // 100 mm to points
        double height = calculatePrintableHeight(nota);
        paper.setSize(width, height);
        paper.setImageableArea(0, 0, width, height);
        pageFormat.setPaper(paper);

        printerJob.setPrintable(new Printable() {
            @Override
            public int print(Graphics g, PageFormat format, int pageIndex) throws PrinterException {
                if (pageIndex > 0) {
                    return NO_SUCH_PAGE;
                }

                Graphics2D g2d = (Graphics2D) g;
                g2d.translate(format.getImageableX(), format.getImageableY());

                // Set font size and style
                g2d.setFont(new Font("Monospaced", Font.PLAIN, 10));
                FontMetrics metrics = g2d.getFontMetrics();
                int lineHeight = metrics.getHeight();
                int y = lineHeight;

                // Print the nota text
                String[] lines = nota.split("\n");
                for (String line : lines) {
                    g2d.drawString(line, 0, y);
                    y += lineHeight;
                }

                return PAGE_EXISTS;
            }
        });

        if (printerJob.printDialog()) {
            printerJob.print();
        }

    } catch (PrinterException e) {
        JOptionPane.showMessageDialog(null, "Gagal mencetak nota: " + e.getMessage());
    }
}

// Method to calculate printable height based on nota content
private double calculatePrintableHeight(String nota) {
    FontMetrics metrics = new FontMetrics(new Font("Monospaced", Font.PLAIN, 10)) {};
    int lineHeight = metrics.getHeight();
    int lines = nota.split("\n").length;
    return lineHeight * lines;
}




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

        jButton4 = new javax.swing.JButton();
        nohp_pelanggan = new javax.swing.JTextField();
        namapelanggan = new javax.swing.JTextField();
        kodebarang = new javax.swing.JTextField();
        namabarang = new javax.swing.JTextField();
        harga = new javax.swing.JTextField();
        jmlhbrg = new javax.swing.JTextField();
        uang = new javax.swing.JTextField();
        kembali = new javax.swing.JTextField();
        carinohppelanggan = new javax.swing.JButton();
        carikodebarang = new javax.swing.JButton();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel9 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();
        hitungbelanja = new javax.swing.JButton();
        jLabel10 = new javax.swing.JLabel();
        jLabel11 = new javax.swing.JLabel();
        bayarbelanja = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabelpenjualan = new javax.swing.JTable();
        tgl = new javax.swing.JTextField();
        jScrollPane2 = new javax.swing.JScrollPane();
        tabelbelanja = new javax.swing.JTable();
        jLabel13 = new javax.swing.JLabel();
        totalbelanja = new javax.swing.JTextField();
        totalsemuabelanja = new javax.swing.JButton();
        txtCari = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();

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

        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(1380, 350, 109, -1));

        nohp_pelanggan.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                nohp_pelangganActionPerformed(evt);
            }
        });
        nohp_pelanggan.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                nohp_pelangganKeyPressed(evt);
            }
        });
        getContentPane().add(nohp_pelanggan, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 170, 270, 30));

        namapelanggan.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                namapelangganActionPerformed(evt);
            }
        });
        namapelanggan.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                namapelangganKeyPressed(evt);
            }
        });
        getContentPane().add(namapelanggan, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 210, 270, 30));

        kodebarang.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                kodebarangActionPerformed(evt);
            }
        });
        kodebarang.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                kodebarangKeyPressed(evt);
            }
        });
        getContentPane().add(kodebarang, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 250, 270, 30));

        namabarang.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                namabarangActionPerformed(evt);
            }
        });
        getContentPane().add(namabarang, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 300, 270, 30));

        harga.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                hargaActionPerformed(evt);
            }
        });
        getContentPane().add(harga, new org.netbeans.lib.awtextra.AbsoluteConstraints(750, 130, 243, 30));

        jmlhbrg.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jmlhbrgActionPerformed(evt);
            }
        });
        jmlhbrg.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jmlhbrgKeyPressed(evt);
            }
        });
        getContentPane().add(jmlhbrg, new org.netbeans.lib.awtextra.AbsoluteConstraints(750, 170, 243, 30));

        uang.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                uangActionPerformed(evt);
            }
        });
        uang.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                uangKeyPressed(evt);
            }
        });
        getContentPane().add(uang, new org.netbeans.lib.awtextra.AbsoluteConstraints(750, 270, 243, 30));

        kembali.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                kembaliActionPerformed(evt);
            }
        });
        getContentPane().add(kembali, new org.netbeans.lib.awtextra.AbsoluteConstraints(750, 310, 244, 30));

        carinohppelanggan.setText("CARI");
        carinohppelanggan.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                carinohppelangganActionPerformed(evt);
            }
        });
        getContentPane().add(carinohppelanggan, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 170, -1, -1));

        carikodebarang.setText("CARI");
        carikodebarang.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                carikodebarangActionPerformed(evt);
            }
        });
        getContentPane().add(carikodebarang, new org.netbeans.lib.awtextra.AbsoluteConstraints(480, 260, -1, -1));

        jLabel2.setFont(new java.awt.Font("Times New Roman", 1, 16)); // NOI18N
        jLabel2.setText("TANGGAL");
        getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 130, -1, -1));

        jLabel3.setFont(new java.awt.Font("Times New Roman", 1, 16)); // NOI18N
        jLabel3.setText("NOMOR HP");
        getContentPane().add(jLabel3, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 170, -1, -1));

        jLabel4.setFont(new java.awt.Font("Times New Roman", 1, 16)); // NOI18N
        jLabel4.setText("NAMA PELANGGAN");
        getContentPane().add(jLabel4, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 220, -1, -1));

        jLabel5.setFont(new java.awt.Font("Times New Roman", 1, 16)); // NOI18N
        jLabel5.setText("KODE BARANG");
        getContentPane().add(jLabel5, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 260, -1, -1));

        jLabel6.setFont(new java.awt.Font("Times New Roman", 1, 16)); // NOI18N
        jLabel6.setText("CARI DATA");
        getContentPane().add(jLabel6, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 380, -1, -1));

        jLabel9.setFont(new java.awt.Font("Times New Roman", 1, 16)); // NOI18N
        jLabel9.setText("NAMA BARANG");
        getContentPane().add(jLabel9, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 310, -1, -1));

        jLabel7.setFont(new java.awt.Font("Times New Roman", 1, 16)); // NOI18N
        jLabel7.setText("HARGA BARANG");
        getContentPane().add(jLabel7, new org.netbeans.lib.awtextra.AbsoluteConstraints(580, 130, -1, -1));

        jLabel8.setFont(new java.awt.Font("Times New Roman", 1, 16)); // NOI18N
        jLabel8.setText("JUMLAH BARANG");
        getContentPane().add(jLabel8, new org.netbeans.lib.awtextra.AbsoluteConstraints(570, 180, -1, -1));

        hitungbelanja.setText("MASUKAN");
        hitungbelanja.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                hitungbelanjaActionPerformed(evt);
            }
        });
        getContentPane().add(hitungbelanja, new org.netbeans.lib.awtextra.AbsoluteConstraints(1000, 180, -1, -1));

        jLabel10.setFont(new java.awt.Font("Times New Roman", 1, 16)); // NOI18N
        jLabel10.setText("MASUKAN UANG");
        getContentPane().add(jLabel10, new org.netbeans.lib.awtextra.AbsoluteConstraints(570, 270, -1, -1));

        jLabel11.setFont(new java.awt.Font("Times New Roman", 1, 16)); // NOI18N
        jLabel11.setText("KEMBALIAN");
        getContentPane().add(jLabel11, new org.netbeans.lib.awtextra.AbsoluteConstraints(570, 320, -1, -1));

        bayarbelanja.setText("BAYAR");
        bayarbelanja.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bayarbelanjaActionPerformed(evt);
            }
        });
        bayarbelanja.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                bayarbelanjaKeyPressed(evt);
            }
        });
        getContentPane().add(bayarbelanja, new org.netbeans.lib.awtextra.AbsoluteConstraints(1000, 270, -1, -1));

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

        getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(10, 410, 1480, 480));

        tgl.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                tglActionPerformed(evt);
            }
        });
        getContentPane().add(tgl, new org.netbeans.lib.awtextra.AbsoluteConstraints(210, 130, 270, 30));

        tabelbelanja.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"
            }
        ));
        jScrollPane2.setViewportView(tabelbelanja);

        getContentPane().add(jScrollPane2, new org.netbeans.lib.awtextra.AbsoluteConstraints(1100, 120, 390, 204));

        jLabel13.setFont(new java.awt.Font("Times New Roman", 1, 16)); // NOI18N
        jLabel13.setText("TOTAL SEMUA");
        getContentPane().add(jLabel13, new org.netbeans.lib.awtextra.AbsoluteConstraints(570, 230, -1, -1));

        totalbelanja.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                totalbelanjaActionPerformed(evt);
            }
        });
        totalbelanja.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                totalbelanjaKeyPressed(evt);
            }
        });
        getContentPane().add(totalbelanja, new org.netbeans.lib.awtextra.AbsoluteConstraints(750, 220, 243, 30));

        totalsemuabelanja.setText("TOTAL");
        totalsemuabelanja.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                totalsemuabelanjaActionPerformed(evt);
            }
        });
        getContentPane().add(totalsemuabelanja, new org.netbeans.lib.awtextra.AbsoluteConstraints(1000, 220, -1, -1));
        getContentPane().add(txtCari, new org.netbeans.lib.awtextra.AbsoluteConstraints(120, 370, 220, 30));

        jLabel1.setIcon(new javax.swing.ImageIcon(getClass().getResource("/bg/KASIR-01-01.jpg"))); // NOI18N
        getContentPane().add(jLabel1, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, 1500, 910));

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

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

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

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

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

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

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

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

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

    private void carinohppelangganActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_carinohppelangganActionPerformed
        // TODO add your handling code here:
        String nohp = nohp_pelanggan.getText();

    if (nohp.isEmpty()) {
        JOptionPane.showMessageDialog(null, "Masukkan nomor HP pelanggan.");
        return;
    }

    try {
        String sql = "SELECT nama FROM pelanggan WHERE nohp = ?";
        PreparedStatement stat = conn.prepareStatement(sql);
        stat.setString(1, nohp);
        ResultSet res = stat.executeQuery();

        if (res.next()) {
            String namaPelanggan = res.getString("nama");
            namapelanggan.setText(namaPelanggan);
            JOptionPane.showMessageDialog(null, "Nama pelanggan ditemukan. Silakan lanjutkan penginputan data.");
            nohp_pelanggan.setEnabled(false); // Menonaktifkan field
            namapelanggan.setEnabled(false);
            carinohppelanggan.setEnabled(false); // Menonaktifkan tombol pencarian
        } else {
            JOptionPane.showMessageDialog(null, "Pelanggan tidak ditemukan.");
            namapelanggan.setText("");
        }
    } catch (SQLException e) {
        JOptionPane.showMessageDialog(null, "Error: " + e.getMessage());
    }
    }//GEN-LAST:event_carinohppelangganActionPerformed

    private void carikodebarangActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_carikodebarangActionPerformed
        // TODO add your handling code here:
        
         String kodeBarang = kodebarang.getText();

    if (kodeBarang.isEmpty()) {
        JOptionPane.showMessageDialog(null, "Silakan masukkan kode barang.");
        return;
    }

    try {
        String sql = "SELECT nm_brg, hrg FROM barang WHERE kd_brg = ?";
        PreparedStatement stat = conn.prepareStatement(sql);
        stat.setString(1, kodeBarang);
        ResultSet res = stat.executeQuery();

        if (res.next()) {
            String namaBarang = res.getString("nm_brg");
            double hargaBarang = res.getDouble("hrg");

            namabarang.setText(namaBarang);
            harga.setText(String.valueOf(hargaBarang));

            // Menonaktifkan field setelah berhasil menemukan barang
            kodebarang.setEnabled(false);
            namabarang.setEnabled(false);
            harga.setEnabled(false);

            JOptionPane.showMessageDialog(null, "Kode barang ditemukan. Silakan lanjutkan penginputan.");
        } else {
            JOptionPane.showMessageDialog(null, "Kode barang tidak ditemukan.");
            namabarang.setText("");
            harga.setText("");
        }
    } catch (SQLException e) {
        JOptionPane.showMessageDialog(null, "Error: " + e.getMessage());
    }
    }//GEN-LAST:event_carikodebarangActionPerformed

    private void hitungbelanjaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_hitungbelanjaActionPerformed
        // TODO add your handling code here:
        masukkanKeTabel();
        hitungBelanja();
        totalSemuaBelanja();
        aktifkanFieldTertentu();

    }//GEN-LAST:event_hitungbelanjaActionPerformed

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

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

    private void nohp_pelangganKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_nohp_pelangganKeyPressed
        // TODO add your handling code here:
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
        carinohppelangganActionPerformed(null); // Panggil metode yang sesuai
        kodebarang.requestFocus();
    }
    }//GEN-LAST:event_nohp_pelangganKeyPressed

    private void namapelangganKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_namapelangganKeyPressed
        // TODO add your handling code here:
        
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
        kodebarang.requestFocus(); // Pindahkan fokus ke field jmlhbrg
    }
        
    }//GEN-LAST:event_namapelangganKeyPressed

    private void kodebarangKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_kodebarangKeyPressed
        // TODO add your handling code here:
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
        // Panggil metode carikodebarangActionPerformed() saat Enter ditekan
        carikodebarangActionPerformed(null);
         jmlhbrg.requestFocus();
    }
        
    }//GEN-LAST:event_kodebarangKeyPressed

    private void jmlhbrgKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jmlhbrgKeyPressed
        // TODO add your handling code here:
         if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
             
        // Panggil metode hitungBelanja() saat Enter ditekan
        masukkanKeTabel();
        totalSemuaBelanja();
        totalbelanja.setEnabled(false);
        nohp_pelanggan.requestFocus();
         aktifkanFieldTertentu();
    }
    }//GEN-LAST:event_jmlhbrgKeyPressed
private void aktifkanFieldTertentu() {
    // Mengaktifkan field yang diperlukan
    nohp_pelanggan.setEnabled(true);
    kodebarang.setEnabled(true);
    namabarang.setEnabled(true);
    jmlhbrg.setEnabled(true);
    harga.setEnabled(true);
}
    private void uangKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_uangKeyPressed
        // TODO add your handling code here:
        if (evt.getKeyCode() == KeyEvent.VK_ENTER) {
        // Panggil metode bayarBelanja() saat Enter ditekan
        bayarBelanja();
    }
    }//GEN-LAST:event_uangKeyPressed

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

    private void totalbelanjaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_totalbelanjaKeyPressed
        // TODO add your handling code here:
    }//GEN-LAST:event_totalbelanjaKeyPressed

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

    private void bayarbelanjaKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_bayarbelanjaKeyPressed
        // TODO add your handling code here:
        
    }//GEN-LAST:event_bayarbelanjaKeyPressed

    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 tabelpenjualanMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_tabelpenjualanMouseClicked
   

    }//GEN-LAST:event_tabelpenjualanMouseClicked
// Event listener yang sudah ada untuk tombol idrandom


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

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bayarbelanja;
    private javax.swing.JButton carikodebarang;
    private javax.swing.JButton carinohppelanggan;
    private javax.swing.JTextField harga;
    private javax.swing.JButton hitungbelanja;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel13;
    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.JLabel jLabel9;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JTextField jmlhbrg;
    private javax.swing.JTextField kembali;
    private javax.swing.JTextField kodebarang;
    private javax.swing.JTextField namabarang;
    private javax.swing.JTextField namapelanggan;
    private javax.swing.JTextField nohp_pelanggan;
    private javax.swing.JTable tabelbelanja;
    private javax.swing.JTable tabelpenjualan;
    private javax.swing.JTextField tgl;
    private javax.swing.JTextField totalbelanja;
    private javax.swing.JButton totalsemuabelanja;
    private javax.swing.JTextField txtCari;
    private javax.swing.JTextField uang;
    // End of variables declaration//GEN-END:variables
}
