using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;


public partial class landing_store_process_order : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Dictionary<String, String> paramValues = new Dictionary<string, string>();

        foreach (string s in Request.Form.Keys)
        {
            paramValues.Add(s.ToString(), Request.Form[s]);
        }

        String uniqueKey = Key.GetUniqueKey();
        CustomerOrders.Add(uniqueKey, paramValues["custom"]);

        if (!paramValues.ContainsKey("rm"))
        {
            paramValues.Add("rm", "2");
        }

        if (paramValues.ContainsKey("referenceViaGET") && paramValues["referenceViaGET"] == "1")
        {
            if (paramValues.ContainsKey("return"))
            {
                paramValues["return"] = paramValues["return"] + "?customer_code=" + uniqueKey + "&viaGET=1";
            }
        }

        //setting currencycode
        paramValues["currency_code"] = "USD";

        //validating plan type, and setting price server-side to avoid hacking or price changing.
        if (paramValues.ContainsKey("plan_name"))
        {
            string plan_name = paramValues["plan_name"];
            paramValues.Remove("plan_name");
            SetPlanPrice(plan_name, paramValues);
        }
        else if (paramValues.ContainsKey("upload") && paramValues["upload"] == "1")
        {
            SetItemPrices(paramValues);
        }
        else
        {
            Response.Redirect("paymentFailure?noCartType");
        }

        //creating a custom variable splitted by ';' containing both uniqueKey and accountID for this transaction
        paramValues["custom"] = uniqueKey + ";" + Request["accountNumber"];

        //paramValues.Add("business", "dev_1362676947_biz@australtek.com");
        paramValues.Add("business", "paypal@australtek.com");
        paramValues.Add("notify_url", "http://www.dzsupervision.com/DZS/DZSupervision/app/PayPal_IPN/pp_IPN.aspx");

        RedirectAndPOST(this, "https://www.paypal.com/cgi-bin/webscr", paramValues); 
    }

    private void SetItemPrices(Dictionary<String, String> paramValues)
    {
        try
        {
            Dictionary<String, String> toModify = new Dictionary<string, string> { };
            foreach (KeyValuePair<String, String> kvp in paramValues)
            {
                if (kvp.Key.IndexOf("item_number_") != -1)
                {
                    string itemNumber = kvp.Key.Substring(kvp.Key.Length - 1, 1);
                    string realPrice = "";
                    switch (kvp.Value)
                    {
                        case "1":
                            realPrice = "450.00";
                            break;
                        case "2":
                            realPrice = "490.00";
                            break;
                        case "3":
                            realPrice = "150.00";
                            break;
                        default:
                            realPrice = "";
                            break;
                    }
                    toModify["amount_" + itemNumber] = realPrice;
                }
            }

            foreach (KeyValuePair<String, String> kvp in toModify)
            {
                paramValues[kvp.Key] = kvp.Value;
            }

            paramValues["handling_cart"] = "20.00";

        }
        catch (Exception ex)
        {
            throw new Exception("SetItemPrices failed.", ex);
        }
    }

    private void SetPlanPrice(string plan_name, Dictionary<String, String> paramValues)
    {
        try
        {
            switch (plan_name.ToUpper())
            {
                case "INDUSTRIAL_M2M":
                    paramValues["a3"] = "99.00";
                    paramValues["item_name"] = "Industrial M2M";
                    break;

                case "M2M":
                    paramValues["a3"] = "14.90";
                    paramValues["item_name"] = "M2M";
                    break;
            }
            //first two months are charged at the same time.
            paramValues["a1"] = Convert.ToString(Convert.ToDouble(paramValues["a3"]) * 2);
            paramValues["p1"] = "1";
            paramValues["t1"] = "M";

            paramValues["p3"] = "1";
            paramValues["t3"] = "M";
            paramValues["src"] = "1";
        }
        catch (Exception ex)
        {
            throw new Exception("SetPlanPrice failed.", ex);
        }
    }

    private static class Key
    {
        public static String GetUniqueKey()
        {
            try
            {
                Int32 maxSize = 8;
                Char[] chars = new Char[62];
                String abc;
                abc = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
                chars = abc.ToCharArray();
                Int32 size = maxSize;
                Byte[] data = new Byte[1];
                System.Security.Cryptography.RNGCryptoServiceProvider crypto = new System.Security.Cryptography.RNGCryptoServiceProvider();
                crypto.GetNonZeroBytes(data);
                size = maxSize;
                data = new Byte[size];
                crypto.GetNonZeroBytes(data);
                StringBuilder result = new StringBuilder(size);
                foreach (byte b in data) result.Append(b);
                return result.ToString();
            }
            catch (Exception ex)
            {
                throw new Exception("GetUniqueKey failed.", ex);
            }
        }
    }


    private static String PreparePOSTForm(string url, Dictionary<String, String> data)
    {
        //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 (KeyValuePair<String, String> kvp in data)
        {
            strForm.Append("<input type=\"hidden\" name=\"" + kvp.Key + "\" value=\"" + kvp.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();
    }

    public static void RedirectAndPOST(Page page, string destinationUrl, Dictionary<String, String> data)
    {
        //Prepare the Posting form
        string strForm = PreparePOSTForm(destinationUrl, data);

        //Add a literal control the specified page holding the Post Form, this is to submit the Posting form with the request.
        page.Controls.Add(new LiteralControl(strForm));
    }
}