using System;
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.Data.SqlClient;
using System.Drawing;
using System.IO;
using System.Text;
using System.Net.Mail;
using System.Net.Sockets;
using System.Xml;
using System.Xml.Linq;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading;


public partial class MobilePortal_MobileAppFundTransfer : System.Web.UI.Page
{
    decimal balance, balanceR;
    string headXML = "<?xml version=\"1.0\" ?><response>";
    string footerXML = "</response>";
    string agent_Id, txn_key, Username, amount, ServiceType, RefrenceNo, AGStatus, url;
    string IPAddress = HttpContext.Current.Request.UserHostAddress.ToString();

    protected void Page_Load(object sender, EventArgs e)
    {
        url = HttpContext.Current.Request.Url.AbsoluteUri;
        //url="http://kashishstudypoint.in/MobilePortal/MobileAppFundTransfer.aspx?agent_Id=1000000004&txn_key=22215474565144&Username=AG00005&amount=10&ServiceType=Credit";
        agent_Id = Request.QueryString["agent_Id"];
        txn_key = Request.QueryString["txn_key"];
        Username = Request.QueryString["Username"];
        amount = Request.QueryString["amount"];
        ServiceType = Request.QueryString["ServiceType"];

        //agent_Id = "1000000004";
        //txn_key = "22215474565144";
        //Username = "AG00005";
        //amount = "10";
        //ServiceType = "Credit";

        RefrenceNo = TID_GEN();
        saveinputoutput();
        refundamount();
    }

    private void refundamount()
    {

        if (ServiceType.Equals("Debit"))
        {
            try
            {
                CheckAgent();
                if (AGStatus.Equals("1"))
                {
                    CheckAgentBalance();
                    if (balanceR > Convert.ToDecimal(amount))
                    {
                        SqlParameter[] param = new SqlParameter[]
                        {
                            new SqlParameter("@USERMAME",Username),
                            new SqlParameter("@refundedamount",amount),
                            new SqlParameter("@ref_no_refunded",RefrenceNo),
                            new SqlParameter("@remark",""),                        
                            new SqlParameter("@IPAddress",IPAddress),
                            new SqlParameter("@ErrorMessage",SqlDbType.Int)
                        };
                        param[5].Direction = ParameterDirection.Output;
                        SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "UDP_PartnerRollback_Amount", param);
                        int result = Convert.ToInt32(param[5].Value);
                        if (result == 1)
                        {
                            headXML += "<trans-response-code>1</trans-response-code><trans-response-message>Technical Error. Pls try again.</trans-response-message>" + footerXML;
                            WriteXML(headXML);
                        }
                        else
                        {
                            headXML += "<trans-response-code>1</trans-response-code><trans-response-message>Amount Rs. " + amount + " reversed from " + Username + "</trans-response-message>" + footerXML;
                            WriteXML(headXML);
                        }
                    }
                    else
                    {
                        headXML += "<trans-response-code>1</trans-response-code><trans-response-message>Insufficient Balance !</trans-response-message>" + footerXML;
                        WriteXML(headXML);
                    }
                }
                else
                {
                    headXML += "<trans-response-code>1</trans-response-code><trans-response-message>Invalid User ID</trans-response-message>" + footerXML;
                    WriteXML(headXML);
                }
            }
            catch (Exception ex)
            {
                //headXML += "<trans-response-code>1</trans-response-code><trans-response-message>There is some technical problem .Please try again</trans-response-message>" + footerXML;
                //WriteXML(headXML);
            }
        }
        if (ServiceType.Equals("Credit") || ServiceType.Equals("credit"))
        {
            try
            {
                CheckAgent();
                if (AGStatus.Equals("1"))
                {
                    if (CheckAgentRelation() == 1)
                    {
                        userdetails();
                        if (balance > Convert.ToDecimal(amount))
                        {
                            SqlParameter[] PushBalance = new SqlParameter[]
                        {
                            new SqlParameter("@DSCURRENTLEVEL",agent_Id),
                            new SqlParameter("@AgentUserName",Username),
                            new SqlParameter("@TransactionID",RefrenceNo),
                            new SqlParameter("@AMOUNT",amount),
                            new SqlParameter("@Depositedin",""),
                            new SqlParameter("@Remarks",""),
                            new SqlParameter("@IPAddress ",IPAddress),
                            new SqlParameter("@ErrorMessage",SqlDbType.Int)
                        };
                            PushBalance[7].Direction = ParameterDirection.Output;
                            SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "udp_PushBalance", PushBalance);
                            int result = Convert.ToInt32(PushBalance[7].Value);
                            if (result == 1)
                            {
                                headXML += "<trans-response-code>1</trans-response-code><trans-response-message>Technical Error. Pls try again.</trans-response-message>" + footerXML;
                                WriteXML(headXML);
                            }
                            else
                            {
                                headXML += "<trans-response-code>1</trans-response-code><trans-response-message>Amount Rs. " + amount + " transferred to " + Username + "</trans-response-message>" + footerXML;
                                WriteXML(headXML);
                            }
                        }
                        else
                        {
                            headXML += "<trans-response-code>1</trans-response-code><trans-response-message>Insufficient Balance !</trans-response-message>" + footerXML;
                            WriteXML(headXML);
                        }
                    }
                    else
                    {
                        headXML += "<trans-response-code>1</trans-response-code><trans-response-message>Invalid Agent Id!</trans-response-message>" + footerXML;
                        WriteXML(headXML);
                    }
                }
                else
                {
                    headXML += "<trans-response-code>1</trans-response-code><trans-response-message>Invalid User ID!</trans-response-message>" + footerXML;
                    WriteXML(headXML);
                }
            }
            catch (Exception ex)
            {
                //headXML += "<trans-response-code>1</trans-response-code><trans-response-message>There is some technical problem .Please try again</trans-response-message>" + footerXML;
                //WriteXML(headXML);
            }
        }
    }



    public int CheckAgentRelation()
    {
        SqlParameter[] get_user_details = new SqlParameter[]
        {
             new SqlParameter("@DSCURRENTLEVEL",agent_Id),
             new SqlParameter("@AgentUserName",Username),                           
             new SqlParameter("@ErrorMessage",SqlDbType.Int)
        };
        get_user_details[2].Direction = ParameterDirection.Output;
        SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "check_agent_dS_relation", get_user_details);
        int result = Convert.ToInt32(get_user_details[2].Value);
        return result;
    }
    public void CheckAgent()
    {
        SqlParameter[] get_user_details = new SqlParameter[]
        {
            new SqlParameter("@Username",Username)
        };
        SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "udp_checkUser", get_user_details);
        if (dr.Read())
        {
            AGStatus = Convert.ToString(dr["AGStatus"]);
        }
    }

    public void CheckAgentBalance()
    {
        try
        {
            SqlParameter[] get_user_details = new SqlParameter[]
            {
                new SqlParameter("@Username",Username)
            };
            SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "udp_getAgbalance", get_user_details);
            if (dr.Read())
            {
                balanceR = Convert.ToDecimal(dr["balance"]);
            }
        }
        catch (Exception ex)
        {
            headXML += "<trans-response-code>1</trans-response-code><trans-response-message>" + ex + "</trans-response-message>" + footerXML;
            WriteXML(headXML);
        }
    }

    public void userdetails()
    {
        try
        {
            SqlParameter[] get_user_details = new SqlParameter[]
            {
                new SqlParameter("@LOGINID",agent_Id)
            };
            SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "udp_getavailablebalance", get_user_details);
            if (dr.Read())
            {
                balance = Convert.ToDecimal(dr["balance"]);
            }
        }
        catch (Exception ex)
        {
        }
    }

    private void WriteXML(string str)
    {
        updateresponce(str);
        Response.ClearHeaders();
        Response.AddHeader("content-type", "text/xml");
        Response.Write(str);
        Response.End();
    }

    public void saveinputoutput()
    {
        SqlParameter[] inputrequest = new SqlParameter[]
        {
            new SqlParameter("@mobileno",agent_Id),
            new SqlParameter("@url",url),
            new SqlParameter("@txnid",RefrenceNo)
        };
        SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "udp_insert_input_request_mobileApps", inputrequest);
    }

    public void updateresponce(string responce)
    {
        SqlParameter[] inputrequest = new SqlParameter[]
        {
            new SqlParameter("@txnid",RefrenceNo),
            new SqlParameter("@Responce",responce)
        };
        SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "udp_update_responce_mobileApps", inputrequest);
    }

    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", "14");
        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", "14");
        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;
    }
}
