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

public partial class Agent_ElectricityNew : System.Web.UI.Page
{
    #region Declare private variable
    private string _loginID;
    #endregion
    AirEpointSupport _objTransaction = new AirEpointSupport();
    WBMobile_Noverification _ObjWBMNverify = new WBMobile_Noverification();
    DataSet ds = new DataSet();
    public string LoginID
    {
        get
        {
            return _loginID;
        }
        set
        {
            _loginID = value;
        }
    }
    public static string Token = "9f180b1b2a49d42aed015564fca83ef8";
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (string.IsNullOrEmpty(Convert.ToString(Session["LOGINID"])) && string.IsNullOrEmpty(Convert.ToString(Session["USERNAME"])))
            {
                Response.Redirect("../login.aspx");
            }
            else
            {

                LoginID = Convert.ToString(Session["LOGINID"]);
                if (!GetServiceActivation(LoginID))
                {
                    string message = "Electricity Bill Payment Service Coming Soon.";
                    string url = "Billpayment.aspx";
                    string script = "window.onload = function(){ alert('";
                    script += message;
                    script += "');";
                    script += "window.location = '";
                    script += url;
                    script += "'; }";
                    ClientScript.RegisterClientScriptBlock(this.GetType(), "Redirect", script, true);
                    //Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('Electricity Bill Payment Service Coming Soon. ');"), true);
                    //return;
                }
                if (!IsPostBack)
                {
                    BindElecticityBoard();
                }
            }
            lblerror.Text = Request.QueryString["error"];
            if (lblerror.Text == "Successfully completed.")
            {
                lblerror.ForeColor = Color.Blue;
            }
            else
            {
                lblerror.ForeColor = Color.Red;
            }
        }
        catch (Exception ex)
        {
            throw (ex);
        }
    }
    public bool GetServiceActivation(string LoginID)
    {
       // bool status = false;
       // status = SqlHelper.checkExistance(SqlHelper.mainConnectionString, CommandType.Text, "select LoginID from UtilityServiceActivation where LoginID='" + LoginID + "'");
        return true;
    }
    public void BindElecticityBoard()
    {
        try
        {

            DataSet ds = SqlHelper.GetDataSet(SqlHelper.mainConnectionString, CommandType.Text, "select MobileDthOperatorDetailsID,OperatorName,Operator_Code,'' Imagename  from APIBOXOPERATOR  order by OperatorName");
            if (ds.Tables[0].Rows.Count > 0)
            {
                ddlEleOpt.DataSource = ds.Tables[0];
                ddlEleOpt.DataTextField = "OperatorName";
                ddlEleOpt.DataValueField = "Operator_Code";
                ddlEleOpt.DataBind();
                ddlEleOpt.Items.Insert(0, new ListItem("--Select Electricity Board--", "0"));
                ddlEleOpt.SelectedIndex = 0;
            }
        }
        catch (Exception ex)
        {
        }
    }
    protected void ddlEleOpt_SelectedIndexChanged(object sender, EventArgs e)
    {
        try
        {
            if (ddlEleOpt.SelectedValue != "0")
            {

                //DataSet ds = SqlHelper.GetDataSet(SqlHelper.mainConnectionString, CommandType.Text, "select MobileDthOperatorDetailsID,OperatorName,Operator_Code,Imagename from MOBILE_DTH_OPERATOR_DETAILS where Type='ELECTRICITY'");
                //if (ds.Tables[0].Rows.Count > 0)
                //{
                //    ddlEleOpt.DataSource = ds.Tables[0];
                //    ddlEleOpt.DataTextField = "OperatorName";
                //    ddlEleOpt.DataValueField = "Operator_Code";
                //    ddlEleOpt.DataBind();
                //    ddlEleOpt.Items.Insert(0, new ListItem("--Select Electricity Board--", "0"));
                //    ddlEleOpt.SelectedIndex = 0;
                //}
            }
        }
        catch (Exception ex)
        {
        }
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {

        if (ddlEleOpt.SelectedValue != "0" && txtConsumerNo.Text != "" && txtMobileNo.Text.Trim() != "" )
        {
            string RefID = _objTransaction.Generate_TID();
            ViewState["RefId"] = RefID;
            if (ddlEleOpt.SelectedValue != "WBSE")
            {
                string p4="";
                    if (ddlEleOpt.SelectedValue == "JBE" ||ddlEleOpt.SelectedValue == "MSE" ||ddlEleOpt.SelectedValue == "REE")
                    {
                        if(txtSubDiv.Text.Trim()=="")
                        {
                            reset();
                            lblerror.Visible = true;
                            lblerror.Text = "Please enter all required field.";
                            return;
                        }
                        else{
                       p4=txtSubDiv.Text.Trim();
                        }
                    }
                    else
                    {
                        p4="";
                    }

                string posturl = "http://venusrecharge.co.in/FetchBill.aspx?authkey=10021&authpass=OrangePay@123&opcode="+ Convert.ToString(ddlEleOpt.SelectedValue) + "&Merchantrefno="+ RefID + "&ConsumerID="+ txtConsumerNo.Text.Trim() + "&SubDiv="+ p4 + "&ConsumerMobileNo="+ txtMobileNo.Text.Trim() + "&ServiceType=EB";
                InsrtLog(RefID, posturl, "FetchBillRequest");
                string Result = GetResponseUsingGetMethod(posturl);
                InsrtLog(RefID, Result, "ValidatePayment");
                if (Result != "")
                {
                    //JObject jsonResponse = JObject.Parse(Result);
                    //JObject Response_JObj = (JObject)jsonResponse["response"];
                    DataSet ds1 = new DataSet();
                    ds1.ReadXml(new StringReader(Result));
                    string OrdId, RechStatus, OpertorTxnID;
                    if (ds1.Tables[0].Rows.Count > 0)
                    {
                        RechStatus= Convert.ToString(ds1.Tables[0].Rows[0]["ResponseStatus"]);
                        if(RechStatus=="TXN" || RechStatus=="IRA" || RechStatus=="RCS")
                        {
                            ViewState["ResponseStatus"] = Convert.ToString(ds1.Tables[0].Rows[0]["ResponseStatus"]);
                            ViewState["ResultID"] = Convert.ToString(ds1.Tables[0].Rows[0]["OrderId"]);
                            lblBillNo.Text = Convert.ToString(ds1.Tables[0].Rows[0]["ConsumerID"]);
                            lblConsumerName.Text = Convert.ToString(ds1.Tables[0].Rows[0]["ConsumerName"]);
                            lblBillDueDate.Text = Convert.ToString(ds1.Tables[0].Rows[0]["DueDate"]);
                            lblDueAmount.Text = Convert.ToString(ds1.Tables[0].Rows[0]["DueAmount"]);
                            ViewState["BillAmount"] = Convert.ToString(ds1.Tables[0].Rows[0]["DueAmount"]);

                            if (RechStatus == "IRA")
                            {
                                chkboxpricediffernce.Visible = true;
                                chkboxpricediffernce.Text = "YOUR REQUEST AMOUNT IS DIFFER FROM ACTUAL DUE AMOUNT. DO YOU WANT TO PAY THIS ACTUAL BILL AMOUNT.";
                            }
                            ModalPopupExtender1.Show();
                        }
                        else
                        {
                            reset();
                            lblerror.Visible = true;
                            lblerror.Text = Convert.ToString(ds1.Tables[0].Rows[0]["Description"]); 
                        }
                    }
                    else
                    {
                        reset();
                        lblerror.Visible = true;
                        lblerror.Text = Result;
                    }
                }
                else
                {
                    reset();
                    lblerror.Visible = true;
                    lblerror.Text = "Server Error! Please try after some time.";
                }

            }
            else if (ddlEleOpt.SelectedValue == "WBSE")
            {
               // PaymentBill_Other(txtAmount.Text.Trim());
            }
        }
        else
        {
            string message = "Please Fill all details";
            string url = "#";
            string script = "window.onload = function(){ alert('";
            script += message;
            script += "');";
            script += "window.location = '";
            script += url;
            script += "'; }";
            ClientScript.RegisterClientScriptBlock(this.GetType(), "Redirect", script, true);
        }

    }
    public void InsrtLog(string RefId, string Log, string Service)
    {
        SqlParameter[] TxnResponce = new SqlParameter[]
                    {
                         new SqlParameter("@RefID",RefId),
                        new SqlParameter("@Log",Log),
                        new SqlParameter("@Service",Service)
                    };
        SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "InserLog", TxnResponce);
    }
    public void reset()
    {
        lblBillNo.Text = "";
        lblConsumerName.Text = "";
        lblBillDueDate.Text = "";
        lblDueAmount.Text = "";
        txtSubDiv.Text = "";
        txtConsumerNo.Text = "";
        txtMobileNo.Text = "";
        ddlEleOpt.SelectedValue = "0";
    }
    private string PostRequest(string url, string json)
    {
        string result = "";
        try
        {
            var httpWebRequest = (HttpWebRequest)WebRequest.Create(url);
            httpWebRequest.ContentType = "application/json";
            httpWebRequest.Method = "POST";
            using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
            {

                streamWriter.Write(json);
                streamWriter.Flush();
                streamWriter.Close();
            }
            var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
            using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
            {
                result = streamReader.ReadToEnd();
            }
            return result;
        }
        catch (Exception ex)
        {
            return result;
        }
    }

    public string GetResponseUsingGetMethod(string URL)
    {
        try
        {
            
            WebRequest request = HttpWebRequest.Create(URL);
            request.Method = "GET";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            Stream s = (Stream)response.GetResponseStream();
            StreamReader readStream = new StreamReader(s);
            string dataString = readStream.ReadToEnd();
            response.Close();
            s.Close();
            readStream.Close();
            return dataString;
        }
        catch (Exception ex)
        {
             return ex.Message;
        }
    }

    protected void btnTxnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            string BillAmount = string.Empty;
            //JObject BillDetails = (JObject)ViewState["BILLDETAILS"];
            if (Convert.ToString(ViewState["ResponseStatus"]) == "IRA")
            {
                if (chkboxpricediffernce.Checked == true)
                {
                    BillAmount = Convert.ToString(ViewState["BillAmount"]);
                }
                else
                {
                    reset();
                    lblerror.Visible = true;
                    lblerror.Text = "Invalid Bill Amount.";
                    return;
                }
            }
            else if (Convert.ToString(ViewState["ResponseStatus"]) == "TXN" || Convert.ToString(ViewState["ResponseStatus"]) == "RCS")
            {
                BillAmount = Convert.ToString(ViewState["BillAmount"]);
            }
            PaymentBill(BillAmount);

        }
        catch (Exception ex)
        {
		lblerror.Text = ex.Message;
            lblerror.Visible = true;
        }
    }
    public decimal WLAmount()
    {
        decimal WLbalance = 0;
        try
        {
            SqlParameter[] get_user_details = new SqlParameter[]
            {
                new SqlParameter("@LOGINID",Session["WhitelabelId"].ToString())
            };

            SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "udp_getavailablebalance", get_user_details);
            if (dr.Read())
            {
                WLbalance = Convert.ToInt32(dr["balance"]);
            }
            return WLbalance;
        }
        catch (Exception ex)
        {
            return WLbalance;
        }

    }
    public decimal userdetails()
    {
        decimal balance = 0;
        try
        {
            SqlParameter[] get_user_details = new SqlParameter[]
            {
                new SqlParameter("@LOGINID",LoginID)
            };
            SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "udp_getavailablebalance", get_user_details);
            if (dr.Read())
            {
                balance = Convert.ToDecimal(dr["balance"]);
            }
            return balance;
        }
        catch (Exception ex)
        {
            return balance;
        }
    }
    public decimal UserCutOffDetails()
    {
        decimal cutoffBalance = 0;
        try
        {
            SqlParameter[] get_user_details = new SqlParameter[]
            {
                new SqlParameter("@LOGINID",LoginID)
            };

            SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "udp_getcutoffbalance", get_user_details);
            if (dr.Read())
            {
                cutoffBalance = Convert.ToInt32(dr["CuttOffAmount"]);
            }
            return cutoffBalance;
        }
        catch (Exception ex)
        {
            return cutoffBalance;
        }
    }
    public void GetOperatorID(string Operator)
    {
        SqlParameter[] ONLINEOFFLINEOPERATOR = new SqlParameter[]
        {
            new SqlParameter("@opname", Operator),
            new SqlParameter("@OperatorType","ELECTRICITY")
        };
        DataSet ds = SqlHelper.GetDataSet(SqlHelper.mainConnectionString, CommandType.Text, "select MobileDthOperatorDetailsID,OperatorName,Operator_Code,'' Imagename  from APIBOXOPERATOR (NOLOCK) where Operator_Code='" + Operator + "'");
        if (ds.Tables[0].Rows.Count != 0)
        {
            ViewState["OperatorID"] = ds.Tables[0].Rows[0]["MobileDthOperatorDetailsID"];

        }

    }
    public void PaymentBill(string BillAmount)
    {
        try
        {
            decimal WLbalance = WLAmount();
            decimal ReqBalance = Convert.ToDecimal(BillAmount);
            decimal AgBalance = userdetails();
            decimal cutoffBalance = UserCutOffDetails();
            string RefNumber = string.Empty;
            string TXNID = string.Empty;
            string IPAdd = HttpContext.Current.Request.UserHostAddress.ToString();
            GetOperatorID(ddlEleOpt.SelectedValue.ToString());
            if (WLbalance > ReqBalance)
            {
                if (AgBalance > cutoffBalance)
                {
                    if (AgBalance > ReqBalance+cutoffBalance)
                    {
                        RefNumber = Convert.ToString(ViewState["RefId"]);
                        int status1 = CommonFunction.InsertTransactionWithPendingStatus(Session["WhitelabelId"].ToString(), IPAdd, RefNumber, LoginID, "ELECTRICITY", ddlEleOpt.SelectedItem.Text,
                                Convert.ToString(ViewState["OperatorID"]), "ALL", txtConsumerNo.Text, BillAmount, " ", "Venus", Session["PortalName"].ToString(), "Bill Payment");

                        if (status1 == 1)
                        {
                            reset();
                            lblerror.Visible = true;
                            lblerror.Text = "There is some technical problem .Please try again.";
                        }
                        else if (status1 == 2)
                        {

                            string p4 = "";
                            if (Convert.ToString(ddlEleOpt.SelectedValue) == "JBE" || Convert.ToString(ddlEleOpt.SelectedValue) == "MSE")
                            {
                                p4 = txtSubDiv.Text.Trim();
                            }
                            if (Convert.ToString(ddlEleOpt.SelectedValue) == "DHE" || Convert.ToString(ddlEleOpt.SelectedValue) == "UHE")
                            {
                                p4 = txtMobileNo.Text.Trim();
                            }
                            string url = "http://venusrecharge.co.in/PaymentBill.aspx?authkey=10021&authpass=OrangePay@123&opcode="+ Convert.ToString(ddlEleOpt.SelectedValue) + "&Merchantrefno="+ RefNumber + " &ConsumerID="+ txtConsumerNo.Text.Trim() + "&ConsumerMobileNo="+ txtMobileNo.Text.Trim() + "&ServiceType=EB&Amount ="+ ReqBalance + "&Orderid="+ Convert.ToString(ViewState["ResultID"]) + "&SubDiv="+ p4;
                             
                            InsrtLog(RefNumber, url, "BillPaymentRequest");
                            string Result = GetResponseUsingGetMethod(url);
                           InsrtLog(RefNumber, Result, "BillPaymentResponse");
                            SqlParameter[] TxnResponce = new SqlParameter[]
                            {
                                 new SqlParameter("@TXNRESPONCE",Result),
                                new SqlParameter("@REFRENCENO",RefNumber)
                            };
                            SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "USP_INSERTTXNRESPONCEFIRSTTIME", TxnResponce);

                            string res = Result;

                            if (true)
                            {
                                //JObject jsonResponse1 = JObject.Parse(res);
                                DataSet ds1 = new DataSet();
                                ds1.ReadXml(new StringReader(res));
                                string OrdId, RechStatus, OpertorTxnID;
                               // JObject jsonResponse = JObject.Parse(res);
                                if (Convert.ToString(ds1.Tables[0].Rows[0]["ResponseStatus"]) == "TXN")
                                {
                                    ViewState["OrderId"] = Convert.ToString(ds1.Tables[0].Rows[0]["OrderId"]);
                                    ViewState["Status"] = "Success";
                                    TXNID = Convert.ToString(ds1.Tables[0].Rows[0]["OperatorTxnId"]); 

                                    _ObjWBMNverify.FinalUpdate(Session["WhitelabelId"].ToString(), LoginID, RefNumber, Convert.ToString(ReqBalance), "Success", ViewState["Status"].ToString(), res, ViewState["OrderId"].ToString(), TXNID);
                                    reset();
                                    lblerror.Text = "Successfully Completed";
                                    lblerror.Visible = true;
                                }
                                else if (Convert.ToString(ds1.Tables[0].Rows[0]["ResponseStatus"]) == "TUP")
                                {
                                    ViewState["OrderId"] = Convert.ToString(ds1.Tables[0].Rows[0]["OrderId"]);
                                    ViewState["Status"] = "Pending";
                                    TXNID = Convert.ToString(ds1.Tables[0].Rows[0]["OperatorTxnId"]);

                                    _ObjWBMNverify.FinalUpdate(Session["WhitelabelId"].ToString(), LoginID, RefNumber, Convert.ToString(ReqBalance), "Pending", ViewState["Status"].ToString(), res, ViewState["OrderId"].ToString(), TXNID);
                                    reset();
                                    lblerror.Text = "Transaction Under Process";
                                    lblerror.Visible = true;
                                }
                                else
                                {
                                    ViewState["OrderId"] = Convert.ToString(ds1.Tables[0].Rows[0]["OrderId"]);
                                    ViewState["Status"] = "Failed";
                                    TXNID = "";

                                    _ObjWBMNverify.FinalUpdate(Session["WhitelabelId"].ToString(), LoginID, RefNumber, Convert.ToString(ReqBalance), "Fail", ViewState["Status"].ToString(), res, ViewState["OrderId"].ToString(), TXNID);
                                    reset();
                                    lblerror.Text = "Transaction Failed.";
                                    lblerror.Visible = true;
                                }
                            }
                        }
                    }
                    else
                    {
                        reset();
                        lblerror.Text = "You don’t have enough balance to do this transaction. Please take balance in your login.";
                        lblerror.Visible = true;
                    }
                }
                else
                {
                    reset();
                    lblerror.Text = "Your balance is low from cutoff balance. Please take balance in your login.";
                    lblerror.Visible = true;
                }
            }
            else
            {
                reset();
                lblerror.Text = "Your Administrator don’t have enough balance to do this transaction.";
                lblerror.Visible = true;
            }
        }
        catch (Exception ex)
        {
	    
        }
    }

   
    protected void ddlEleOpt_SelectedIndexChanged1(object sender, EventArgs e)
    {
        if (ddlEleOpt.SelectedValue == "JBE")
        {
            trsubdiv.Visible = true;
            txtSubDiv.ToolTip = "Please enter Subdivision Code (1-3 digits)";
            txtSubDiv.Attributes.Add("placeholder", "Please enter Subdivision Code (1-3 digits)");
        }
        else if (ddlEleOpt.SelectedValue == "MSE")
        {
            trsubdiv.Visible = true;
            txtSubDiv.ToolTip = "Please enter Billing Unit (4 digits)";
            txtSubDiv.Attributes.Add("placeholder", "Please enter Billing Unit (4 digits)");
        }
        else if (ddlEleOpt.SelectedValue == "REE")
        {
            trsubdiv.Visible = true;
            txtSubDiv.ToolTip = "Please enter Cycle Number (2 digits)";
            txtSubDiv.Attributes.Add("placeholder", "Please enter Cycle Number (2 digits)");
        }
        else
        {
            trsubdiv.Visible = false;
        }
    }
}