using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Data;
using System.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using TrainService;

public partial class TrainService_PaymentRequest : System.Web.UI.Page
{
    string InputRequest;
    string[] arryStr = null;
    TrainResponseDetails Train_ResponseDetails = default(TrainResponseDetails);
    //TrainResponseDetails Train_ResponseDetails;
    string _encResponseString = string.Empty;
    string bookPageTitle, description, sno, bookKeywords;
    protected void Page_Load(object sender, EventArgs e)
    {

       // if (Request.QueryString.Count > 0)
        if (Request.Form["encdata"]!=null)
        {
            InputRequest = Request.Form["encdata"];//Request.QueryString["encdata"];
            InsertLog("PaymentRequest", InputRequest);
            string strAfterDecryption = DecryptStringFromBytes_Aes(ParseHex(InputRequest), "abfb7c8d48dfc4f1ce7ed92a44989f25", "232fcfdc2e2b4767");
            if (!strAfterDecryption.ToLower().Contains("merchantCode="))
            {
                strAfterDecryption=strAfterDecryption.Insert(0, "merchantCode=");
            }
            //merchantCode=CRIS|reservationId=1100012345|txnAmount=458.00|currencyType=INR|appCode=BOOKING|pymtMode=Internet|txnDate=20111206|securityId=CRIS|RU=https://localhost:8080/eticketing/BankResponse|checkSum=1EF7C9AA4C9CF912C1539AE332E997E15019E40010A59363064C9C308EA13873
            InsertLog("PaymentReqDecrypt", strAfterDecryption);
            try
            {
                NameValueCollection ResponseString = new NameValueCollection();
                arryStr = strAfterDecryption.Split('|');
                for (Int16 i = 0; i <= arryStr.Length - 1; i++)
                {
                    string[] ArrString = arryStr[i].ToString().Split('=');
                    ResponseString.Add(ArrString[0], ArrString[1]);
                }
                    Train_ResponseDetails = new TrainResponseDetails();
                    Train_ResponseDetails.merchantCode = ResponseString["merchantCode"];
                    Train_ResponseDetails.reservationId = ResponseString["reservationId"];
                    Train_ResponseDetails.txnAmount = ResponseString["txnAmount"];
                    Train_ResponseDetails.currencyType = ResponseString["currencyType"];
                    Train_ResponseDetails.appCode = ResponseString["appCode"];
                    Train_ResponseDetails.pymtMode = ResponseString["pymtMode"];
                    Train_ResponseDetails.txnDate = ResponseString["txnDate"];
                    Train_ResponseDetails.securityId = ResponseString["securityId"];
                    Train_ResponseDetails.RU = ResponseString["RU"];
                   
                    //string flag = InsertTrainBookingDetails(TrainResponseDetails);
                 
               // }
              // Response.Redirect("Login.aspx?" + Convert.ToString(ResponseString["merchantCode"]));

                //GetWhitelabelDetails();
                //Category_Name();
                if (ResponseString["merchantCode"].ToString().ToUpper() == "CRISVENUS" || ResponseString["merchantCode"].ToString().ToUpper() == "SVENUS")
                {
                    //login("ag80297", "12344321", Train_ResponseDetails);
                   // Response.Redirect("Login.aspx?" + Convert.ToString(ResponseString["merchantCode"]));
                    GetWhitelabelDetails();
                    Category_Name();
                    getmessage();
                   Session["TrainResponseDetails"]= Train_ResponseDetails;
                }



               
            }
            catch(Exception ex)
            {
            }
        }

    }
    public void getmessage()
    {
        try
        {
            SqlParameter[] getmess = new SqlParameter[] { };
            SqlDataReader Dr = SqlHelper.ExecuteReader(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "udp_ShowActiveMessage", getmess);

            if (Dr.Read())
            {
                lblmessage.Visible = true;
                lblheading.Text = Convert.ToString(Dr["msgHeading"]);
                lblmessage.Text = Convert.ToString(Dr["AddContent"]);
            }
            else
            {
                lblmessage.Visible = false;
            }
	    Dr.Close();
            Dr.Dispose();
        }
        catch (Exception ex)
        {
            lblerror.Text = "There is some technical error, Please try after some time";
            lblerror.ForeColor = Color.Red;
        }
    }
    private void Category_Name()
    {
        SqlParameter[] param_subscription = new SqlParameter[]
        {
            new SqlParameter("@domainname","http://venusrecharge.in"),
        };
        DataSet objDs = SqlHelper.GetDataSet(SqlHelper.mainConnectionString, CommandType.Text, "select AgentPanelTitle from WhiteLebelCorporateDetail where courentlevel=" + Convert.ToInt32(Session["WhitelabelId"].ToString()) + "", null);
        if (objDs.Tables[0].Rows.Count != 0)
        {
            foreach (DataRow dr in objDs.Tables[0].Rows)
            {
                bookPageTitle += dr["AgentPanelTitle"].ToString() + "/";
                string abcd = bookPageTitle;
            }
            HtmlMeta myMetaKeyWords = new HtmlMeta();
            myMetaKeyWords.Name = description;
            string category = lbltest.Text.Trim();
            string categoryname = category;
            myMetaKeyWords.Content = sno;
            Page.Header.Controls.Add(myMetaKeyWords);
        }
        getPageTitle();
    }
    private void getPageTitle()
    {
        bookPageTitle = "http://venusrecharge.in/" + bookPageTitle;
        Page.Title = bookPageTitle.ToString();
    }
    public void InsertLog(string ServiceName, string Log)
    {
        SqlParameter[] warlock = new SqlParameter[]
        {
            new SqlParameter("@ServiceName",ServiceName),
            new SqlParameter("@LogData",Log)
        };
        int a = SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "Insert_Train_Log", warlock);
    }
    public  byte[] ParseHex(string hex)
    {
        int offset = hex.StartsWith("0x") ? 2 : 0;
        if ((hex.Length % 2) != 0)
        {
            throw new ArgumentException("Invalid length: " + hex.Length);
        }
        byte[] ret = new byte[(hex.Length - offset) / 2];

        for (int i = 0; i < ret.Length; i++)
        {
            ret[i] = (byte)((ParseNybble(hex[offset]) << 4)
                             | ParseNybble(hex[offset + 1]));
            offset += 2;
        }
        return ret;
    }

    public int ParseNybble(char c)
    {
        if (c >= '0' && c <= '9')
        {
            return c - '0';
        }
        if (c >= 'A' && c <= 'F')
        {
            return c - 'A' + 10;
        }
        if (c >= 'a' && c <= 'f')
        {
            return c - 'a' + 10;
        }
        throw new ArgumentException("Invalid hex digit: " + c);
    }
    public string DecryptStringFromBytes_Aes(byte[] input, string key, string ivString)
    {
        byte[] cipherTextCombined = input;
        byte[] Key;
        byte[] IV;
        IV = Encoding.UTF8.GetBytes(ivString);
        Key = Encoding.UTF8.GetBytes(key);
        string plaintext = null;

        using (Aes aesAlg = Aes.Create())
        {
            aesAlg.Key = Key;
            byte[] cipherText = new byte[cipherTextCombined.Length - IV.Length];
            Array.Copy(cipherTextCombined, IV, IV.Length);
            Array.Copy(cipherTextCombined, IV.Length, cipherText, 0, cipherText.Length);
            aesAlg.IV = IV;
            aesAlg.Mode = CipherMode.CBC;
            // Create a decrytor to perform the stream transform.
            ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
            // Create the streams used for decryption. 
            using (var msDecrypt = new MemoryStream(cipherText))
            {
                using (var csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (var srDecrypt = new StreamReader(csDecrypt))
                    {
                        // Read the decrypted bytes from the decrypting stream
                        // and place them in a string.
                        plaintext = srDecrypt.ReadToEnd();
                    }
                }
            }

        }
        return plaintext;
    }
    //public string InsertTrainBookingDetails(TrainResponseDetails TrainResponseDetails)
    //{
    //    string Flag = string.Empty;
    //    SqlParameter[] warlock = new SqlParameter[]
    //    {
    //        new SqlParameter("@merchantCode",TrainResponseDetails.merchantCode),
    //        new SqlParameter("@reservationId",TrainResponseDetails.reservationId),
    //        new SqlParameter("@txnAmount",TrainResponseDetails.txnAmount),
    //        new SqlParameter("@currencyType",TrainResponseDetails.currencyType),
    //        new SqlParameter("@appCode",TrainResponseDetails.appCode),
    //        new SqlParameter("@pymtMode",TrainResponseDetails.pymtMode),
    //        new SqlParameter("@txnDate",TrainResponseDetails.txnDate),
    //        new SqlParameter("@securityId",TrainResponseDetails.securityId),
    //        new SqlParameter("@RU",TrainResponseDetails.RU),
    //        new SqlParameter("@Status","Pending"),

    //    };
    //    return Flag;
    //}


    private void GetWhitelabelDetails()
    {
        try
        {
            SqlParameter[] check_DomainName = new SqlParameter[]
            {
                new SqlParameter("@DomainName","http://venusrecharge.in")
            };
            DataSet ds = SqlHelper.GetDataSet(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "usp_GetWhiteLabelDetails", check_DomainName);
            if (ds.Tables[0].Rows.Count != 0)
            {
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    Session["headerlogoimage"] = dr[0].ToString();
                    Session["helpdeskmobileno"] = dr[1].ToString();
                    Session["helpdeskemailid"] = dr[2].ToString();
                    Session["copyright"] = dr[3].ToString();
                    Session["HelpDeskMobileNoAlter"] = dr[4].ToString();
                    Session["WhitelabelId"] = dr[5].ToString();
                    Session["CompanyName"] = dr[6].ToString();
                    Session["PortalName"] = dr[7].ToString();
                    Session["agentimage"] = "~/images/logo.png";
                }
            }
            lblimage.Text = Session["headerlogoimage"].ToString();
        }
        catch (Exception ex)
        {

        }
    }
    public void login(string userid, string pass, TrainResponseDetails Train_ResponseDetails)
    {

        try
        {
            SqlParameter[] check_login_details = new SqlParameter[]
                {
                    new SqlParameter("@DomailName","http://venusrecharge.in"), 
                    new SqlParameter("@User_details",userid),
                    new SqlParameter("@Password",pass),
                    new SqlParameter("@ErrorResult",SqlDbType.Int),
                };
            check_login_details[3].Direction = ParameterDirection.Output;
            DataSet ds = SqlHelper.GetDataSet(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "UDP_CHECK_USERLOGIN_DETAILS_New_WithOutUserType", check_login_details);
            int loginvariable = Convert.ToInt32(check_login_details[3].Value);
            if (loginvariable == 1)
            {
                if (ds.Tables[0].Rows.Count != 0 & loginvariable == 1)
                {
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        Session["LOGINID"] = dr[0].ToString();
                        Session["USERTYPE"] = dr[3].ToString();
                        Session["MobileNo"] = dr[4].ToString();
                        if (Session["USERTYPE"].Equals("Agent"))
                        {
                            //Response.Redirect("PaymentPage.aspx", false);
                            Payment(Train_ResponseDetails);
                        }

                    }
                }
                else
                {
                    FailedTrxn(Train_ResponseDetails);
                    //Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('You have entered invalid login details, please login with correct details.!');"), true);
                }
            }
            if (loginvariable == 2)
            {
                FailedTrxn(Train_ResponseDetails); // Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('Your account has been deactivate. Please contact Helpdesk');"), true);
            }
            if (loginvariable == 3)
            {
                FailedTrxn(Train_ResponseDetails);//Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('You are not authorize user for this portal. Please contact Helpdesk');"), true);
            }
        }
        catch (Exception ex)
        {
            FailedTrxn(Train_ResponseDetails);//Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('You have entered invalid login details, please login with correct details.!');"), true);     
        }

    }
    public void FailedTrxn(TrainResponseDetails Train_ResponseDetails)
    {
        string ResponseData = "resrvationId=" + Train_ResponseDetails.reservationId + "|bankTxnId= " + Generate_TID() + "|txnAmount=" + Train_ResponseDetails.txnAmount + "| status=1|statusDesc=Fail";
        string checksum = GenerateCheckSum(ResponseData);
        ResponseData += "|checkSum=" + checksum;
        InsertLog("PaymentResD", ResponseData);
        _encResponseString = EncryptAPP(ResponseData, "abfb7c8d48dfc4f1ce7ed92a44989f25", "232fcfdc2e2b4767");
        PostData(Train_ResponseDetails.RU, _encResponseString);
    }
    public void Payment(TrainResponseDetails Train_ResponseDetails)
    {
        string ResponseData = string.Empty, checksum, BankTxnId;
        decimal WL_Amount = Convert.ToDecimal(WLAmount());
        decimal ReqBal = Convert.ToDecimal(Train_ResponseDetails.txnAmount);
        decimal AgBal = Convert.ToDecimal(AgentBalance());
        decimal CutOffBal = Convert.ToDecimal(UserCutOffDetails());
        BankTxnId = Generate_TID();
        if (WL_Amount > ReqBal)
        {
            if (AgBal > CutOffBal)
            {
                if (ReqBal < (AgBal - CutOffBal))
                {
                    int status1 = CommonFunction.InsertTransactionWithPendingStatus(Session["WhitelabelId"].ToString(), "127.0.0.1", BankTxnId, Convert.ToString(Session["LOGINID"]), "Train", "Train", "64", "ALL", "8802024429", Convert.ToString(Train_ResponseDetails.txnAmount), Convert.ToString(Train_ResponseDetails.reservationId), "IRCTC_NGeT_RDS", Session["PortalName"].ToString(), "Train Reservation");
                   // int status1 = CommonFunction.InsertTransactionWithPendingStatus(Session["WhitelabelId"].ToString(), "", BankTxnId, Convert.ToString(Session["LOGINID"]), "Train", "Train", Convert.ToString(Train_ResponseDetails.reservationId), "ALL", "", Convert.ToString(Train_ResponseDetails.txnAmount), " ", "IRCTC_NGeT_RDS", Session["PortalName"].ToString(), "Train Reservation");
                    if (status1 == 1)
                    {
                        ResponseData = "resrvationId=" + Train_ResponseDetails.reservationId + "|bankTxnId= " + BankTxnId + "|txnAmount=" + Train_ResponseDetails.txnAmount + "| status=2|statusDesc=Technical Issue";
                        checksum = GenerateCheckSum(ResponseData);
                        ResponseData += "|checkSum=" + checksum;
                        PostResponse(ResponseData, Train_ResponseDetails);
                        return;
                    }
                    else if (status1 == 2)
                    {
                        InsertTrainBookingDetails(Train_ResponseDetails, BankTxnId);
                        ResponseData = "resrvationId=" + Train_ResponseDetails.reservationId + "|bankTxnId= " + BankTxnId + "|txnAmount=" + Train_ResponseDetails.txnAmount + "| status=0|statusDesc=Success";
                        checksum = GenerateCheckSum(ResponseData);
                        ResponseData += "|checkSum=" + checksum;
                        PostResponse(ResponseData, Train_ResponseDetails);
                        return;
                    }
                }
                else
                {
                    ResponseData = "resrvationId=" + Train_ResponseDetails.reservationId + "|bankTxnId= " + BankTxnId + "|txnAmount=" + Train_ResponseDetails.txnAmount + "| status=2|statusDesc=Low balance";
                    checksum = GenerateCheckSum(ResponseData);
                    ResponseData += "|checkSum=" + checksum;
                    PostResponse(ResponseData, Train_ResponseDetails);
                    return;
                }
            }
            else
            {
                ResponseData = "resrvationId=" + Train_ResponseDetails.reservationId + "|bankTxnId= " + BankTxnId + "|txnAmount=" + Train_ResponseDetails.txnAmount + "| status=2|statusDesc=Low cutoff balance";
                checksum = GenerateCheckSum(ResponseData);
                ResponseData += "|checkSum=" + checksum;
                PostResponse(ResponseData, Train_ResponseDetails);
                return;
            }
        }
        else
        {
            ResponseData = "resrvationId=" + Train_ResponseDetails.reservationId + "|bankTxnId= " + BankTxnId + "|txnAmount=" + Train_ResponseDetails.txnAmount + "| status=2|statusDesc=Low balance on Administrator";
            checksum = GenerateCheckSum(ResponseData);
            ResponseData += "|checkSum=" + checksum;
            PostResponse(ResponseData, Train_ResponseDetails);
            return;
        }
    }
    public string Generate_TID()
    {
        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");

        if (new_tid[0] == '0')
        {
            string s = new_tid.Substring(1, new_tid.Length - 1);
            new_tid = "9" + s;
        }

        return new_tid;
    }
    public void InsertTrainBookingDetails(TrainResponseDetails TrainResponseDetails, string TxnId)
    {
        //string Flag = string.Empty;
        SqlParameter[] warlock = new SqlParameter[]
        {
            new SqlParameter("@merchantCode",Convert.ToString(TrainResponseDetails.merchantCode)),
            new SqlParameter("@reservationId",Convert.ToString(TrainResponseDetails.reservationId)),
            new SqlParameter("@txnAmount",Convert.ToString(TrainResponseDetails.txnAmount)),
            new SqlParameter("@currencyType",Convert.ToString(TrainResponseDetails.currencyType)),
            new SqlParameter("@appCode",Convert.ToString(TrainResponseDetails.appCode)),
            new SqlParameter("@pymtMode",Convert.ToString(TrainResponseDetails.pymtMode)),
            new SqlParameter("@txnDate",Convert.ToString(TrainResponseDetails.txnDate)),
            new SqlParameter("@securityId",Convert.ToString(TrainResponseDetails.securityId)),
            new SqlParameter("@RU",Convert.ToString(TrainResponseDetails.RU)),
            new SqlParameter("@Status","Pending"),
            new SqlParameter("@TransactionId",TxnId)
        };
        SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "InsertTrainTransaction", warlock);

    }
    public void PostData(string Url, string PostData)
    {
        string strUrl = Url + "?encdata=" + PostData;
        //string strUrl = "http://localhost:1045/venusrecharge.in/TrainService.aspx?encdata=" + PostData;
        InsertLog("PaymentResE", strUrl);
        WebRequest request = HttpWebRequest.Create(strUrl);
        request.Method = "POST";
        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();
    }
    public void PostResponse(string RequestString, TrainService.TrainResponseDetails TrainResponseDetails)
    {
        InsertLog("PaymentResD", RequestString);
        _encResponseString = EncryptAPP(RequestString, "abfb7c8d48dfc4f1ce7ed92a44989f25", "232fcfdc2e2b4767");
        PostData(TrainResponseDetails.RU, _encResponseString);
    }
    public static string GenerateCheckSum(string text)
    {
        UTF8Encoding encoder = new UTF8Encoding();

        byte[] hashValue = null;
        byte[] message = encoder.GetBytes(text);

        SHA256Managed hashString = new SHA256Managed();
        string hex = "";

        hashValue = hashString.ComputeHash(message);
        foreach (byte x in hashValue)
        {
            hex += String.Format("{0:x2}", x);
        }
        return hex.ToUpper();
    }
    public int WLAmount()
    {
	SqlDataReader dr=null;
        try
        {
            SqlParameter[] get_user_details = new SqlParameter[]
            {
                new SqlParameter("@LOGINID",Session["WhitelabelId"].ToString())
            };

            dr = SqlHelper.ExecuteReader(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "udp_getavailablebalance", get_user_details);
            if (dr.Read())
            {
                return Convert.ToInt32(dr["balance"]);
            }
            else
            {
                return 0;
            }
        }
        catch (Exception ex)
        {
            return 0;
        }
        finally
        {
            dr.Close();
        }
    }
    public int UserCutOffDetails()
    {
	SqlDataReader dr=null;
        try
        {
            SqlParameter[] get_user_details = new SqlParameter[]
            {
                new SqlParameter("@LOGINID",Convert.ToString(Session["LOGINID"]))
            };

            dr = SqlHelper.ExecuteReader(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "udp_getcutoffbalance", get_user_details);
            if (dr.Read())
            {
                return Convert.ToInt32(dr["CuttOffAmount"]);
            }
            else
            {
                return 0;
            }
        }
        catch (Exception ex)
        {
            return 0;
        }
	finally
        {
            dr.Close();
        }
    }
    public string EncryptAPP(string textToEncrypt, string key, string ivString)
    {
        RijndaelManaged rijndaelCipher = new RijndaelManaged();
        rijndaelCipher.Mode = CipherMode.CBC;
        rijndaelCipher.Padding = PaddingMode.PKCS7;

        rijndaelCipher.KeySize = 0x80;
        rijndaelCipher.BlockSize = 0x80;
        byte[] pwdBytes = Encoding.UTF8.GetBytes(key);
        byte[] keyBytes = new byte[32];
        int len = pwdBytes.Length;
        if (len > keyBytes.Length)
        {
            len = keyBytes.Length;
        }
        Array.Copy(pwdBytes, keyBytes, len);
        byte[] iv = Encoding.UTF8.GetBytes(ivString);
        rijndaelCipher.Key = keyBytes;
        rijndaelCipher.IV = iv;
        ICryptoTransform transform = rijndaelCipher.CreateEncryptor();
        byte[] plainText = Encoding.UTF8.GetBytes(textToEncrypt);
        string hexString = BitConverter.ToString(transform.TransformFinalBlock(plainText, 0, plainText.Length));
        hexString = hexString.Replace("-", "");
        return hexString;
    }
    public string AgentBalance()
    {
        try
        {
            SqlParameter[] get_user_details = new SqlParameter[]
            {
                new SqlParameter("@LOGINID",Session["LOGINID"].ToString())
            };

            SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "UDP_USERDETAILS", get_user_details);
            if (dr.Read())
            {

                return Convert.ToString(dr["balance"]);
            }
            else
                return "0";
        }
        catch (Exception ex)
        {
            return "0";
        }
    }
    protected void btn_submit_Click(object sender, EventArgs e)
    {
        try
        {


            login();
        }
        catch (Exception ex)
        {
            throw (ex);
        }
    }

    public void login()
    {
        if (txt_uname.Text != "" && txt_pwd.Text != "")
        {
            try
            {
                SqlParameter[] check_login_details = new SqlParameter[]
                {
                    new SqlParameter("@DomailName","http://venusrecharge.in"), 
                    new SqlParameter("@User_details",txt_uname.Text.Trim()),
                    new SqlParameter("@Password",txt_pwd.Text.Trim()),
                    new SqlParameter("@ErrorResult",SqlDbType.Int),
                };
                check_login_details[3].Direction = ParameterDirection.Output;
                DataSet ds = SqlHelper.GetDataSet(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "UDP_CHECK_USERLOGIN_DETAILS_New_WithOutUserType", check_login_details);
                int loginvariable = Convert.ToInt32(check_login_details[3].Value);
                if (loginvariable == 1)
                {
                    if (ds.Tables[0].Rows.Count != 0 & loginvariable == 1)
                    {
                        foreach (DataRow dr in ds.Tables[0].Rows)
                        {
                            Session["LOGINID"] = dr[0].ToString();
                            Session["USERTYPE"] = dr[3].ToString();
                            Session["EMAILID"] = dr[2].ToString();
                            Session["MobileNo"] = dr[4].ToString();
                            Session["USERNAME"] = txt_uname.Text.Trim();
                            Session["PASSWORD"] = txt_pwd.Text.Trim();
                            //Session["DMRStatus"] = dr["DMRStatus"].ToString();
                            //Session["FlightStatus"] = dr["FLAGFLIGHT"].ToString();
                            Session["agency_name"] = dr["CORPORATENAME"].ToString();
                            if (Session["USERTYPE"].Equals("Agent"))
                            {
                                Response.Redirect("PaymentPage.aspx", false);
                            }

                        }
                    }
                    else
                    {
                        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('You have entered invalid login details, please login with correct details.!');"), true);
                    }
                }
                if (loginvariable == 2)
                {
                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('Your account has been deactivate. Please contact Helpdesk');"), true);
                }
                if (loginvariable == 3)
                {
                    Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('You are not authorize user for this portal. Please contact Helpdesk');"), true);
                }
            }
            catch (Exception ex)
            {
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('You have entered invalid login details, please login with correct details.!');"), true);
                //throw (ex);
            }
        }
    }
}