package json_package;

import group_head_package.DataBaseIncomeExpense;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;

import main_package.DataBaseConnection;
import main_package.DataBaseMethodTaheer;
import main_package.DataBaseMethods;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

@ManagedBean(name = "payLoanEmiJson")
@ViewScoped

public class PayLoanEmiJsonBean implements Serializable
{
    private static final long serialVersionUID = 1L;

    String json;
    
    Date startDate;

    DataBaseMethods obj = new DataBaseMethods();
    DataBaseMethodTaheer dbmt = new DataBaseMethodTaheer();
    
    
    
    public PayLoanEmiJsonBean() throws ParseException
    {
        Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();

        String employee = params.get("userid");
        String loanType = params.get("loanType");
        String loanNo = params.get("loanNo");
        String sDate = params.get("startDate");
        String amount = params.get("amount");
        String savingAmount = params.get("savingAmount");
        String penaltyAmount = params.get("penaltyAmount");
        String rdAmount = params.get("rdAmount");
        String payMode = params.get("payMode");
        String transactionId = params.get("transactionId");
        String response = params.get("response");
        String paymentProof = params.get("paymentProof");
        String branchStr = params.get("branchId");
        String rdNumber = params.get("rdNumber");
        String chequeBounceAmount = params.get("chequeBounceCharge");
        
        System.out.println("userid = " + employee);
        System.out.println("loanType = " + loanType);
        System.out.println("loanNo = " + loanNo);
        System.out.println("startDate = " + sDate);
        System.out.println("amount = " + amount);
        System.out.println("savingAmount = " + savingAmount);
        System.out.println("penaltyAmount = " + penaltyAmount);
        System.out.println("rdAmount = " + rdAmount);
        System.out.println("payMode = " + payMode);
        System.out.println("transactionId = " + transactionId);
        System.out.println("response = " + response);
        System.out.println("paymentProof = " + paymentProof);
        System.out.println("branchId = " + branchStr);
        System.out.println("rdNumber = " + rdNumber);
        System.out.println("chequeBounceCharge = " + chequeBounceAmount);
        
        int branchId = Integer.valueOf(branchStr);
        
        if (paymentProof == null)
        {
            paymentProof = "";
        }

        if (savingAmount == null || savingAmount.equals(""))
        {
            savingAmount = "0";
        }

        if (penaltyAmount == null || penaltyAmount.equals(""))
        {
            penaltyAmount = "0";
        }
        
        if (chequeBounceAmount == null || chequeBounceAmount.equals(""))
        {
        	chequeBounceAmount = "0";
        }

        if (rdAmount == null || rdAmount.equals(""))
        {
            rdAmount = "0";
        }

        if (amount == null || amount.equals(""))
        {
            amount = "0";
        }

        String paymentProofPath = "";

        if (paymentProof != null && !paymentProof.trim().equals(""))
    	{
    	    try
    	    {
    	        String extension = ".jpg";

    	        if (paymentProof.startsWith("data:image/png"))
    	        {
    	            extension = ".png";
    	        }
    	        else if (paymentProof.startsWith("data:image/jpeg"))
    	        {
    	            extension = ".jpg";
    	        }
    	        else if (paymentProof.startsWith("data:image/jpg"))
    	        {
    	            extension = ".jpg";
    	        }
    	        else if (paymentProof.startsWith("data:image/webp"))
    	        {
    	            extension = ".webp";
    	        }

    	        if (paymentProof.contains(","))
    	        {
    	            paymentProof = paymentProof.substring(paymentProof.indexOf(",") + 1);
    	        }

    	        paymentProof = paymentProof.replace(' ', '+');

    	        paymentProof = paymentProof.replace("\r", "").replace("\n", "").replace("\t", "");

    	        byte[] fileBytes = Base64.getDecoder().decode(paymentProof);

    	        String fileName = "payment_proof_" + System.currentTimeMillis() + extension;

    	        paymentProofPath = fileName;

    	        InputStream in = new ByteArrayInputStream(fileBytes);

    	        obj.makeProfile(in, paymentProofPath);

    	        in.close();
    	    }
    	    catch (Exception e)
    	    {
    	        e.printStackTrace();

    	        paymentProofPath = "";
    	    }
    	}
        
        DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");

        if (sDate != null && !sDate.equals(""))
        {
            startDate = (Date) formatter.parse(sDate);
        }

        if (loanNo != null && loanNo.contains("/"))
        {
            loanNo = loanNo.substring(0, loanNo.indexOf("/"));
        }

        String loginStatus = obj.checkLoginIdStatus(employee);

        int i = 0;

        if (loginStatus.equalsIgnoreCase("active"))
        {
            i = new DatabaseMethods1().paymentRequest(branchId, employee, startDate, loanType, loanNo, amount, payMode, "NA", 
            										  transactionId, response, "", paymentProofPath);
        }
        else
        {
            i = -99;
        }

        if (savingAmount != null && !savingAmount.equalsIgnoreCase("") && Double.parseDouble(savingAmount) > 0 && 
        	loginStatus.equalsIgnoreCase("active"))
        {
            String shno = obj.shareHolderNoByLoanNo(loanNo);
            String svno = obj.savingAccountByShareHolderNo(shno);

            new DatabaseMethods1().paymentRequest(branchId, employee, startDate, "saving", svno, savingAmount, payMode, "deposit",
            									  transactionId, response, "");
        }

        if (Double.parseDouble(penaltyAmount) > 0 && loginStatus.equalsIgnoreCase("active"))
        {
            new DatabaseMethods1().paymentRequest(branchId, employee, startDate, "penalty", loanNo, penaltyAmount, payMode, "NA",
            									  transactionId, response, "");
        }

        if (Double.parseDouble(chequeBounceAmount) > 0 && loginStatus.equalsIgnoreCase("active"))
        {
            new DatabaseMethods1().paymentRequest(branchId, employee, startDate, "bounceCharge", loanNo, chequeBounceAmount, payMode, "NA",
            									  transactionId, response, "");
        }
        
        if (Double.parseDouble(rdAmount) > 0 && loginStatus.equalsIgnoreCase("active"))
        {
            new DatabaseMethods1().paymentRequest(branchId, employee, startDate, "RD", rdNumber, rdAmount, payMode, "NA",
                transactionId, response, "");
        }

        JSONObject mainobj = new JSONObject();

        JSONArray arr = new JSONArray();

        JSONObject resultObj = new JSONObject();

        String status = "";

        if (i >= 1)
        {
            status = "Payment Request Sent Successfully";

            sendMessage(branchId, employee, loanNo, amount, payMode, savingAmount, penaltyAmount);

            if (response != null && response.equalsIgnoreCase("success"))
            {
                String typeMessage = "Dear Sir, A Request of Payment Amount "
				                   + amount
				                   + "/- Receive From Payment Gateway. "
				                   + "Please Capture This Payment from Payment "
				                   + "Gateway. Thanks...";

                Connection conn = DataBaseConnection.JAVAConnection();

                String contactNo = new DataBaseMethods().contactNoForSchedularMsg(branchId, conn);

                new DataBaseMethods().runMessageUrl(branchId, contactNo, typeMessage, "System", "pending", conn);

                try
                {
                    conn.close();
                }
                catch (SQLException e)
                {
                    e.printStackTrace();
                }
            }
        }
        else if (i == -99)
        {
            status = "Your User ID Has been Blocked By Admin. ";
        }
        else
        {
            status = "Something went wrong.";
        }

        resultObj.put("st", status);

        arr.add(resultObj);

        mainobj.put("track", arr);

        json =
            mainobj.toJSONString();
    }

    
    
    private void addPenalty(int branchId, String employee, String lno, String penaltyAmount, String loanType)
    {
        Connection conn = DataBaseConnection.JAVAConnection();

        String loanLabel = obj.loanLabelByLoanValue(loanType);

        String paymentMode = "Cash";

        String voucherNo = obj.generateVoucherNo(branchId, "income_table", conn);

        int i = new DataBaseIncomeExpense().addIncome(branchId, startDate, "Other_Cr", paymentMode, penaltyAmount, "", "", "", 
									        		  null, "Receive Loan Penalty", "Receive Penalty", 0, "N/A", "0", 0,
									                  lno, loanLabel, voucherNo, "", 0, "active", "");

        
        if (i > 0)
        {
            if (paymentMode.equalsIgnoreCase("Cash"))
            {
                obj.decreaseSharedCompanyAmount(branchId, Double.parseDouble(penaltyAmount));
            }
        }
        
    }

 
    
    private void sendMessage(int branchId, String employee, String lno, String amount, String payMode,
			String savingAmount, String penaltyAmount) 
    {			
		double totalAmount = Double.parseDouble(savingAmount) + Double.parseDouble(amount)
				+ Double.parseDouble(penaltyAmount);

		Connection conn = DataBaseConnection.JAVAConnection();

		String check = obj.checkStatusInMessageSettingTable("Pay Loan Emi By App");
		
		if (check.equals("active")) {

			String shno = obj.shareHolderNoByLoanNo(lno);
			String name = obj.firstApplicantNameBySHNo(shno, conn);
			String contactNo = obj.applicantContactNoByShareHolderNo(shno, conn);
			
			boolean isDLT = dbmt.isDLTMessageApi(conn);
			
			if (isDLT) 
			{
				Map<String, String> variables = new HashMap<>();
				variables.put("name", name);
				variables.put("amount", String.valueOf(totalAmount));

				dbmt.sendDLTMessage(contactNo, null, variables, conn, "loan EMI payment");
			}
			else 
			{
				String typeMessage = "Dear " + name + ", Rs. " + totalAmount + " Submit Sucessfully By " + payMode;
				obj.runMessageUrl(branchId, contactNo, typeMessage, employee,
				        "1207161822711123650", conn);
			}

		} else {
			FacesContext.getCurrentInstance().addMessage(null,
					new FacesMessage("Message For This Module is not Active. "
							+ "Please Go to In Master Setting Module " + "and Active Message For This Module."));
		}

		try {
			conn.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

    // =============================================================
    // RENDER JSON
    // =============================================================

    public void renderJson() throws IOException
    {
        FacesContext facesContext =
            FacesContext.getCurrentInstance();

        ExternalContext externalContext =
            facesContext.getExternalContext();

        externalContext.setResponseContentType(
            "application/json"
        );

        externalContext.setResponseCharacterEncoding(
            "UTF-8"
        );

        externalContext
            .getResponseOutputWriter()
            .write(json);

        facesContext.responseComplete();
    }

    public String getJson()
    {
        return json;
    }

    public void setJson(String json)
    {
        this.json = json;
    }
}