using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
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.WebControls;

public partial class TrainService_PaymentPage : System.Web.UI.Page
{
    string usertype, Ipaddress;
    string bookPageTitle, bookKeywords, description, sno;
    TrainService.TrainResponseDetails Train_ResponseDetails;
    string _encResponseString = string.Empty;
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (Session["LOGINID"] == null && Session["USERTYPE"] == null)
            {
                Response.Redirect("../login.aspx");
            }
            lblimage.Text = Convert.ToString(Session["headerlogoimage"]);
            lblCopyRight.Text = Session["copyright"].ToString();
            lblMobileNo.Text = Session["helpdeskmobileno"].ToString();
            lblMobileNoAlt.Text = Session["HelpDeskMobileNoAlter"].ToString();
            lblEmailIdSupport.Text = Session["helpdeskemailid"].ToString();
            usertype = Session["USERTYPE"].ToString();
            if (!IsPostBack)
            {
                Train_ResponseDetails = (TrainService.TrainResponseDetails)Session["TrainResponseDetails"];
                userdetails();
                getTrainTransaction();
            }

        }
        catch (Exception ex)
        {
            throw (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_USERDETAILS", get_user_details);
            if (dr.Read())
            {
                lblAgentid.Text = Convert.ToString(dr["USERNAME"]);
                lblbalance.Text = Convert.ToString(dr["balance"]);
                Session["balance"] = Convert.ToString(dr["balance"]);
                lbl_title.Text = Convert.ToString(dr["title"]);
                lbl_FirstName.Text = Convert.ToString(dr["firstname"]);
                lbl_LastName.Text = Convert.ToString(dr["LASTNAME"]);
            }
            dr.Close();
        }
        catch (Exception ex)
        {
            throw (ex);
        }
    }
    public void getTrainTransaction()
    {
       
        lblRefId.Text = Train_ResponseDetails.reservationId;
        lblAmount.Text = Train_ResponseDetails.txnAmount;
        lblmarchentName.Text = "IRCTC_NGeT_RDS";
    }
    protected void btnCan_Click(object sender, EventArgs e)
    {
             Train_ResponseDetails = (TrainService.TrainResponseDetails)Session["TrainResponseDetails"];
             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);
    }
    protected void btnconfirm_Click(object sender, EventArgs e)
    {
        Train_ResponseDetails = (TrainService.TrainResponseDetails)Session["TrainResponseDetails"];
        string ResponseData=string.Empty, checksum, BankTxnId;
        decimal WL_Amount = Convert.ToDecimal(WLAmount());
        decimal ReqBal=Convert.ToDecimal(Train_ResponseDetails.txnAmount);
        decimal AgBal=Convert.ToDecimal(Session["balance"]);
        decimal CutOffBal = Convert.ToDecimal(UserCutOffDetails());
        BankTxnId = Generate_TID();
        if (WL_Amount > ReqBal)//WLbalance > ReqBalance)
        {
            if (AgBal > CutOffBal)//balance > cutoffBalance)
            {
                if (ReqBal < (AgBal - CutOffBal))//ReqBalance < (balance - cutoffBalance))
                {

                    int status1 = CommonFunction.InsertTransactionWithPendingStatus(Session["WhitelabelId"].ToString(), "", 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");
                    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 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 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 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 void PostData(string Url, string PostData)
    {
       string strUrl = Url + "?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();


        string FormName = "form1";
        string Method = "post";
        //string V3URL = "http://venusrecharge.in/TrainService/PaymentRequest.aspx";
        string V3URL = Url;
        Response.Clear();
        Response.Write("<html><head>");
        Response.Write("<META HTTP-EQUIV=\"CACHE-CONTROL\" CONTENT=\"no-store, no-cache, must-revalidate\" />");
        Response.Write("<META HTTP-EQUIV=\"PRAGMA\" CONTENT=\"no-store, no-cache, must-revalidate\" />");
        Response.Write(string.Format("</head><body onload=\"document.{0}.submit()\">", FormName));
        Response.Write(string.Format("<form name=\"{0}\" method=\"{1}\" action=\"{2}\" >", FormName, Method, V3URL));

        //foreach (KeyValuePair<string, string> param in postparamslist)
        //{
        //    Response.Write(string.Format("<input name=\"{0}\" type=\"hidden\" value=\"{1}\" />", param.Key, param.Value));
        //}
        // Response.Write("<input type=\"hidden\" name=\"response\" value=" + md5HashData + " />");
        Response.Write("<input type=\"hidden\" name=\"encdata\" value=" + PostData + " />");
        Response.Write("</form>");
        Response.Write("</body></html>");
        Response.End();
    }
    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 void InsertTrainBookingDetails(TrainService.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 PostResponse(string RequestString, TrainService.TrainResponseDetails TrainResponseDetails)
    {
        InsertLog("PaymentResD", RequestString);
        _encResponseString = EncryptAPP(RequestString, "abfb7c8d48dfc4f1ce7ed92a44989f25", "232fcfdc2e2b4767");
        PostData(TrainResponseDetails.RU, _encResponseString);
    }
    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();
        }
    }
}