/*
 * 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.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import koneksi.Koneksi;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.swing.JTable;


/**
 *
 * @author Hp
 */
public class pendapatan extends javax.swing.JFrame {
     private final Connection conn = new Koneksi().connect();

    /**
     * Creates new form pendapatan
     */
    public pendapatan() {
        initComponents();
        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);
    }

    /**
     * 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();
        totalpendapatan = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        tabelpendapatan = new javax.swing.JTable();
        tgll = new com.toedter.calendar.JDateChooser();
        jButton1 = new javax.swing.JButton();
        jLabel2 = 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, 16)); // 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(770, 80, -1, -1));

        totalpendapatan.setFont(new java.awt.Font("Times New Roman", 3, 14)); // NOI18N
        totalpendapatan.setText("HITUNG TOTAL PENDAPATAN");
        totalpendapatan.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                totalpendapatanActionPerformed(evt);
            }
        });
        getContentPane().add(totalpendapatan, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 80, -1, -1));

        tabelpendapatan.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {
                {null, null, null, null, null}
            },
            new String [] {
                "No", "Kode Barang", "Nama Barang", "Total Barang Yang Keluar", "Total Harga"
            }
        ));
        jScrollPane1.setViewportView(tabelpendapatan);

        getContentPane().add(jScrollPane1, new org.netbeans.lib.awtextra.AbsoluteConstraints(40, 110, 843, -1));
        getContentPane().add(tgll, new org.netbeans.lib.awtextra.AbsoluteConstraints(290, 80, 256, -1));

        jButton1.setFont(new java.awt.Font("Times New Roman", 1, 16)); // NOI18N
        jButton1.setText("CETAK");
        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(680, 80, -1, -1));

        jLabel2.setIcon(new javax.swing.ImageIcon(getClass().getResource("/bg/PENDAPATAN-02-02.jpg"))); // NOI18N
        getContentPane().add(jLabel2, new org.netbeans.lib.awtextra.AbsoluteConstraints(0, 0, -1, -1));

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

    private void totalpendapatanActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_totalpendapatanActionPerformed
    // Validasi input tanggal
    if (tgll.getDate() == null) {
        JOptionPane.showMessageDialog(null, "Silahkan masukkan tanggal terlebih dahulu.");
        return;
    }
    
    // Ambil tanggal dari JDateChooser dan format ke dalam string
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    String tanggalInput = sdf.format(tgll.getDate());

    // Query untuk mendapatkan data berdasarkan tanggal
    String sql = "SELECT kd_brg, nama_brg, SUM(qty) AS total_qty, SUM(total) AS total_harga "
               + "FROM penjualan WHERE tanggal = ? GROUP BY kd_brg, nama_brg";
    
    try {
        PreparedStatement stat = conn.prepareStatement(sql);
        stat.setString(1, tanggalInput);
        ResultSet rs = stat.executeQuery();
        
        // Cek apakah ada hasil dari query
        if (!rs.isBeforeFirst()) {
            JOptionPane.showMessageDialog(null, "Pada tanggal ini tidak ada penjualan.");
            return;
        }
        
        // Bersihkan tabel sebelum menambahkan data baru
        DefaultTableModel model = (DefaultTableModel) tabelpendapatan.getModel();
        model.setRowCount(0);
        
        int nomor = 1;
        double totalKeseluruhan = 0.0;
        
        // Menampilkan data di tabel
        while (rs.next()) {
            String kodeBarang = rs.getString("kd_brg");
            String namaBarang = rs.getString("nama_brg");
            int totalQty = rs.getInt("total_qty");
            double totalHarga = rs.getDouble("total_harga");
            
            // Menambahkan baris ke tabel
            Object[] row = {
                nomor++, 
                kodeBarang, 
                namaBarang, 
                totalQty, 
                totalHarga
            };
            model.addRow(row);
            
            // Menambahkan ke total keseluruhan
            totalKeseluruhan += totalHarga;
        }
        
        // Menambahkan baris terakhir untuk total keseluruhan harga
        Object[] totalRow = {"", "", "Total Keseluruhan", "", totalKeseluruhan};
        model.addRow(totalRow);
        
    } catch (SQLException e) {
        JOptionPane.showMessageDialog(null, "Gagal mendapatkan data: " + e.getMessage());
 }
    }//GEN-LAST:event_totalpendapatanActionPerformed

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

    // Ambil tanggal dari JDateChooser dan format menjadi string
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    String selectedDate = sdf.format(tgll.getDate()); // tgll adalah JDateChooser Anda
    
    try {
        // Mencetak tabel dengan header yang menyertakan tanggal
        boolean printComplete = tabelpendapatan.print(JTable.PrintMode.FIT_WIDTH, 
                new java.text.MessageFormat("Laporan Pendapatan Pada Tanggal " + selectedDate), 
                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_jButton1ActionPerformed

    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

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

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton4;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable tabelpendapatan;
    private com.toedter.calendar.JDateChooser tgll;
    private javax.swing.JButton totalpendapatan;
    // End of variables declaration//GEN-END:variables
}
