/*
 * 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.awt.Color;
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 NewSale extends javax.swing.JFrame {

    /**
     * Creates new form NewSale
     */
    public NewSale() {
        setTitle("New Sale");

        initComponents();
        updateTable();
        LoginForm lf = new LoginForm();
        mId.setVisible(false);
        mPrice.setEnabled(false);
        sellBtn.setEnabled(false);
        mName.setEnabled(false);
        buyFld.setEnabled(false);
        mTotalBill.setEnabled(false);
        idLbl.setVisible(false);
        currentStock.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();
        mName = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        buyFld = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        mPrice = new javax.swing.JTextField();
        jLabel4 = new javax.swing.JLabel();
        mTotalBill = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        medicineTable = new javax.swing.JTable();
        clearBtn = new javax.swing.JButton();
        sellBtn = new javax.swing.JButton();
        backBtn = new javax.swing.JButton();
        jLabel6 = new javax.swing.JLabel();
        idLbl = new javax.swing.JLabel();
        mId = new javax.swing.JTextField();
        currentStock = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText(" Name");

        jLabel2.setText("Quantity");

        jLabel3.setText("Price");

        jLabel4.setText("Total Bill");

        mTotalBill.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        mTotalBill.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                mTotalBillActionPerformed(evt);
            }
        });

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

            },
            new String [] {
                "Id", "Medicine Name", "Type", "Price", "Quantity"
            }
        ));
        medicineTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                medicineTableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(medicineTable);

        clearBtn.setText("Clear");
        clearBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clearBtnActionPerformed(evt);
            }
        });

        sellBtn.setText("Sell ");
        sellBtn.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                sellBtnActionPerformed(evt);
            }
        });

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

        jLabel6.setFont(new java.awt.Font("Tahoma", 1, 18)); // NOI18N
        jLabel6.setText("                                           Sell Medicine");

        idLbl.setText("Id");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(backBtn))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(54, 54, 54)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(clearBtn)
                                .addGap(164, 164, 164)
                                .addComponent(sellBtn))
                            .addGroup(layout.createSequentialGroup()
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(jLabel1)
                                    .addComponent(idLbl)
                                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 71, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(jLabel3)
                                    .addComponent(jLabel4))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                    .addComponent(mTotalBill, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(mPrice, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(buyFld, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addComponent(mName, javax.swing.GroupLayout.PREFERRED_SIZE, 183, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGroup(layout.createSequentialGroup()
                                        .addComponent(mId, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addGap(18, 18, 18)
                                        .addComponent(currentStock, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)))))))
                .addGap(18, 18, 18)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 626, Short.MAX_VALUE))
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 495, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(183, 183, 183))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel6, javax.swing.GroupLayout.PREFERRED_SIZE, 59, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(10, 10, 10)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 440, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addContainerGap(22, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(3, 3, 3)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(idLbl)
                            .addComponent(mId, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(currentStock, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel1)
                            .addComponent(mName, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel2)
                            .addComponent(buyFld, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 20, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(mPrice, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(18, 18, 18)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jLabel4)
                            .addComponent(mTotalBill, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(30, 30, 30)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(clearBtn)
                            .addComponent(sellBtn))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                        .addComponent(backBtn)
                        .addGap(35, 35, 35))))
        );

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

    private void mTotalBillActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_mTotalBillActionPerformed

    }//GEN-LAST:event_mTotalBillActionPerformed

    private void medicineTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_medicineTableMouseClicked

        int i = medicineTable.getSelectedRow();

        DefaultTableModel model = (DefaultTableModel) medicineTable.getModel();
        mId.setText(model.getValueAt(i, 0).toString());
        mName.setText(model.getValueAt(i, 1).toString());
        currentStock.setText(model.getValueAt(i, 6).toString());
        mPrice.setText(model.getValueAt(i, 4).toString());
        mTotalBill.setText(Integer.toString(TotalBill));
        buyFld.setEnabled(true);
        sellBtn.setEnabled(true);
        stock = Integer.parseInt(currentStock.getText().toString());

    }//GEN-LAST:event_medicineTableMouseClicked

    private void clearBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearBtnActionPerformed

        clear();
    }//GEN-LAST:event_clearBtnActionPerformed

    private void backBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_backBtnActionPerformed

        if (GlobalConstant.userType == 1)
        {
            dispose();
            admin();
        } 
        else 
        {   
            dispose();
            user();
        }


    }//GEN-LAST:event_backBtnActionPerformed

    private void sellBtnActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sellBtnActionPerformed

        Medicines medicine = new Medicines();

        NewSale ns = new NewSale();
        Connection con;
        PreparedStatement ps;

        try 
        {
            buy = Integer.parseInt(buyFld.getText().toString());

        } 
        catch (Exception x) 
        {
            JOptionPane.showMessageDialog(null, "Quantity Empty");
            ns.updateTable();
        }

        System.out.println("Buy:" + buy);
        int up = stock - buy;
        String sql = "UPDATE medicines SET current_stock='" + up + "'WHERE id='" + mId.getText() + "'";
        
        if (stock < buy) 
        {
            JOptionPane.showMessageDialog(null, "Medicine Out Of Stock");
        } 
        else 
        {

            try 
            {

                con = DriverManager.getConnection("jdbc:mysql://localhost/medical_store", "root", "");
                ps = con.prepareStatement(sql);
                int save = ps.executeUpdate();

                System.out.println("executeQuery");

                if (save > 0) {
                    System.out.println("Inserted");
                    ns.updateTable();
                    medicine.updateTable();
                    ns.setVisible(true);
                    dispose();
                    SellsRecord();

                } else {
                    System.out.println("Not Inserted");
                    JOptionPane.showMessageDialog(null, "Not saved");

                }

            } 
            catch (SQLException ex) 
            {
                JOptionPane.showMessageDialog(null, "Insert Valid Data");
                dispose();
            }
        }


    }//GEN-LAST:event_sellBtnActionPerformed

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

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton backBtn;
    private javax.swing.JTextField buyFld;
    private javax.swing.JButton clearBtn;
    private javax.swing.JTextField currentStock;
    private javax.swing.JLabel idLbl;
    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 mId;
    private javax.swing.JTextField mName;
    private javax.swing.JTextField mPrice;
    private javax.swing.JTextField mTotalBill;
    private javax.swing.JTable medicineTable;
    private javax.swing.JButton sellBtn;
    // End of variables declaration//GEN-END:variables
    public int Price, Quantity, TotalBill;
    public int stock;
    int userType;
    String name;
    int buy;

    public void updateTable() 
    {
        Connection con;
        PreparedStatement ps;
        try 
        {
            con = DriverManager.getConnection("jdbc:mysql://localhost/medical_store", "root", "root");
            ps = con.prepareStatement("SELECT * FROM medicines");

            ResultSet rs = ps.executeQuery();
            medicineTable.setModel(DbUtils.resultSetToTableModel(rs));

        } 
        catch (SQLException ex)
        {

            Logger.getLogger(LoginForm.class.getName()).log(Level.SEVERE, null, ex);

        }
    }

    public void clear() {
        mId.setText("");
        mName.setText("");
        mPrice.setText("");
        buyFld.setText("");
        mTotalBill.setText("");
    }

    public void SellsRecord() {

        NewSale ns = new NewSale();
        Connection con;
        PreparedStatement ps;
        
        try 
        {
            String sql = "INSERT INTO sellsRecord (mediId,name,quantity,price,totalBill)" + " VALUES (?,?,?,?,?)";

            con = DriverManager.getConnection("jdbc:mysql://localhost/medical_store", "root", "root");

            Price = Integer.parseInt(mPrice.getText().toString());

            Quantity = Integer.parseInt(buyFld.getText().toString());
            System.out.println("Quantity:" + Quantity);
            TotalBill = Price * Quantity;
            System.out.println("total" + TotalBill);
            mTotalBill.setText(Integer.toString(TotalBill));
            System.out.println("TotalBill:" + mTotalBill);

            ps = con.prepareStatement(sql);
            ps.setString(1, mId.getText());
            ps.setString(2, mName.getText());
            ps.setString(4, mPrice.getText());
            ps.setString(3, buyFld.getText());
            ps.setString(5, mTotalBill.getText());

            ///////////////Price Count///////////////////////////////
            int save = ps.executeUpdate();

            System.out.println("executeQuery");

            if (save > 0)
            {
                System.out.println("Inserted");
                JOptionPane.showMessageDialog(null, "Sold");
                ns.updateTable();
                dispose();
            } 
            else 
            {
                System.out.println("Not Inserted");
                JOptionPane.showMessageDialog(null, "Not Sold");
            }

        } 
        catch (SQLException ex) 
        {

            Logger.getLogger(LoginForm.class.getName()).log(Level.SEVERE, null, ex);

        }
    }

    public void admin() 
    {
        LoginForm lf = new LoginForm();
        MainPage mainpage = new MainPage();
        mainpage.setVisible(true);
        mainpage.wcLbl.setText("Welcome: " +GlobalConstant.name);
    }

    public void user() 
    {
        LoginForm lf = new LoginForm();
        MainPage mainpage = new MainPage();
        mainpage.wcLbl.setText("Welcome: " +GlobalConstant.name);
        mainpage.adminPanelBtn.setVisible(false);
        mainpage.medicineBtn.setVisible(false);
        mainpage.companyBtn.setVisible(false);
        mainpage.setVisible(true);

    }
}
