using System;
using System.Data;
using System.Configuration;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Security.Cryptography;
using System.Text;
using System.Net;
using System.IO;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;


public partial class App_Payment : System.Web.UI.Page
{
    public string action1 = string.Empty;
    public string hash1 = string.Empty;
    public string txnid1 = string.Empty;

    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            key.Value = ConfigurationManager.AppSettings["MERCHANT_KEY"];

            if (!IsPostBack)
            {
                string id = Request.QueryString["drgbzrid"];
                string conString = ConfigurationManager.ConnectionStrings["dbnm"].ConnectionString;
                SqlConnection con = new SqlConnection(conString);

                SqlDataAdapter da = new SqlDataAdapter(
                    "select *,year(getdate()) as yr from company WHERE drgbzrid='" + id +
                    "'", con);

                DataSet dsrepdt = new DataSet();
                dsrepdt.Reset();
                dsrepdt.Clear();
                da.Fill(dsrepdt);

                if (dsrepdt.Tables[0].Rows.Count == 0)
                {
                    ScriptManager.RegisterStartupScript(this, GetType(), "showalert",
                        "alert('Invalid ID');", true);
                    submit.Enabled = false;
                    return;
                }
                else
                {
                    lblcomp.Text = dsrepdt.Tables[0].Rows[0]["compname"].ToString();
                    lbltown.Text = dsrepdt.Tables[0].Rows[0]["comptown"].ToString();
                    firstname.Text = dsrepdt.Tables[0].Rows[0]["compname"].ToString();
                    email.Text = dsrepdt.Tables[0].Rows[0]["CompEmail"].ToString();
                    txtusers.Text = dsrepdt.Tables[0].Rows[0]["NoOfUsr"].ToString();
                    submit.Enabled = true;
                    if (dsrepdt.Tables[0].Rows[0]["yr"].ToString() == dsrepdt.Tables[0].Rows[0]["amcyr"].ToString())
                    {
                        ScriptManager.RegisterStartupScript(this, GetType(), "showalert",
                        "alert('AMC already Paid For This Year');", true);
                        submit.Enabled = false;
                        return;
                    }
                    
                }
            }
            
            if (string.IsNullOrEmpty(Request.Form["hash"]))
            {
                submit.Visible = true;
            }
            else
            {
                submit.Visible = false;
            }
            // Required - Response callback url to be used by Payment Gateway to post back payment status. 
            // surl - for success tranction, furl - for failure transaction, curl - for cancel transaction.
            surl.Value = HttpContext.Current.Request.Url.GetLeftPart(UriPartial.Authority) + HttpRuntime.AppDomainAppVirtualPath + "/ResponseHandling.aspx";
            furl.Value = surl.Value.ToString();
            curl.Value = furl.Value.ToString();
            // Contains information of integration type. Consult to PayU for more details.
            
            //Not mandatory but fixed code can be passed to Payment Gateway to show default payment 
            //option tab. e.g. NB, CC, DC, CASH, EMI. Refer PDF for more details.
            
        }
        catch (Exception ex)
        {
            Response.Write("<span style='color:red'>" + ex.Message + "</span>");

        }
    }

    public string Generatehash512(string text)
    {

        byte[] message = Encoding.UTF8.GetBytes(text);

        UnicodeEncoding UE = new UnicodeEncoding();
        byte[] hashValue;
        SHA512Managed hashString = new SHA512Managed();
        string hex = "";
        hashValue = hashString.ComputeHash(message);
        foreach (byte x in hashValue)
        {
            hex += String.Format("{0:x2}", x);
        }
        return hex;

    }

protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {

            string[] hashVarsSeq;
            string hash_string = string.Empty;
            decimal amt = 1;
            if (Convert.ToInt32(txtusers.Text)> 1)
            {
                amt = amt + ((Convert.ToInt32(txtusers.Text) - 1) * 1500);
            }
            amt = amt + ((amt * 18) / 100);

            if (string.IsNullOrEmpty(Request.Form["txnid"])) // generating random txnid
            {
                Random rnd = new Random();
                string strHash = Generatehash512(rnd.ToString() + DateTime.Now);
                txnid1 = strHash.ToString().Substring(0, 20);

            }
            else
            {
                txnid1 = Request.Form["txnid"];
            }
            if (string.IsNullOrEmpty(Request.Form["hash"])) // generating hash value
            {
              
                    //frmError.Visible = false;
                    hashVarsSeq = ConfigurationManager.AppSettings["hashSequence"].Split('|'); // spliting hash sequence from config
                    hash_string = "";
                    foreach (string hash_var in hashVarsSeq)
                    {
                        if (hash_var == "key")
                        {
                            hash_string = hash_string + ConfigurationManager.AppSettings["MERCHANT_KEY"];
                            hash_string = hash_string + '|';
                        }
                        else if (hash_var == "txnid")
                        {
                            hash_string = hash_string + txnid1;
                            hash_string = hash_string + '|';
                        }
                        else if (hash_var == "amount")
                        {
                            hash_string = hash_string + Convert.ToDecimal(Request.Form[hash_var]).ToString("g29");
                            hash_string = hash_string + '|';
                        }
                        else
                        {

                            hash_string = hash_string + (Request.Form[hash_var] != null ? Request.Form[hash_var].Trim() : "");// isset if else
                            hash_string = hash_string + '|';
                        }
                    }

                    hash_string += ConfigurationManager.AppSettings["SALT"];// appending SALT

                    hash_string = ConfigurationManager.AppSettings["MERCHANT_KEY"] + "|" + txnid1 + "|"+ amt +"|Service|" + firstname.Text + "|" + email.Text + "|||||PayUBiz_ASP.NET_Kit||||||" + ConfigurationManager.AppSettings["SALT"];

                    hash1 = Generatehash512(hash_string).ToLower();         //generating hash
                    action1 = ConfigurationManager.AppSettings["PAYU_BASE_URL"] + "/_payment";// setting URL

               


            }

            else if (!string.IsNullOrEmpty(Request.Form["hash"]))
            {
                hash1 = Request.Form["hash"];
                action1 = ConfigurationManager.AppSettings["PAYU_BASE_URL"] + "/_payment";

            }

            if (!string.IsNullOrEmpty(hash1))
            {
                hash.Value = hash1;
                txnid.Value = txnid1;

                System.Collections.Hashtable data = new System.Collections.Hashtable(); // adding values in gash table for data post
                data.Add("hash", hash.Value);
                data.Add("txnid", txnid1);
                data.Add("key", key.Value);
                string AmountForm = Convert.ToDecimal(amt).ToString("g29");// eliminating trailing zeros
                data.Add("amount", AmountForm);
                data.Add("firstname", firstname.Text.Trim());
                data.Add("email", email.Text.Trim());
                data.Add("phone", phone.Text.Trim());
                data.Add("productinfo", "Service");
                data.Add("surl", surl.Value.Trim());
                data.Add("furl", furl.Value.Trim());
                data.Add("lastname", Request.QueryString["drgbzrid"]);
                data.Add("curl", curl.Value.Trim());
                data.Add("address1", "");
                data.Add("address2", "");
                data.Add("city", "");
                data.Add("state", "");
                data.Add("country", "");
                data.Add("zipcode", "");
                data.Add("udf1", "");
                data.Add("udf2", "");
                data.Add("udf3", "");
                data.Add("udf4", "");
                data.Add("udf5", "PayUBiz_ASP.NET_Kit");
                data.Add("pg", "");


                string strForm = PreparePOSTForm(action1, data);
                Page.Controls.Add(new LiteralControl(strForm));

            }

            else
            {
                //no hash

            }

        }

        catch (Exception ex)
        {
            Response.Write("<span style='color:red'>" + ex.Message + "</span>");

        }



    }
    private string PreparePOSTForm(string url, System.Collections.Hashtable data)      // post form
    {
        //Set a name for the form
        string formID = "PostForm";
        //Build the form using the specified data to be posted.
        StringBuilder strForm = new StringBuilder();
        strForm.Append("<form id=\"" + formID + "\" name=\"" +
                       formID + "\" action=\"" + url +
                       "\" method=\"POST\">");

        foreach (System.Collections.DictionaryEntry key in data)
        {

            strForm.Append("<input type=\"hidden\" name=\"" + key.Key +
                           "\" value=\"" + key.Value + "\">");
        }


        strForm.Append("</form>");
        //Build the JavaScript which will do the Posting operation.
        StringBuilder strScript = new StringBuilder();
        strScript.Append("<script language='javascript'>");
        strScript.Append("var v" + formID + " = document." +
                         formID + ";");
        strScript.Append("v" + formID + ".submit();");
        strScript.Append("</script>");
        //Return the form and the script concatenated.
        //(The order is important, Form then JavaScript)
        return strForm.ToString() + strScript.ToString();
    }
}