using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.SqlClient;
using System.Text;
using System.Drawing;
using System;

public partial class Agent_pancardN : System.Web.UI.Page
{
    string refrenceno, CouponValue, ResponseDate, address;
    int PanCardStatus;
    decimal balance, cutoffBalance, deduct;
    string IPAddress = HttpContext.Current.Request.UserHostAddress.ToString();
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (Session["LOGINID"] == null && Session["USERNAME"] == null)
            {
                Response.Redirect("../login.aspx");
            }
        }
        catch (Exception ex)
        {
            throw (ex);
        }
    }



    public void Get_Deducted_Pancard_Charge()
    {

        try
        {
            SqlParameter[] get_pancard_status = new SqlParameter[]
            {
                new SqlParameter("@DomainName",ConfigurationManager.AppSettings["WebsiteUrl"])
            };
            SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "spGetPancardCharge", get_pancard_status);
            if (dr.Read())
            {
               // deduct = Convert.ToDecimal(dr["WlSerChaInRS"]);

                deduct = Convert.ToDecimal(dr["UserSerCharInRS"]);
            }


        }
        catch (Exception ex)
        {

        }
    }
    public void userdetails()
    {
        try
        {
            SqlParameter[] get_user_details = new SqlParameter[]
            {
                new SqlParameter("@LOGINID",Session["LOGINID"].ToString())
            };
            SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "udp_getavailablebalance", get_user_details);
            if (dr.Read())
            {
                balance = Convert.ToDecimal(dr["balance"]);
            }
            //ViewState["leftbalance"]=Label5.Text;
        }
        catch (Exception ex)
        {
            Server.Transfer("Error.aspx?id=" + ex + "");
            //string st = ex.Message;
        }
    }


    public void GetStatusForPanCard()
    {
        try
        {
            SqlParameter[] get_pancard_status = new SqlParameter[]
            {
                new SqlParameter("@LOGINID",Session["LOGINID"].ToString())
            };
            SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "up_get_user_status_for_pancard", get_pancard_status);
            if (dr.Read())
            {
                PanCardStatus = Convert.ToInt32(dr["PanCardFlag"]);
            }
            //ViewState["leftbalance"]=Label5.Text;
        }
        catch (Exception ex)
        {
            Server.Transfer("Error.aspx?id=" + ex + "");
            //string st = ex.Message;
        }
    }

    public string RandomString(Random r, int len)
    {
        string str = "1234567890";
        StringBuilder sb = new StringBuilder();

        while ((len--) > 0)
            sb.Append(str[(int)(r.NextDouble() * str.Length)]);

        return sb.ToString();
    }

    public void GetCoupanDetails()
    {
        try
        {
            SqlParameter[] Coupan = new SqlParameter[] 
            {
            };
            DataSet ds = SqlHelper.GetDataSet(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "up_getCoupanNo", Coupan);
            if (ds.Tables[0].Rows.Count != 0)
            {
                CouponValue = Convert.ToString(ds.Tables[0].Rows[0]["CoupanNo"]);
            }
            else
            {
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('Coupon not available.');"), true);
            }
        }
        catch (Exception ex)
        {

        }
    }

    protected void btnPancard_Click1(object sender, EventArgs e)
    {
        try
        {
            if (txtMobNo.Text.Trim() == "")
            {
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('Please enter Mobile no.');"), true);
                return;
            }
            address = txtFlat.Text.Trim() + " " + txtStreet.Text.Trim() + " " + txtvillage.Text.Trim() + " " + txtArea.Text.Trim() + " " + txtCity.Text.Trim() + " " + ddlState.SelectedItem.Text + " " + txtPin.Text.Trim();
            //Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('Rs. 110.00 will be debit from your account as Pan Crad Fee. Are you sure want to continue!');"), true);
            ViewState["address"] = address;
            Session["Name"] = txtName.Text;
            Get_Deducted_Pancard_Charge();
            GetStatusForPanCard();
            if (PanCardStatus == 1)
            {
                if (WLAmount() > deduct)
                {
                    userdetails();
                    GetCoupanDetails();
                    if (CouponValue != null)
                    {
                        Session["CouponNo"] = CouponValue;
                        if ((balance - cutoffBalance) < deduct)
                        {
                            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('You don’t have enough balance to do this transaction. Please take balance in your login.');"), true);
                            return;
                        }
                        else
                        {
                            Session["CouponNo"] = CouponValue;
                            //   DeductAmountPanCardFees();
                            string RefNumber = TID_GEN();
                            string IPAddress = HttpContext.Current.Request.UserHostAddress.ToString();
                            int status1 =InsertTransactionWithPendingStatus(Session["WhitelabelId"].ToString(), IPAddress.ToUpper(), RefNumber, Convert.ToString(Session["LOGINID"]), "Pan Card", "Pan Card",
                               "57", "ALL", txtMobNo.Text.Trim(), Convert.ToString(deduct), " ", "PanService", Session["PortalName"].ToString(), "Pan Card", Convert.ToString(Session["CouponNo"]), txtName.Text.Trim(), Convert.ToString(ViewState["address"]));
                            if (status1 == 1)
                            {
                                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('There are some technical issues. Please try after some time');"), true);
                                // txtAddress.Text = "";
                                txtMobNo.Text = "";
                                txtName.Text = "";
                                return;
                            }
                            else if (status1 == 2)
                            {
                                Response.Redirect("PanAcknowledgement.aspx");
                            }

                        }
                    }
                    else
                    {
                        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('Coupon not available.');"), true);
                        //txtAddress.Text = "";
                        txtMobNo.Text = "";
                        txtName.Text = "";
                        return;
                    }
                }
                else
                {
                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('Your Administrator don’t have enough balance to do this transaction.');"), true);
                    txtMobNo.Text = "";
                    txtName.Text = "";
                    return;
                }
            }
            else
            {
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('Services Inactive, Pls contact Administrator.');"), true);
                // txtAddress.Text = "";
                txtMobNo.Text = "";
                txtName.Text = "";
                return;

            }
        }
        catch (Exception ex)
        {
            throw (ex);
        }
    }
    public decimal WLAmount()
    {
        try
        {
            decimal wlbalance=0;
            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.ToDecimal(dr["balance"]);
            }
            return wlbalance;
        }
        catch (Exception ex)
        {
            return 0;
        }
    }
    public static string TID_GEN()
    {
        string new_tid = System.Guid.NewGuid().ToString();
        new_tid = new_tid.Replace("-", string.Empty).ToLower();
        new_tid = new_tid.Substring(0, 14).Replace("a", "1");
        new_tid = new_tid.Substring(0, 14).Replace("b", "2");
        new_tid = new_tid.Substring(0, 14).Replace("c", "3");
        new_tid = new_tid.Substring(0, 14).Replace("d", "4");
        new_tid = new_tid.Substring(0, 14).Replace("e", "5");
        new_tid = new_tid.Substring(0, 14).Replace("f", "6");
        new_tid = new_tid.Substring(0, 14).Replace("g", "7");
        new_tid = new_tid.Substring(0, 14).Replace("h", "8");
        new_tid = new_tid.Substring(0, 14).Replace("i", "9");
        new_tid = new_tid.Substring(0, 14).Replace("j", "0");
        new_tid = new_tid.Substring(0, 14).Replace("k", "1");
        new_tid = new_tid.Substring(0, 14).Replace("l", "2");
        new_tid = new_tid.Substring(0, 14).Replace("m", "3");
        new_tid = new_tid.Substring(0, 14).Replace("n", "4");
        new_tid = new_tid.Substring(0, 14).Replace("o", "5");
        new_tid = new_tid.Substring(0, 14).Replace("p", "0");
        new_tid = new_tid.Substring(0, 14).Replace("q", "9");
        new_tid = new_tid.Substring(0, 14).Replace("r", "8");
        new_tid = new_tid.Substring(0, 14).Replace("s", "7");
        new_tid = new_tid.Substring(0, 14).Replace("t", "6");
        new_tid = new_tid.Substring(0, 14).Replace("u", "5");
        new_tid = new_tid.Substring(0, 14).Replace("v", "4");
        new_tid = new_tid.Substring(0, 14).Replace("w", "3");
        new_tid = new_tid.Substring(0, 14).Replace("x", "2");
        new_tid = new_tid.Substring(0, 14).Replace("y", "1");
        new_tid = new_tid.Substring(0, 14).Replace("z", "0");
        return new_tid;
    }
    private void DeductAmountPanCardFees()
    {
        Random rand = new Random();
        rand.Next(0, 1);
        for (int i = 0; i <= 1; i++)
        {
            refrenceno = RandomString(rand, 15);
            //lbluniqueid.Text = abc;
        }
        SqlParameter[] pancardservice = new SqlParameter[] 
        {
            new SqlParameter("@CoupanNo",CouponValue),
            new SqlParameter("@AgentID",Session["LOGINID"].ToString()),
            new SqlParameter("@name",txtName.Text.Trim()),
            new SqlParameter("@mobile",txtMobNo.Text.Trim()),
            new SqlParameter("@custAddress",Convert.ToString(ViewState["address"])),
            new SqlParameter("@IPAddress",IPAddress),
            new SqlParameter("@ReferenceNumber",refrenceno),
            new SqlParameter("@servicetype","Pan Card"),
            new SqlParameter("@circle","All Circle"),
            new SqlParameter("@operator","Pan Card"),
            new SqlParameter("@accountno",""),
            new SqlParameter("@amount",deduct),
            new SqlParameter("@ErrorMessage",SqlDbType.Int)
        };
        pancardservice[12].Direction = ParameterDirection.Output;
        SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "[udp_Pan_Card_Services_new]", pancardservice);
        int result = Convert.ToInt32(pancardservice[12].Value);
        if (result == 1)
        {
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("There is some technical problem .Please try again"), true);
            return;
        }
        else
        {
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("Pan card details process successfully"), true);
            return;

        }
    }

    public void UserCutOffDetails()
    {
        try
        {
            SqlParameter[] get_user_details = new SqlParameter[]
            {
                new SqlParameter("@LOGINID",Session["LOGINID"].ToString())
            };

            SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "udp_getcutoffbalance", get_user_details);
            if (dr.Read())
            {
                cutoffBalance = Convert.ToInt32(dr["CuttOffAmount"]);
            }
        }
        catch (Exception ex)
        {
            string st = ex.Message;
        }
    }
    protected void btnback_Click(object sender, EventArgs e)
    {
        Response.Redirect("PanCardDetail.aspx");
    }

    public static int InsertTransactionWithPendingStatus(string WLID, 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,string CoupanCode,string Custname,string custAdd)
    {
        SqlParameter[] InsertWithPendingStatusParam = new SqlParameter[]
        {
            new SqlParameter("@WLID",Convert.ToInt64(WLID)),
            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.ToInt64(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("@CoupanNo",CoupanCode),
            new SqlParameter("@name",Custname),
            new SqlParameter("@custAddress",custAdd),
            new SqlParameter("@ErrorMessage",SqlDbType.Int)
        };
        InsertWithPendingStatusParam[17].Direction = ParameterDirection.Output;
        SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "Insert_Pancard_Utility_Transaction", InsertWithPendingStatusParam);
        int result = Convert.ToInt32(InsertWithPendingStatusParam[17].Value);
        return result;
    }
}