package com.reallinkbilling.add;

import java.io.File;
import java.io.FileInputStream;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.apache.struts2.dispatcher.SessionMap;
import org.apache.struts2.interceptor.SessionAware;

import com.opensymphony.xwork2.ActionSupport;
import com.reallinkbilling.DAO.ProductBarcodeDetailsDAO;
import com.reallinkbilling.DAO.PurchaseInvoiceInformationDAO;
import com.reallinkbilling.DAO.PurchaseProductInfoDAO;
import com.reallinkbilling.ajax.GetNewProductCodeForNewProduct;
import com.reallinkbilling.db.GetDBConnection;
import com.reallinkbilling.resource.GetListResource;
import com.reallinkbilling.resource.CheckAlreadyAvailable;
import com.reallinkbilling.update.UpdateProductStockDetails;

public class SavePurchaseInvoiceType2  extends ActionSupport implements SessionAware,Serializable{

    private static final long serialVersionUID = 3005109908698701102L;
    private HttpSession session;
    private SessionMap<String,Object> sessionMap;
    private PurchaseInvoiceInformationDAO purchaseInvoiceInformationDAO = null; 
    private List<PurchaseProductInfoDAO> purchaseProductInfoList = null;

    private Map<String,String> taxList = new LinkedHashMap<String,String>();
    private Map<String,String> unitList = new LinkedHashMap<String,String>();

    private String totalPurchaseAmount;
    private Float amountPaid;
    private String frightCharges;
    private String otherExpense;
    private File invoiceImage;
    private String comments;
    private DecimalFormat df;
    private String invoiceImageContentType;
    private boolean addToStock;
    private String paymentType;
    private Map<String,String> paymentTypeList = new  LinkedHashMap<String,String>();
    private String paymentDefaultValue;
    private Map<String,String> rateTypeList = new  LinkedHashMap<String,String>();
    private String rateTyprDefaultValue;
    private Float tcsPercentage;
    private Float tcsAmount;
    private Float directDiscountAmount;

    @SuppressWarnings("unchecked")
    public String execute() {
        String result = "login";
        session=ServletActionContext.getRequest().getSession(false); 
        if(session==null || session.getAttribute("login")==null){ 
            addActionMessage("Please Login First !!!");
            return "login";
        }

        String shopId = (String) this.getSessionMap().get("shopId");
        String shopCode = (String) this.getSessionMap().get("shopCode");

        paymentTypeList.put("CASH","CASH");
        paymentTypeList.put("CREDIT","CREDIT");
        this.setPaymentDefaultValue(this.getPaymentDefaultValue());

        this.getRateTypeList().put("INCLUDINGGST", "Including GST");
        this.getRateTypeList().put("EXCLUDINGGST", "Excluding GST");

        // Ensure lists are always available for the JSP
        taxList = GetListResource.GetTaxList(this.getSessionMap());
        unitList = GetListResource.GetUnitList();

        df = new DecimalFormat("0.00");
        purchaseInvoiceInformationDAO = (PurchaseInvoiceInformationDAO) this.getSessionMap().get("purchaseInformation");
        purchaseProductInfoList = (List<PurchaseProductInfoDAO>) this.getSessionMap().get("purchaseProductList");

        Connection connection = null;
        PreparedStatement preparedStatement= null;
        ResultSet resultSet = null;

        String sql = "";
        String db = (String) this.getSessionMap().get("db");

        try{
            if(this.getPurchaseInvoiceInformationDAO() != null && this.getPurchaseProductInfoList() != null)
            {
                if(this.getPurchaseProductInfoList().isEmpty())
                {
                    addActionError("No items to save. Please add products to the list.");
                    return INPUT;
                }

                connection = GetDBConnection.getDBConnection(db);
                connection.setAutoCommit(false);

                // Generate purchase id if needed
                String currentPid = this.getPurchaseInvoiceInformationDAO().getPurchaseId();
                if(currentPid == null || currentPid.equals("NA") || currentPid.equals(""))
                {
                    if(preparedStatement != null){ try { preparedStatement.close(); } catch(SQLException e){} preparedStatement = null; }
                    sql = "SELECT purchase_number FROM shop_purchase_info_master WHERE shop_id = ? AND shop_code = ? ORDER BY purchase_number DESC LIMIT 1";
                    preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1, shopId);
                    preparedStatement.setString(2, shopCode);
                    resultSet = preparedStatement.executeQuery();
                    int newPid = 1;
                    if(resultSet.next()) { newPid = resultSet.getInt(1)+1; }
                    if(resultSet != null){ try { resultSet.close(); } catch(SQLException e){} resultSet = null; }
                    this.getPurchaseInvoiceInformationDAO().setPurchaseId(String.valueOf(newPid));
                }

                // Ensure each variant exists in product master; if exists, update rates; if not, create
                for(PurchaseProductInfoDAO dao : this.getPurchaseProductInfoList())
                {
                    String prodId = dao.getProductId();
                    boolean exists = false;
                    if(preparedStatement != null){ try { preparedStatement.close(); } catch(SQLException e){} preparedStatement = null; }
                    sql = "SELECT product_id FROM shop_product_master WHERE product_name_eng = ? AND shop_id = ? AND shop_code = ?";
                    preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1, dao.getProductName()!=null?dao.getProductName().toUpperCase().trim():"NA");
                    preparedStatement.setString(2, shopId);
                    preparedStatement.setString(3, shopCode);
                    resultSet = preparedStatement.executeQuery();
                    if(resultSet.next()){ exists = true; dao.setProductId(resultSet.getString(1)); }
                    if(resultSet != null){ try { resultSet.close(); } catch(SQLException e){} resultSet = null; }

                    if(!exists)
                    {
                        // get next id
                        if(preparedStatement != null){ try { preparedStatement.close(); } catch(SQLException e){} preparedStatement = null; }
                        sql = "SELECT product_id FROM shop_product_master WHERE shop_id = ? AND shop_code = ? ORDER BY product_id DESC LIMIT 1";
                        preparedStatement = connection.prepareStatement(sql);
                        preparedStatement.setString(1, shopId);
                        preparedStatement.setString(2, shopCode);
                        resultSet = preparedStatement.executeQuery();
                        int nextProductId = 1;
                        if(resultSet.next()) { nextProductId = resultSet.getInt(1) + 1; }
                        if(resultSet != null){ try { resultSet.close(); } catch(SQLException e){} resultSet = null; }

                        // resolve tax
                        Map<String,String> taxInfoMap = GetListResource.GetTaxNamePercentage(dao.getTaxId(), this.getSessionMap());
                        Float taxPercentage = 0.0F;
                        try{ taxPercentage = Float.parseFloat(taxInfoMap.get("TAX-PERCENTAGE")); }catch(Exception ex){ taxPercentage = 0.0F; }

                        String addDateStr = this.getPurchaseInvoiceInformationDAO().getPurchaseDate();
                        String productNameEng = dao.getProductName()!=null?dao.getProductName().toUpperCase().trim():"NA";
                        String productNameMar = productNameEng; // copy

                        // short code via generator
                        String generatedCode = GetNewProductCodeForNewProduct.getRandomNumber(shopId);
                        String[] checkRes = new CheckAlreadyAvailable().checkAvaibility("shop_product_master", "product_short_code", "NA", generatedCode, this.getSessionMap());
                        while("true".equals(checkRes[0]))
                        {
                            generatedCode = GetNewProductCodeForNewProduct.getRandomNumber(shopId);
                            checkRes = new CheckAlreadyAvailable().checkAvaibility("shop_product_master", "product_short_code", "NA", generatedCode, this.getSessionMap());
                        }
                        String productAlias = generatedCode; // alias can also be built from initials-size if needed

                        Float purchaseRateF = (dao.getPurchaseRate() != null) ? dao.getPurchaseRate() : 0.0F;
                        Float salesPriceF = (dao.getSalesPrice()!=null && dao.getSalesPrice()>0F)? dao.getSalesPrice() : purchaseRateF;
                        Float mrpF = salesPriceF;

                        String purchaseUnitStr = (dao.getPurchaseUnit()!=null && !dao.getPurchaseUnit().trim().equals("")) ? dao.getPurchaseUnit() : "NOS";
                        String salesUnitStr = (dao.getSalesUnit()!=null && !dao.getSalesUnit().trim().equals("")) ? dao.getSalesUnit() : purchaseUnitStr;
                        String hsnCode = (dao.getHsnCode()!=null && !dao.getHsnCode().trim().equals("")) ? dao.getHsnCode() : "NA";
                        String stockConvRatio = "1";
                        Float defaultBarcodeQty = 1.0F;

                        if(preparedStatement != null){ try { preparedStatement.close(); } catch(SQLException e){} preparedStatement = null; }
                        sql = "INSERT INTO shop_product_master (product_id,shop_id,shop_code,add_date,product_name_eng,product_name_mar,product_short_code,product_alias,low_stock_count,purchase_rate,customer_sales_price,dealer_sales_price,retailer_sales_price,tax_id,tax_percentage,purchase_unit,sales_unit,hsn_sac_code,stock_conversion_ratio,product_image,in_stock_quantity,rack_number,barcode_mrp,discount_type,discount_amount_percentage,sales_price,default_barcode_quantity) values (?,?,?,STR_TO_DATE(?,'%d-%m-%Y'),?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
                        preparedStatement = connection.prepareStatement(sql);
                        preparedStatement.setInt(1, nextProductId);
                        preparedStatement.setString(2, shopId);
                        preparedStatement.setString(3, shopCode);
                        preparedStatement.setString(4, addDateStr);
                        preparedStatement.setString(5, productNameEng);
                        preparedStatement.setString(6, productNameMar);
                        preparedStatement.setString(7, generatedCode);
                        preparedStatement.setString(8, productAlias);
                        preparedStatement.setString(9, "0");
                        preparedStatement.setFloat(10, purchaseRateF);
                        preparedStatement.setFloat(11, salesPriceF);
                        preparedStatement.setFloat(12, salesPriceF);
                        preparedStatement.setFloat(13, salesPriceF);
                        preparedStatement.setString(14, dao.getTaxId());
                        preparedStatement.setFloat(15, taxPercentage);
                        preparedStatement.setString(16, purchaseUnitStr);
                        preparedStatement.setString(17, salesUnitStr);
                        preparedStatement.setString(18, hsnCode);
                        preparedStatement.setString(19, stockConvRatio);
                        preparedStatement.setBinaryStream(20, null);
                        preparedStatement.setFloat(21, 0.0F);
                        preparedStatement.setString(22, "NA");
                        preparedStatement.setFloat(23, mrpF);
                        preparedStatement.setString(24, "PERCENTAGE");
                        preparedStatement.setFloat(25, 0.0F);
                        preparedStatement.setFloat(26, salesPriceF);
                        preparedStatement.setFloat(27, defaultBarcodeQty);
                        int prodInserted = preparedStatement.executeUpdate();
                        if(prodInserted > 0){ dao.setProductId(String.valueOf(nextProductId)); }
                    }
                    else
                    {
                        // Product exists: update purchase and sales rates only (no duplicates)
                        Float purchaseRateF = (dao.getPurchaseRate() != null) ? dao.getPurchaseRate() : 0.0F;
                        Float salesPriceF = (dao.getSalesPrice()!=null && dao.getSalesPrice()>0F)? dao.getSalesPrice() : purchaseRateF;
                        Float mrpF = salesPriceF;
                        // resolve tax for update branch
                        Map<String,String> taxInfoMap = GetListResource.GetTaxNamePercentage(dao.getTaxId(), this.getSessionMap());
                        Float taxPercentage = 0.0F;
                        try{ taxPercentage = Float.parseFloat(taxInfoMap.get("TAX-PERCENTAGE")); }catch(Exception ex){ taxPercentage = 0.0F; }
                        String purchaseUnitStr = (dao.getPurchaseUnit()!=null && !dao.getPurchaseUnit().trim().equals("")) ? dao.getPurchaseUnit() : "NOS";
                        String salesUnitStr = (dao.getSalesUnit()!=null && !dao.getSalesUnit().trim().equals("")) ? dao.getSalesUnit() : purchaseUnitStr;
                        String hsnCode = (dao.getHsnCode()!=null && !dao.getHsnCode().trim().equals("")) ? dao.getHsnCode() : "NA";
                        if(preparedStatement != null){ try { preparedStatement.close(); } catch(SQLException e){} preparedStatement = null; }
                        sql = "UPDATE shop_product_master SET purchase_rate = ?, customer_sales_price = ?, dealer_sales_price = ?, retailer_sales_price = ?, barcode_mrp = ?, sales_price = ?, purchase_unit = ?, sales_unit = ?, hsn_sac_code = ?, tax_id = ?, tax_percentage = ? WHERE product_id = ? AND shop_id = ? AND shop_code = ?";
                        preparedStatement = connection.prepareStatement(sql);
                        preparedStatement.setFloat(1, purchaseRateF);
                        preparedStatement.setFloat(2, salesPriceF);
                        preparedStatement.setFloat(3, salesPriceF);
                        preparedStatement.setFloat(4, salesPriceF);
                        preparedStatement.setFloat(5, mrpF);
                        preparedStatement.setFloat(6, salesPriceF);
                        preparedStatement.setString(7, purchaseUnitStr);
                        preparedStatement.setString(8, salesUnitStr);
                        preparedStatement.setString(9, hsnCode);
                        preparedStatement.setString(10, dao.getTaxId());
                        preparedStatement.setFloat(11, taxPercentage);
                        preparedStatement.setInt(12, Integer.parseInt(dao.getProductId()));
                        preparedStatement.setString(13, shopId);
                        preparedStatement.setString(14, shopCode);
                        preparedStatement.executeUpdate();
                    }
                }

                // Insert purchase header
                if(preparedStatement != null){ try { preparedStatement.close(); } catch(SQLException e){} preparedStatement = null; }
                java.util.Date dateNow = new java.util.Date();
                long t = dateNow.getTime();
                java.sql.Time timeNow = new java.sql.Time(t);

                float totalGross = 0F, totalNett=0F, totalCgst=0F, totalSgst=0F, totalIgst=0F;
                for(PurchaseProductInfoDAO p : this.getPurchaseProductInfoList())
                {
                    totalGross += (p.getGrossAmount()!=null? p.getGrossAmount():0F);
                    totalNett += (p.getNettAmount()!=null? p.getNettAmount():0F);
                    totalCgst += (p.getCgst()!=null? p.getCgst():0F);
                    totalSgst += (p.getSgst()!=null? p.getSgst():0F);
                    totalIgst += (p.getIgst()!=null? p.getIgst():0F);
                }

                // Before writing header and details, detect if this is an update for existing purchase_number
                int existingHeaderRows = 0;
                if(preparedStatement != null){ try { preparedStatement.close(); } catch(SQLException e){} preparedStatement = null; }
                sql = "SELECT COUNT(*) FROM shop_purchase_info_master WHERE shop_id = ? AND shop_code = ? AND purchase_number = ?";
                preparedStatement = connection.prepareStatement(sql);
                preparedStatement.setString(1, shopId);
                preparedStatement.setString(2, shopCode);
                preparedStatement.setString(3, this.getPurchaseInvoiceInformationDAO().getPurchaseId());
                resultSet = preparedStatement.executeQuery();
                if(resultSet.next()){ existingHeaderRows = resultSet.getInt(1); }
                if(resultSet != null){ try { resultSet.close(); } catch(SQLException e){} resultSet = null; }

                // If header exists, delete old detail rows and minus stock for them first (update flow)
                if(existingHeaderRows > 0)
                {
                    if(preparedStatement != null){ try { preparedStatement.close(); } catch(SQLException e){} preparedStatement = null; }
                    sql = "SELECT product_id, product_name, puroduct_quantity FROM shop_purchase_product_info_master WHERE shop_id = ? AND shop_code = ? AND purchase_number = ?";
                    preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1, shopId);
                    preparedStatement.setString(2, shopCode);
                    preparedStatement.setString(3, this.getPurchaseInvoiceInformationDAO().getPurchaseId());
                    ResultSet rsOld = preparedStatement.executeQuery();
                    while(rsOld.next())
                    {
                        try{ UpdateProductStockDetails.minusStockToCurrentStockForPurchase(connection, this.getSessionMap(), rsOld.getString(1), rsOld.getString(2), rsOld.getFloat(3)); }catch(Exception ignore){}
                    }
                    if(rsOld != null){ try{ rsOld.close(); }catch(SQLException e){} }
                    if(preparedStatement != null){ try { preparedStatement.close(); } catch(SQLException e){} preparedStatement = null; }

                    sql = "DELETE FROM shop_purchase_product_info_master WHERE shop_id = ? AND shop_code = ? AND purchase_number = ?";
                    preparedStatement = connection.prepareStatement(sql);
                    preparedStatement.setString(1, shopId);
                    preparedStatement.setString(2, shopCode);
                    preparedStatement.setString(3, this.getPurchaseInvoiceInformationDAO().getPurchaseId());
                    preparedStatement.executeUpdate();
                }

                // Check if purchase_type column exists
                boolean hasTypeCol = false;
                try{
                    if(preparedStatement != null){ try { preparedStatement.close(); } catch(SQLException e){} preparedStatement = null; }
                    sql = "SELECT column_name FROM information_schema.COLUMNS WHERE TABLE_NAME='shop_purchase_info_master' AND COLUMN_NAME='purchase_type'";
                    preparedStatement = connection.prepareStatement(sql);
                    resultSet = preparedStatement.executeQuery();
                    hasTypeCol = resultSet.next();
                    if(resultSet != null){ try { resultSet.close(); } catch(SQLException e){} resultSet = null; }
                }catch(SQLException ignore){}

                FileInputStream fis = null;
                if(this.getInvoiceImage()!=null){ try{ fis = new FileInputStream(this.getInvoiceImage()); }catch(Exception e){} }

                if(existingHeaderRows > 0)
                {
                    // UPDATE header
                    if(this.getInvoiceImage()!=null && fis!=null)
                    {
                        if(hasTypeCol)
                        {
                            sql = "UPDATE shop_purchase_info_master SET purchase_invoice_number=?, purchase_date=STR_TO_DATE(?,'%d-%m-%Y'), purchase_time=?, supplier_id=?, transportation_charges=?, other_expenses=?, comments=?, total_purchase_amount=?, purchase_amount_paid=?, purchase_igst_amount=?, purchase_scgst_amount=?, purchase_cgst_amount=?, purchase_net_amount=?, invoice_pic=?, payment_type=?, entry_by=?, purchased_by=?, supplier_name=?, rate_type=?, tcs_percentage=?, tcs_amount=?, direct_discount_amount=?, purchase_type='TYPE2' WHERE shop_id=? AND shop_code=? AND purchase_number=?";
                        }
                        else
                        {
                            sql = "UPDATE shop_purchase_info_master SET purchase_invoice_number=?, purchase_date=STR_TO_DATE(?,'%d-%m-%Y'), purchase_time=?, supplier_id=?, transportation_charges=?, other_expenses=?, comments=?, total_purchase_amount=?, purchase_amount_paid=?, purchase_igst_amount=?, purchase_scgst_amount=?, purchase_cgst_amount=?, purchase_net_amount=?, invoice_pic=?, payment_type=?, entry_by=?, purchased_by=?, supplier_name=?, rate_type=?, tcs_percentage=?, tcs_amount=?, direct_discount_amount=? WHERE shop_id=? AND shop_code=? AND purchase_number=?";
                        }
                        preparedStatement = connection.prepareStatement(sql);
                        preparedStatement.setString(1, this.getPurchaseInvoiceInformationDAO().getInvoiceNumber());
                        preparedStatement.setString(2, this.getPurchaseInvoiceInformationDAO().getPurchaseDate());
                        preparedStatement.setTime(3, timeNow);
                        preparedStatement.setString(4, this.getPurchaseInvoiceInformationDAO().getSupplierId());
                        preparedStatement.setString(5, this.getFrightCharges()!=null? this.getFrightCharges():"0");
                        preparedStatement.setString(6, this.getOtherExpense()!=null? this.getOtherExpense():"0");
                        preparedStatement.setString(7, this.getComments()!=null? this.getComments():"NA");
                        preparedStatement.setFloat(8, totalGross);
                        preparedStatement.setFloat(9, this.getAmountPaid()!=null? this.getAmountPaid():0F);
                        preparedStatement.setFloat(10, totalIgst);
                        preparedStatement.setFloat(11, totalSgst);
                        preparedStatement.setFloat(12, totalCgst);
                        preparedStatement.setFloat(13, totalNett);
                        preparedStatement.setBinaryStream(14, fis, (int)this.getInvoiceImage().length());
                        preparedStatement.setString(15, this.getPaymentType()!=null? this.getPaymentType():"CREDIT");
                        String fullUserName = (String) this.getSessionMap().get("userFullName");
                        String entryBy = (fullUserName!=null && fullUserName.contains(" "))? fullUserName.split(" ")[0] : (fullUserName!=null? fullUserName : "USER");
                        preparedStatement.setString(16, entryBy);
                        preparedStatement.setString(17, this.getPurchaseInvoiceInformationDAO().getPurchaseBy()!=null? this.getPurchaseInvoiceInformationDAO().getPurchaseBy():entryBy);
                        preparedStatement.setString(18, this.getPurchaseInvoiceInformationDAO().getSupplierName());
                        preparedStatement.setString(19, this.getPurchaseInvoiceInformationDAO().getRateType());
                        preparedStatement.setFloat(20, this.getTcsPercentage()!=null? this.getTcsPercentage():0F);
                        preparedStatement.setFloat(21, this.getTcsAmount()!=null? this.getTcsAmount():0F);
                        preparedStatement.setFloat(22, this.getDirectDiscountAmount()!=null? this.getDirectDiscountAmount():0F);
                        preparedStatement.setString(23, shopId);
                        preparedStatement.setString(24, shopCode);
                        preparedStatement.setString(25, this.getPurchaseInvoiceInformationDAO().getPurchaseId());
                    }
                    else
                    {
                        if(hasTypeCol)
                        {
                            sql = "UPDATE shop_purchase_info_master SET purchase_invoice_number=?, purchase_date=STR_TO_DATE(?,'%d-%m-%Y'), purchase_time=?, supplier_id=?, transportation_charges=?, other_expenses=?, comments=?, total_purchase_amount=?, purchase_amount_paid=?, purchase_igst_amount=?, purchase_scgst_amount=?, purchase_cgst_amount=?, purchase_net_amount=?, payment_type=?, entry_by=?, purchased_by=?, supplier_name=?, rate_type=?, tcs_percentage=?, tcs_amount=?, direct_discount_amount=?, purchase_type='TYPE2' WHERE shop_id=? AND shop_code=? AND purchase_number=?";
                        }
                        else
                        {
                            sql = "UPDATE shop_purchase_info_master SET purchase_invoice_number=?, purchase_date=STR_TO_DATE(?,'%d-%m-%Y'), purchase_time=?, supplier_id=?, transportation_charges=?, other_expenses=?, comments=?, total_purchase_amount=?, purchase_amount_paid=?, purchase_igst_amount=?, purchase_scgst_amount=?, purchase_cgst_amount=?, purchase_net_amount=?, payment_type=?, entry_by=?, purchased_by=?, supplier_name=?, rate_type=?, tcs_percentage=?, tcs_amount=?, direct_discount_amount=? WHERE shop_id=? AND shop_code=? AND purchase_number=?";
                        }
                        
                        if(preparedStatement != null){ try { preparedStatement.close(); } catch(SQLException e){} preparedStatement = null; }
                        
                        preparedStatement = connection.prepareStatement(sql);
                        preparedStatement.setString(1, this.getPurchaseInvoiceInformationDAO().getInvoiceNumber());
                        preparedStatement.setString(2, this.getPurchaseInvoiceInformationDAO().getPurchaseDate());
                        preparedStatement.setTime(3, timeNow);
                        preparedStatement.setString(4, this.getPurchaseInvoiceInformationDAO().getSupplierId());
                        preparedStatement.setString(5, this.getFrightCharges()!=null? this.getFrightCharges():"0");
                        preparedStatement.setString(6, this.getOtherExpense()!=null? this.getOtherExpense():"0");
                        preparedStatement.setString(7, this.getComments()!=null? this.getComments():"NA");
                        preparedStatement.setFloat(8, totalGross);
                        preparedStatement.setFloat(9, this.getAmountPaid()!=null? this.getAmountPaid():0F);
                        preparedStatement.setFloat(10, totalIgst);
                        preparedStatement.setFloat(11, totalSgst);
                        preparedStatement.setFloat(12, totalCgst);
                        preparedStatement.setFloat(13, totalNett);
                        preparedStatement.setString(14, this.getPaymentType()!=null? this.getPaymentType():"CREDIT");
                        String fullUserName2 = (String) this.getSessionMap().get("userFullName");
                        String entryBy2 = (fullUserName2!=null && fullUserName2.contains(" "))? fullUserName2.split(" ")[0] : (fullUserName2!=null? fullUserName2 : "USER");
                        preparedStatement.setString(15, entryBy2);
                        preparedStatement.setString(16, this.getPurchaseInvoiceInformationDAO().getPurchaseBy()!=null? this.getPurchaseInvoiceInformationDAO().getPurchaseBy():entryBy2);
                        preparedStatement.setString(17, this.getPurchaseInvoiceInformationDAO().getSupplierName());
                        preparedStatement.setString(18, this.getPurchaseInvoiceInformationDAO().getRateType());
                        preparedStatement.setFloat(19, this.getTcsPercentage()!=null? this.getTcsPercentage():0F);
                        preparedStatement.setFloat(20, this.getTcsAmount()!=null? this.getTcsAmount():0F);
                        preparedStatement.setFloat(21, this.getDirectDiscountAmount()!=null? this.getDirectDiscountAmount():0F);
                        preparedStatement.setString(22, shopId);
                        preparedStatement.setString(23, shopCode);
                        preparedStatement.setString(24, this.getPurchaseInvoiceInformationDAO().getPurchaseId());
                    }
                }
                else
                {
                    // INSERT header (new purchase)
                    if(this.getInvoiceImage()!=null && fis!=null)
                    {
                        if(hasTypeCol)
                        {
                            sql = "INSERT INTO shop_purchase_info_master (purchase_number,shop_id,shop_code,purchase_invoice_number,purchase_date,purchase_time,supplier_id,transportation_charges,other_expenses,comments,total_purchase_amount,purchase_amount_paid,purchase_igst_amount,purchase_scgst_amount,purchase_cgst_amount,purchase_net_amount,invoice_pic,payment_type,entry_by,purchased_by,supplier_name,rate_type,tcs_percentage,tcs_amount,direct_discount_amount,purchase_type) VALUES (?,?,?,?,STR_TO_DATE(?,'%d-%m-%Y'),?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,'TYPE2')";
                        }
                        else
                        {
                            sql = "INSERT INTO shop_purchase_info_master (purchase_number,shop_id,shop_code,purchase_invoice_number,purchase_date,purchase_time,supplier_id,transportation_charges,other_expenses,comments,total_purchase_amount,purchase_amount_paid,purchase_igst_amount,purchase_scgst_amount,purchase_cgst_amount,purchase_net_amount,invoice_pic,payment_type,entry_by,purchased_by,supplier_name,rate_type,tcs_percentage,tcs_amount,direct_discount_amount) VALUES (?,?,?,?,STR_TO_DATE(?,'%d-%m-%Y'),?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
                        }
                        
                        if(preparedStatement != null){ try { preparedStatement.close(); } catch(SQLException e){} preparedStatement = null; }
                        
                        
                        preparedStatement = connection.prepareStatement(sql);
                        preparedStatement.setString(1, this.getPurchaseInvoiceInformationDAO().getPurchaseId());
                        preparedStatement.setString(2, shopId);
                        preparedStatement.setString(3, shopCode);
                        preparedStatement.setString(4, this.getPurchaseInvoiceInformationDAO().getInvoiceNumber());
                        preparedStatement.setString(5, this.getPurchaseInvoiceInformationDAO().getPurchaseDate());
                        preparedStatement.setTime(6, timeNow);
                        preparedStatement.setString(7, this.getPurchaseInvoiceInformationDAO().getSupplierId());
                        preparedStatement.setString(8, this.getFrightCharges()!=null? this.getFrightCharges():"0");
                        preparedStatement.setString(9, this.getOtherExpense()!=null? this.getOtherExpense():"0");
                        preparedStatement.setString(10, this.getComments()!=null? this.getComments():"NA");
                        preparedStatement.setFloat(11, totalGross);
                        preparedStatement.setFloat(12, this.getAmountPaid()!=null? this.getAmountPaid():0F);
                        preparedStatement.setFloat(13, totalIgst);
                        preparedStatement.setFloat(14, totalSgst);
                        preparedStatement.setFloat(15, totalCgst);
                        preparedStatement.setFloat(16, totalNett);
                        preparedStatement.setBinaryStream(17, fis, (int)this.getInvoiceImage().length());
                        preparedStatement.setString(18, this.getPaymentType()!=null? this.getPaymentType():"CREDIT");
                        String fullUserName = (String) this.getSessionMap().get("userFullName");
                        String entryBy = (fullUserName!=null && fullUserName.contains(" "))? fullUserName.split(" ")[0] : (fullUserName!=null? fullUserName : "USER");
                        preparedStatement.setString(19, entryBy);
                        preparedStatement.setString(20, this.getPurchaseInvoiceInformationDAO().getPurchaseBy()!=null? this.getPurchaseInvoiceInformationDAO().getPurchaseBy():entryBy);
                        preparedStatement.setString(21, this.getPurchaseInvoiceInformationDAO().getSupplierName());
                        preparedStatement.setString(22, this.getPurchaseInvoiceInformationDAO().getRateType());
                        preparedStatement.setFloat(23, this.getTcsPercentage()!=null? this.getTcsPercentage():0F);
                        preparedStatement.setFloat(24, this.getTcsAmount()!=null? this.getTcsAmount():0F);
                        preparedStatement.setFloat(25, this.getDirectDiscountAmount()!=null? this.getDirectDiscountAmount():0F);
                    }
                    else
                    {
                        if(hasTypeCol)
                        {
                            sql = "INSERT INTO shop_purchase_info_master (purchase_number,shop_id,shop_code,purchase_invoice_number,purchase_date,purchase_time,supplier_id,transportation_charges,other_expenses,comments,total_purchase_amount,purchase_amount_paid,purchase_igst_amount,purchase_scgst_amount,purchase_cgst_amount,purchase_net_amount,payment_type,entry_by,purchased_by,supplier_name,rate_type,tcs_percentage,tcs_amount,direct_discount_amount,purchase_type) VALUES (?,?,?,?,STR_TO_DATE(?,'%d-%m-%Y'),?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,'TYPE2')";
                        }
                        else
                        {
                            sql = "INSERT INTO shop_purchase_info_master (purchase_number,shop_id,shop_code,purchase_invoice_number,purchase_date,purchase_time,supplier_id,transportation_charges,other_expenses,comments,total_purchase_amount,purchase_amount_paid,purchase_igst_amount,purchase_scgst_amount,purchase_cgst_amount,purchase_net_amount,payment_type,entry_by,purchased_by,supplier_name,rate_type,tcs_percentage,tcs_amount,direct_discount_amount) VALUES (?,?,?,?,STR_TO_DATE(?,'%d-%m-%Y'),?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
                        }
                        
                        if(preparedStatement != null){ try { preparedStatement.close(); } catch(SQLException e){} preparedStatement = null; }
                        
                        
                        preparedStatement = connection.prepareStatement(sql);
                        preparedStatement.setString(1, this.getPurchaseInvoiceInformationDAO().getPurchaseId());
                        preparedStatement.setString(2, shopId);
                        preparedStatement.setString(3, shopCode);
                        preparedStatement.setString(4, this.getPurchaseInvoiceInformationDAO().getInvoiceNumber());
                        preparedStatement.setString(5, this.getPurchaseInvoiceInformationDAO().getPurchaseDate());
                        preparedStatement.setTime(6, timeNow);
                        preparedStatement.setString(7, this.getPurchaseInvoiceInformationDAO().getSupplierId());
                        preparedStatement.setString(8, this.getFrightCharges()!=null? this.getFrightCharges():"0");
                        preparedStatement.setString(9, this.getOtherExpense()!=null? this.getOtherExpense():"0");
                        preparedStatement.setString(10, this.getComments()!=null? this.getComments():"NA");
                        preparedStatement.setFloat(11, totalGross);
                        preparedStatement.setFloat(12, this.getAmountPaid()!=null? this.getAmountPaid():0F);
                        preparedStatement.setFloat(13, totalIgst);
                        preparedStatement.setFloat(14, totalSgst);
                        preparedStatement.setFloat(15, totalCgst);
                        preparedStatement.setFloat(16, totalNett);
                        preparedStatement.setString(17, this.getPaymentType()!=null? this.getPaymentType():"CREDIT");
                        String fullUserName2 = (String) this.getSessionMap().get("userFullName");
                        String entryBy2 = (fullUserName2!=null && fullUserName2.contains(" "))? fullUserName2.split(" ")[0] : (fullUserName2!=null? fullUserName2 : "USER");
                        preparedStatement.setString(18, entryBy2);
                        preparedStatement.setString(19, this.getPurchaseInvoiceInformationDAO().getPurchaseBy()!=null? this.getPurchaseInvoiceInformationDAO().getPurchaseBy():entryBy2);
                        preparedStatement.setString(20, this.getPurchaseInvoiceInformationDAO().getSupplierName());
                        preparedStatement.setString(21, this.getPurchaseInvoiceInformationDAO().getRateType());
                        preparedStatement.setFloat(22, this.getTcsPercentage()!=null? this.getTcsPercentage():0F);
                        preparedStatement.setFloat(23, this.getTcsAmount()!=null? this.getTcsAmount():0F);
                        preparedStatement.setFloat(24, this.getDirectDiscountAmount()!=null? this.getDirectDiscountAmount():0F);
                    }
                }
                int headerInserted = preparedStatement.executeUpdate();
                if(headerInserted <= 0)
                {
                    connection.rollback();
                    addActionError("Purchase header not saved.");
                    return ERROR;
                }

                // Insert product info lines
                if(preparedStatement != null){ try { preparedStatement.close(); } catch(SQLException e){} preparedStatement = null; }
                sql = "INSERT into shop_purchase_product_info_master (purchase_number,shop_id,shop_code,purchase_invoice_number,product_id,product_name,serial_no_batch_id,purchase_unit,tax_id,purchase_rate,puroduct_quantity,product_total_amount,product_net_amount,product_igst_amount,product_cgst_amount,product_sgst_amount,product_gross_amount,discount,discount_type) values(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
                preparedStatement = connection.prepareStatement(sql);
                boolean allStockAdded = true;
                for(PurchaseProductInfoDAO dao: this.getPurchaseProductInfoList())
                {
                    preparedStatement.setString(1, this.getPurchaseInvoiceInformationDAO().getPurchaseId() );
                    preparedStatement.setString(2, shopId);
                    preparedStatement.setString(3, shopCode);
                    preparedStatement.setString(4, this.getPurchaseInvoiceInformationDAO().getInvoiceNumber());
                    preparedStatement.setString(5, dao.getProductId());
                    preparedStatement.setString(6, dao.getProductName());
                    preparedStatement.setString(7, (dao.getSerialBatchNo()!=null && dao.getSerialBatchNo().trim().length()>0)? dao.getSerialBatchNo():"NA");
                    preparedStatement.setString(8, dao.getPurchaseUnit());
                    preparedStatement.setString(9, dao.getTaxId());
                    preparedStatement.setFloat(10, dao.getPurchaseRate());
                    preparedStatement.setFloat(11, dao.getQuantity());
                    preparedStatement.setFloat(12, dao.getAmount());
                    preparedStatement.setFloat(13, dao.getNettAmount());
                    preparedStatement.setFloat(14, dao.getIgst());
                    preparedStatement.setFloat(15, dao.getCgst());
                    preparedStatement.setFloat(16, dao.getSgst());
                    preparedStatement.setFloat(17, dao.getGrossAmount());
                    preparedStatement.setFloat(18, dao.getDiscount());
                    preparedStatement.setString(19, dao.getDiscountType());
                    preparedStatement.addBatch();

                    boolean stockAdded = UpdateProductStockDetails.addStockToCurrentStockForPurchase( connection, this.getSessionMap(),dao.getProductId(), dao.getProductName(), dao.getQuantity());
                    if(!stockAdded){ allStockAdded = false; }
                }
                int[] numUpdates = preparedStatement.executeBatch();

                if(numUpdates != null && numUpdates.length == this.getPurchaseProductInfoList().size() && allStockAdded)
                {
                    connection.commit();
                    this.getPurchaseInvoiceInformationDAO().setPurchaseSaved(true);
                    this.getSessionMap().remove("purchaseProductList");
                    this.getSessionMap().remove("purchaseInformation");
                    // Prepare redirect to view purchase page
                    ServletActionContext.getRequest().setAttribute("redirectToViewPurchaseNumber", this.getPurchaseInvoiceInformationDAO().getPurchaseId());
                    result="success";
                    addActionMessage("Purchase invoice (Type 2) saved successfully!");
                }
                else
                {
                    connection.rollback();
                    result="error";
                    addActionError("Purchase details not saved! Please try again.");
                }
            }
            else
            {
                result = "error";
                addActionError("Purchase details not found!Please try again!");
            }
        }
        catch (SQLException e) {
            result = "error"; 
            addActionError(e.getErrorCode()+" || "+e.getMessage()+" || Purchase details not Saved!");
        } catch (Exception e) {
            result = "error"; 
            addActionError(e.getMessage()+" || "+e.getCause()+" || Purchase details not Saved!");
        } finally {
            try{ if(connection!=null) connection.close(); } catch(Exception ignore){}
        }

        return result;
    }

    @Override
    public void validate()
    {
        // Repopulate lists to avoid Tiles errors on error/input
        this.setTaxList(GetListResource.GetTaxList(this.getSessionMap()));
        this.setUnitList(GetListResource.GetUnitList());

        // Also ensure radio/select models exist in JSP
        if(this.getRateTypeList()==null){
            this.rateTypeList = new LinkedHashMap<String,String>();
            this.rateTypeList.put("INCLUDINGGST","Including GST");
            this.rateTypeList.put("EXCLUDINGGST","Excluding GST");
        }
        if(this.getPaymentTypeList()==null){
            this.paymentTypeList = new LinkedHashMap<String,String>();
            this.paymentTypeList.put("CASH","CASH");
            this.paymentTypeList.put("CREDIT","CREDIT");
        }

        // Server-side validations
        // Load header and list from session if not already populated, since validate() runs before execute()
        if(this.getPurchaseInvoiceInformationDAO()==null)
        {
            try{
                this.setPurchaseInvoiceInformationDAO((PurchaseInvoiceInformationDAO) this.getSessionMap().get("purchaseInformation"));
            }catch(Exception ignore){}
        }

        PurchaseInvoiceInformationDAO info = this.getPurchaseInvoiceInformationDAO();
        if(info == null)
        {
            addActionError("Purchase header not found. Please open Add Purchase Type 2 and add items again.");
            return;
        }
        if(info.getPurchaseDate()==null || info.getPurchaseDate().trim().equals(""))
        { addActionError("Purchase Date is required."); }
        if(info.getSupplierName()==null || info.getSupplierName().trim().equals("") )
        { addActionError("Supplier/Party Name is required."); }
        if(info.getInvoiceNumber()==null || info.getInvoiceNumber().trim().equals(""))
        { addActionError("Invoice Number is required."); }
        if(info.getRateType()==null || info.getRateType().trim().equals(""))
        { info.setRateType("INCLUDINGGST"); }

        @SuppressWarnings("unchecked")
        List<PurchaseProductInfoDAO> list = (List<PurchaseProductInfoDAO>) (this.getSessionMap()!=null? this.getSessionMap().get("purchaseProductList"): null);
        if(list==null || list.isEmpty())
        { addActionError("No items to save. Please add products to the list."); }
    }

    public void setSession(Map<String, Object> map) { sessionMap=(SessionMap<String, Object>)map; }
    public SessionMap<String,Object> getSessionMap(){ return sessionMap; }

    public PurchaseInvoiceInformationDAO getPurchaseInvoiceInformationDAO() { return purchaseInvoiceInformationDAO; }
    public void setPurchaseInvoiceInformationDAO(PurchaseInvoiceInformationDAO purchaseInvoiceInformationDAO) { this.purchaseInvoiceInformationDAO = purchaseInvoiceInformationDAO; }
    public List<PurchaseProductInfoDAO> getPurchaseProductInfoList() { return purchaseProductInfoList; }
    public void setPurchaseProductInfoList(List<PurchaseProductInfoDAO> purchaseProductInfoList) { this.purchaseProductInfoList = purchaseProductInfoList; }
    public String getTotalPurchaseAmount() { return totalPurchaseAmount; }
    public void setTotalPurchaseAmount(String totalPurchaseAmount) { this.totalPurchaseAmount = totalPurchaseAmount; }
    public Float getAmountPaid() { return amountPaid; }
    public void setAmountPaid(Float amountPaid) { this.amountPaid = amountPaid; }
    public String getFrightCharges() { return frightCharges; }
    public void setFrightCharges(String frightCharges) { this.frightCharges = frightCharges; }
    public String getOtherExpense() { return otherExpense; }
    public void setOtherExpense(String otherExpense) { this.otherExpense = otherExpense; }
    public File getInvoiceImage() { return invoiceImage; }
    public void setInvoiceImage(File invoiceImage) { this.invoiceImage = invoiceImage; }
    public String getComments() { return comments; }
    public void setComments(String comments) { this.comments = comments; }
    public DecimalFormat getDf() { return df; }
    public void setDf(DecimalFormat df) { this.df = df; }
    public String getInvoiceImageContentType() { return invoiceImageContentType; }
    public void setInvoiceImageContentType(String invoiceImageContentType) { this.invoiceImageContentType = invoiceImageContentType; }
    public boolean isAddToStock() { return addToStock; }
    public void setAddToStock(boolean addToStock) { this.addToStock = addToStock; }
    public String getPaymentType() { return paymentType; }
    public void setPaymentType(String paymentType) { this.paymentType = paymentType; }
    public Map<String, String> getPaymentTypeList() { return paymentTypeList; }
    public void setPaymentTypeList(Map<String, String> paymentTypeList) { this.paymentTypeList = paymentTypeList; }
    public String getPaymentDefaultValue() { return paymentDefaultValue; }
    public void setPaymentDefaultValue(String paymentDefaultValue) { this.paymentDefaultValue = paymentDefaultValue; }
    public Map<String, String> getRateTypeList() { return rateTypeList; }
    public void setRateTypeList(Map<String, String> rateTypeList) { this.rateTypeList = rateTypeList; }
    public String getRateTyprDefaultValue() { return rateTyprDefaultValue; }
    public void setRateTyprDefaultValue(String rateTyprDefaultValue) { this.rateTyprDefaultValue = rateTyprDefaultValue; }
    public Float getTcsPercentage() { return tcsPercentage; }
    public void setTcsPercentage(Float tcsPercentage) { this.tcsPercentage = tcsPercentage; }
    public Float getTcsAmount() { return tcsAmount; }
    public void setTcsAmount(Float tcsAmount) { this.tcsAmount = tcsAmount; }
    public Float getDirectDiscountAmount() { return directDiscountAmount; }
    public void setDirectDiscountAmount(Float directDiscountAmount) { this.directDiscountAmount = directDiscountAmount; }

    public Map<String,String> getTaxList(){ return taxList; }
    public void setTaxList(Map<String,String> taxList){ this.taxList = taxList; }
    public Map<String,String> getUnitList(){ return unitList; }
    public void setUnitList(Map<String,String> unitList){ this.unitList = unitList; }
}


