using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.IO;
using System.Xml.Serialization;
using Newtonsoft.Json;

public partial class Admin_ManagePinePaymentStatus : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
       if (!IsPostBack)
        {
            lblMsg.Text = "";
            txtFrom.Text = DateTime.Now.ToString("yyyy-MM-dd");
            txtTo.Text = DateTime.Now.ToString("yyyy-MM-dd");
            GetPendingBillPostDetail();
        }
       
    }
    protected void Timer1_Tick(object sender, EventArgs e)
    {
        GetPendingBillPostDetail();

    }
    protected void btnFind_Click(object sender, EventArgs e)
    {
        if (txtFrom.Text.Trim() == "")
        {
            Page.RegisterStartupScript("XXX", "<script> alert('Please select From Date.')</script>");
            return;
        }
        else if (txtTo.Text.Trim() == "")
        {
            Page.RegisterStartupScript("XXX", "<script> alert('Please select To Date.')</script>");
            return;
        }
        else
        {
            GetPendingBillPostDetail();
        }
    }
    public void GetPendingBillPostDetail()
    {
        SqlParameter[] warlock = new SqlParameter[]
        {
         new SqlParameter("@From", Convert.ToString(txtFrom.Text)),
         new SqlParameter("@To", Convert.ToString(txtTo.Text))
        };
        DataSet ds = SqlHelper.GetDataSet(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "usp_GetPinePendingTxnDetails", warlock);
        if (ds.Tables[0].Rows.Count > 0)
        {
            gvPndTxn.DataSource = ds.Tables[0];
            gvPndTxn.DataBind();
           
        }
        else
        {
            gvPndTxn.DataSource = null;
            gvPndTxn.DataBind();
        }
        
    }
    protected void lnk_download_Rpt_Click(object sender, EventArgs e)
    {
        
    }

    public void ExportToExcel(DataTable dt)
    {
        if (dt.Rows.Count > 0)
        {
            string filename = "PendingPGTxnDetails.xls";
            System.IO.StringWriter tw = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
            DataGrid dgGrid = new DataGrid();
            dgGrid.DataSource = dt;
            dgGrid.DataBind();

            //Get the HTML for the control.
            dgGrid.RenderControl(hw);
            //Write the HTML back to the browser.
            //Response.ContentType = application/vnd.ms-excel;
            Response.ContentType = "application/vnd.ms-excel";
            Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
            this.EnableViewState = false;
            Response.Write(tw.ToString());
            Response.End();
        }
    }

    public override void VerifyRenderingInServerForm(Control control)
    {

    }

    protected void btnReProcess_Click(object sender, EventArgs e)
    {
        try
        {
            //CommonFunction obj_ComFun = new CommonFunction();
            //ReProcess objRePro = new ReProcess();
            Boolean flag = true;
            foreach (GridViewRow rowItem in gvPndTxn.Rows)
            {
                CheckBox chk = (CheckBox)(rowItem.Cells[0].FindControl("chkbox"));
                if (chk.Checked)
                {
                    string Response = "";
                    string MerTxn = Convert.ToString(gvPndTxn.DataKeys[rowItem.RowIndex].Values[0]);
                    string TxnAmt = Convert.ToString(gvPndTxn.DataKeys[rowItem.RowIndex].Values[1]);
                    string LoginId = Convert.ToString(gvPndTxn.DataKeys[rowItem.RowIndex].Values[2]);
                    string MobileNo = Convert.ToString(gvPndTxn.DataKeys[rowItem.RowIndex].Values[3]);
                    string pineRefId = Convert.ToString(gvPndTxn.DataKeys[rowItem.RowIndex].Values[5]);
                    string PaymentFor = Convert.ToString(gvPndTxn.DataKeys[rowItem.RowIndex].Values[6]);
                    if (PaymentFor.ToLower() == "topup")
                    {
                         Response = GetStatus(MerTxn, TxnAmt, LoginId, MobileNo, pineRefId);
                    }
                    else
                    {
                        Response = GetStatusElecticity(MerTxn, TxnAmt, LoginId, MobileNo, pineRefId);
                    }


                    lblMsg.Text = Response;
                    lblMsg.ForeColor = System.Drawing.Color.Red;
                    flag = false;
                }
            }
            if (flag)
            {
                lblMsg.Text = "Please Select Any Transaction";
                lblMsg.ForeColor = System.Drawing.Color.Red;
            }
            GetPendingBillPostDetail();
        }
        catch (Exception ex)
        {
            throw (ex);
        }
    }
    public void InsertServiceRequestResponseLog(string MethodName, string RequestLog, string ResponseLog)
    {
        try
        {
            SqlParameter[] warlock = new SqlParameter[]
            {
                new SqlParameter("@MethodName", MethodName),
                new SqlParameter("@RequestLog", RequestLog),
                new SqlParameter("@ResponseLog", ResponseLog)
            };
            SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "usp_Insert_ServiceRequestResponseLog", warlock);
        }
        catch (Exception ex)
        {
            throw ex;

        }
    }
    public void UpdateConsumerBillDetail(string TxnId, string ReceiptNo)
    {
        SqlParameter[] warlock = new SqlParameter[]
        {
                
                new SqlParameter("@TxnId",TxnId),
                new SqlParameter("@ReceiptNo",ReceiptNo)
        };
        SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, System.Data.CommandType.StoredProcedure, "usp_updateRepostPaymentStatus", warlock);
    }
    public int RefundTxnUnProcessedBill(string TxnId)
    {
        SqlParameter[] warlock = new SqlParameter[]
        {
                new SqlParameter("@TxnId",TxnId)
        };
       return SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, System.Data.CommandType.StoredProcedure, "usp_RejectTxn", warlock);
    }
    public bool CheckRefundValidation(string TxnId)
    {
        SqlParameter[] warlock = new SqlParameter[]
        {
                new SqlParameter("@TxnId",TxnId)
        };
        return  SqlHelper.checkExistance(SqlHelper.mainConnectionString, System.Data.CommandType.StoredProcedure, "usp_CheckTxnIsValid", warlock);
    }
    public string GetStatusElecticity(string TxnId, string amount, string LoginId, string ConsumerMobileNo, string PineRefId)
    {
        string Response = "";
        try
        {

            pineLab objpinelab = new pineLab();
            string result = objpinelab.PinelabPaymentStatus(PineRefId, amount);
            PineLabStatusResponse myDeserializedClass = JsonConvert.DeserializeObject<PineLabStatusResponse>(result);
            if (myDeserializedClass.ResponseMessage.ToUpper() == "SUCCESS")
            {
                if (myDeserializedClass.UPITxnData != null)
                {
                    if (myDeserializedClass.UPITxnData.TxnStatus.ToLower() == "pass")
                    {
                        UpdateCustomerPayment(TxnId,
                            myDeserializedClass.UPITxnData.RRN, myDeserializedClass.UPITxnData.HostTxnId,
                             "success", myDeserializedClass.UPITxnData.HostTID, myDeserializedClass.UPITxnData.HostMID, "", 
                            LoginId, myDeserializedClass.UPITxnData.TxnType, myDeserializedClass.UPITxnData.CustomerVPA);

                        Response = "Success";
                    }
                    
                    else if (myDeserializedClass.UPITxnData.TxnStatus.ToLower() == "fail")
                    {
                        UpdateCustomerPayment(TxnId,
                            myDeserializedClass.UPITxnData.RRN, myDeserializedClass.UPITxnData.HostTxnId,
                            "failed",  myDeserializedClass.UPITxnData.HostTID, myDeserializedClass.UPITxnData.HostMID, "", 
                            LoginId, myDeserializedClass.UPITxnData.TxnType, myDeserializedClass.UPITxnData.CustomerVPA);
                        Response = myDeserializedClass.UPITxnData.UPITxnStatusDesciption;
                    }
                }
                else if (myDeserializedClass.UPITxnData == null && myDeserializedClass.CardTxnData != null)
                {
                    if (myDeserializedClass.CardTxnData.TxnStatus.ToLower() == "pass")
                    {

                        UpdateCustomerPayment(TxnId,
                            myDeserializedClass.CardTxnData.RRN, myDeserializedClass.CardTxnData.TransactionLogId,
                            "success", myDeserializedClass.CardTxnData.BankTid, myDeserializedClass.CardTxnData.BankMid, myDeserializedClass.CardTxnData.CardHolderName, 
                            LoginId, myDeserializedClass.CardTxnData.CardType, myDeserializedClass.CardTxnData.MaskedPanNum);
                            //Response = myDeserializedClass.CardTxnData.ResponseMessage;
                            Response = "Success";
                        
                    }
                    else if (myDeserializedClass.CardTxnData.TxnStatus.ToLower() == "fail")
                    {
                        UpdateCustomerPayment(TxnId,
                                                    myDeserializedClass.CardTxnData.RRN, myDeserializedClass.CardTxnData.TransactionLogId,
                                                    "failed", myDeserializedClass.CardTxnData.BankTid, myDeserializedClass.CardTxnData.BankMid, myDeserializedClass.CardTxnData.CardHolderName,
                                                    LoginId, myDeserializedClass.CardTxnData.CardType, myDeserializedClass.CardTxnData.MaskedPanNum);
                        Response = myDeserializedClass.CardTxnData.ResponseMessage;
                    }
                    else if (myDeserializedClass.CardTxnData.TxnStatus.ToLower() == "pending")
                    {
                        if(myDeserializedClass.CardTxnData.ResponseMessage.ToLower() == "success")
                        {
                            UpdateCustomerPayment(TxnId,
                            myDeserializedClass.CardTxnData.RRN, myDeserializedClass.CardTxnData.TransactionLogId,
                            "success", myDeserializedClass.CardTxnData.BankTid, myDeserializedClass.CardTxnData.BankMid, myDeserializedClass.CardTxnData.CardHolderName,
                            LoginId, myDeserializedClass.CardTxnData.CardType, myDeserializedClass.CardTxnData.MaskedPanNum);
                            //Response = myDeserializedClass.CardTxnData.ResponseMessage;
                            Response = "Success";
                        }
                        
                    }

                }


            }
            else
            {
                Response = myDeserializedClass.ResponseMessage;
            }
        }
        catch (Exception ex)
        {
            Response = ex.Message;
        }

        return Response;
    }

    public void UpdateCustomerPayment(string TxnId, string BankReferenceCode, string BankID,
            string PaymentStatus, string TerminalID, string MId, string cardonName
           , string LoginId, string Feild1, string Feild2)
    {
        SqlParameter[] warlock = new SqlParameter[]
        {
                new SqlParameter("@BankReferenceCode",BankReferenceCode),
                new SqlParameter("@BankID",BankID),
                new SqlParameter("@PaymentStatus",PaymentStatus),
                new SqlParameter("@cardTxnTypeDesc",""),
                new SqlParameter("@TerminalID",TerminalID),
                new SqlParameter("@MId",MId),
                new SqlParameter("@nameOnCard",cardonName),
                new SqlParameter("@LoginId",LoginId),
                new SqlParameter("@Feild1",Feild1),
                new SqlParameter("@Feild2",Feild2),
                new SqlParameter("@TxnID",TxnId)
        };
        SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, System.Data.CommandType.StoredProcedure, "usp_UpdatePaymentPipe", warlock);
    }

    public string GetStatus(string TxnId,string amount,string LoginId,string ConsumerMobileNo,string PineRefId)
    {
        string Response = "";
        try
        {
         
            pineLab objpinelab = new pineLab();
            string result = objpinelab.PinelabPaymentStatus(PineRefId, amount);
            PineLabStatusResponse myDeserializedClass = JsonConvert.DeserializeObject<PineLabStatusResponse>(result);
            if (myDeserializedClass.ResponseMessage.ToUpper()=="SUCCESS")
            {
                if (myDeserializedClass.UPITxnData != null)
                {
                    if(myDeserializedClass.UPITxnData.TxnStatus.ToLower()=="pass")
                    {
                        int status1 = InsertTransactionWithtopupStatus("", TxnId, LoginId, "Topup", "NBDCL",
                                    "102", "All", ConsumerMobileNo, Convert.ToString(amount), " ", "NBDCL", "Orangepay", "Topup");
                        if(status1!=1)
                        {
                            iNSERTtOTPUPBillDetail(TxnId, amount,
                            myDeserializedClass.UPITxnData.RRN, myDeserializedClass.UPITxnData.HostTxnId,
                            "UPI", "success", "success", "PINELABS", "", myDeserializedClass.UPITxnData.HostTID, myDeserializedClass.UPITxnData.HostMID, "", "AdminGetStatusProcess",
                            LoginId, myDeserializedClass.UPITxnData.TxnType, myDeserializedClass.UPITxnData.CustomerVPA, myDeserializedClass.UPITxnData.TxnDateTime, "", "", ConsumerMobileNo);

                            Response = "Success";
                        }
                        else if(myDeserializedClass.UPITxnData.TxnStatus.ToLower() == "pass")
                        {
                            iNSERTtOTPUPBillDetail(TxnId, amount,
                            myDeserializedClass.UPITxnData.RRN, myDeserializedClass.UPITxnData.HostTxnId,
                            "UPI", "success", "success", "PINELABS", "", myDeserializedClass.UPITxnData.HostTID, myDeserializedClass.UPITxnData.HostMID, "", "AdminGetStatusProcess",
                            LoginId, myDeserializedClass.UPITxnData.TxnType, myDeserializedClass.UPITxnData.CustomerVPA, myDeserializedClass.UPITxnData.TxnDateTime, "", "", ConsumerMobileNo);

                            Response = "Success";
                        }

                    }
                    else if(myDeserializedClass.UPITxnData.TxnStatus.ToLower() == "fail") 
                    {
                        iNSERTtOTPUPBillDetail(TxnId, amount,
                            myDeserializedClass.UPITxnData.RRN, myDeserializedClass.UPITxnData.HostTxnId,
                            "UPI", "failed", "failed", "PINELABS", "", myDeserializedClass.UPITxnData.HostTID, myDeserializedClass.UPITxnData.HostMID, "", "AdminGetStatusProcess",
                            LoginId, myDeserializedClass.UPITxnData.TxnType, myDeserializedClass.UPITxnData.CustomerVPA, myDeserializedClass.UPITxnData.TxnDateTime, "", "", ConsumerMobileNo);
                        Response = myDeserializedClass.UPITxnData.UPITxnStatusDesciption;
                    }
                }
                else if (myDeserializedClass.UPITxnData == null && myDeserializedClass.CardTxnData != null)
                {
                    if (myDeserializedClass.CardTxnData.TxnStatus.ToLower() == "pass")
                    {
                        int status1 = InsertTransactionWithtopupStatus("", TxnId, LoginId, "Topup", "NBDCL",
                                                            "102", "All", ConsumerMobileNo, Convert.ToString(amount), " ", "NBDCL", "Orangepay", "Topup");
                        if (status1 != 1)
                        {
                            iNSERTtOTPUPBillDetail(TxnId, amount,
                            myDeserializedClass.CardTxnData.RRN, myDeserializedClass.CardTxnData.TransactionLogId,
                            "CARD", "success", "success", "PINELABS", "", myDeserializedClass.CardTxnData.BankTid, myDeserializedClass.CardTxnData.BankMid, myDeserializedClass.CardTxnData.CardHolderName, "AdminGetStatusProcess",
                            LoginId, myDeserializedClass.CardTxnData.CardType, myDeserializedClass.CardTxnData.MaskedPanNum, myDeserializedClass.CardTxnData.TxnDateTime, "", "", ConsumerMobileNo);
                            Response = myDeserializedClass.CardTxnData.ResponseMessage;
                        }
                        else if (myDeserializedClass.CardTxnData.TxnStatus.ToLower() == "pass")
                        {
                            iNSERTtOTPUPBillDetail(TxnId, amount,
                            myDeserializedClass.CardTxnData.RRN, myDeserializedClass.CardTxnData.TransactionLogId,
                            "CARD", "success", "success", "PINELABS", "", myDeserializedClass.CardTxnData.BankTid, myDeserializedClass.CardTxnData.BankMid, myDeserializedClass.CardTxnData.CardHolderName, "AdminGetStatusProcess",
                            LoginId, myDeserializedClass.CardTxnData.CardType, myDeserializedClass.CardTxnData.MaskedPanNum, myDeserializedClass.CardTxnData.TxnDateTime, "", "", ConsumerMobileNo);
                            //Response = myDeserializedClass.CardTxnData.ResponseMessage;
                            Response = "Success";
                        }
                    }
                    else if(myDeserializedClass.CardTxnData.TxnStatus.ToLower() == "fail")
                    {
                        iNSERTtOTPUPBillDetail(TxnId, amount,
                                                    myDeserializedClass.CardTxnData.RRN, myDeserializedClass.CardTxnData.TransactionLogId,
                                                    "CARD", "failed", "failed", "PINELABS", "", myDeserializedClass.CardTxnData.BankTid, myDeserializedClass.CardTxnData.BankMid, myDeserializedClass.CardTxnData.CardHolderName, "AdminGetStatusProcess",
                                                    LoginId, myDeserializedClass.CardTxnData.CardType, myDeserializedClass.CardTxnData.MaskedPanNum, myDeserializedClass.CardTxnData.TxnDateTime, "", "", ConsumerMobileNo);
                        Response = myDeserializedClass.CardTxnData.ResponseMessage;
                    }
                    else if(myDeserializedClass.CardTxnData.TxnStatus.ToLower() == "pending")
                    {
                        if (myDeserializedClass.CardTxnData.ResponseMessage.ToLower() == "success")
                        {
                            int status1 = InsertTransactionWithtopupStatus("", TxnId, LoginId, "Topup", "NBDCL",
                                                                "102", "All", ConsumerMobileNo, Convert.ToString(amount), " ", "NBDCL", "Orangepay", "Topup");
                            if (status1 != 1)
                            {
                                iNSERTtOTPUPBillDetail(TxnId, amount,
                                myDeserializedClass.CardTxnData.RRN, myDeserializedClass.CardTxnData.TransactionLogId,
                                "CARD", "success", "success", "PINELABS", "", myDeserializedClass.CardTxnData.BankTid, myDeserializedClass.CardTxnData.BankMid, myDeserializedClass.CardTxnData.CardHolderName, "AdminGetStatusProcess",
                                LoginId, myDeserializedClass.CardTxnData.CardType, myDeserializedClass.CardTxnData.MaskedPanNum, myDeserializedClass.CardTxnData.TxnDateTime, "", "", ConsumerMobileNo);
                                Response = myDeserializedClass.CardTxnData.ResponseMessage;
                            }
                            
                        }
                    }
                        
                }
                
                
            }
            else
            {
                Response = myDeserializedClass.ResponseMessage;
            }
        }
        catch(Exception ex)
        {
            Response = ex.Message;
        }

        return Response;
    }
    public void iNSERTtOTPUPBillDetail(string TxnId, string PaidAmount, string BankReferenceCode, string BankID,
            string PaymentMode, string PaymentStatus, string PostingStatus, string Gateway, string cardTxnTypeDesc, string TerminalID, string MId, string cardonName, string Remarks
            , string LoginId, string Feild1, string Feild2, string paymentDate = "", string latitude = "", string longitude = "", string ConsumerMobileNo = "")
    {
        SqlParameter[] warlock = new SqlParameter[]
        {
                new SqlParameter("@TxnId",TxnId),
                new SqlParameter("@PaidAmount",Convert.ToDecimal(PaidAmount)),
                new SqlParameter("@BankReferenceCode",BankReferenceCode),
                new SqlParameter("@BankID",BankID),
                new SqlParameter("@PaymentMode",PaymentMode),
                new SqlParameter("@PaymentStatus",PaymentStatus),
                new SqlParameter("@Gateway",Gateway),
                new SqlParameter("@TerminalID",TerminalID),
                new SqlParameter("@MId",MId),
                new SqlParameter("@nameOnCard",cardonName),
                new SqlParameter("@Remarks",Remarks),
                new SqlParameter("@LoginId",LoginId),
                new SqlParameter("@Feild1",Feild1),
                new SqlParameter("@Feild2",Feild2),
                new SqlParameter("@PaymentDate",paymentDate),
                new SqlParameter("@ConsumerMobileNo",ConsumerMobileNo),
                new SqlParameter("@ConsumerName",cardonName),
                new SqlParameter("@RequestFor","Topup")
        };
        SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, System.Data.CommandType.StoredProcedure, "usp_UpdatePGPaymentDetail", warlock);
    }
    public int InsertTransactionWithtopupStatus(string Ipaddress, string RefNo, string AgentId, string Type, string Operator, string OperatotId, string Circle, string MobileNo, string Amount, string VendorTxnId, string ServiceVendor, string PortalName, string ServiceName)
    {
        SqlParameter[] InsertWithPendingStatusParam = new SqlParameter[]
        {
            new SqlParameter("@IPAddress",Ipaddress),
            new SqlParameter("@ReferenceNumber",RefNo),
            new SqlParameter("@AgentID",Convert.ToInt64(AgentId)),
            new SqlParameter("@Type",Type.ToString()),
            new SqlParameter("@Operater",Operator),
            new SqlParameter("@operatorID",Convert.ToInt32(OperatotId)),
            new SqlParameter("@Circle",Circle),
            new SqlParameter("@Mobileno",Convert.ToString(MobileNo)),
            new SqlParameter("@Amount",Convert.ToDecimal(Amount)),
            new SqlParameter("@cptransactionid",VendorTxnId),
            new SqlParameter("@ServiceVendor",ServiceVendor),
            new SqlParameter("@PortalName",PortalName),
            new SqlParameter("@SERVICE_NAME",ServiceName),
            new SqlParameter("@ErrorMessage",SqlDbType.Int)
        };
        InsertWithPendingStatusParam[13].Direction = ParameterDirection.Output;
        SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "InsertWalletTransactionForTopup", InsertWithPendingStatusParam);
        int result = Convert.ToInt32(InsertWithPendingStatusParam[13].Value);
        return result;
    }

    protected void btnReject_Click(object sender, EventArgs e)
    {
        try
        {
            Boolean flag = true;
            foreach (GridViewRow rowItem in gvPndTxn.Rows)
            {
                CheckBox chk = (CheckBox)(rowItem.Cells[0].FindControl("chkbox"));
                if (chk.Checked)
                {

                    string MerTxn = Convert.ToString(gvPndTxn.DataKeys[rowItem.RowIndex].Values[0]);
                    if (CheckRefundValidation(MerTxn))
                    {
                      int a=  RefundTxnUnProcessedBill(MerTxn);
                    }

                    lblMsg.Text = "Transaction Refund Successfully";
                    lblMsg.ForeColor = System.Drawing.Color.Red;
                    flag = false;
                }
            }
            if (flag)
            {
                lblMsg.Text = "Please Select Any Transaction";
                lblMsg.ForeColor = System.Drawing.Color.Red;
            }
            GetPendingBillPostDetail();
        }
        catch (Exception ex)
        {
            throw (ex);
        }
    }
}