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

public partial class MobileSMS_AmountTransfer : System.Web.UI.Page
{
    decimal balance, balanceR;
    decimal requestbalance;
    string stringquery, msg, MobileNo, AgMobileNo, RefrenceNo;
    CommonFunction objcommonfun = new CommonFunction();
    string Type;
    string Session_RQ_MRecharge;
    string txn;
    string Paymentstatus_RS, agent_Id, flagREFREV;
    string errorcode = string.Empty;
    string ActualMPIN, date_time, BalanceAfterTransaction;
    int LoginCount;
    string IPAddress = HttpContext.Current.Request.UserHostAddress.ToString();    
    protected void Page_Load(object sender, EventArgs e)
    {
        //VUS TRF AG09467 10 2222

        //VUS+BAL+AT+8002266480
        stringquery = Request.QueryString["Message"].ToString().Trim();
        MobileNo = Request.QueryString["MobNo"].ToString();
        RefrenceNo = Request.QueryString["Refno"].ToString();
        //string[] stringquery11 = new string[10];
        //stringquery11 = stringquery.Split('/');

        msg = stringquery;
        msg = Regex.Replace(msg, @"\s+", " ");
        string[] sms = msg.Split(' ');
        ViewState["Keyword"] = Convert.ToString(sms.GetValue(1));
        ViewState["Userid"] = Convert.ToString(sms.GetValue(2));
        ViewState["Amount"] = Convert.ToString(sms.GetValue(3));
        ViewState["mpin"] = Convert.ToString(sms.GetValue(4));
        AgMobileNo = MobileNo.Substring(MobileNo.Length - Math.Min(10, MobileNo.Length));
        string strAmt = string.Empty;
        strAmt = ViewState["Amount"].ToString();
        string userstatus = objcommonfun.GetUserStatus(AgMobileNo);
        GetMpin();
        if (userstatus.Equals("1"))
        {         
            if (LoginCount <= 2)
            {
                if (ActualMPIN == Convert.ToString(ViewState["mpin"]))
                {
                    if (Regex.IsMatch(strAmt, "[A-Z|a-z]"))
                    {
                        BalanceAfterTransaction = objcommonfun.userdetails(agent_Id);
                        if (Convert.ToDouble(BalanceAfterTransaction) > 0.25)
                        {
                            deductamount();
                            objcommonfun.SendSMS(AgMobileNo, "You have send Wrong Amount. Kindly use correct Amount This SMS charge@ 0.25 paisa", RefrenceNo, AgMobileNo, stringquery);
                        }
                    }
                    else
                    {
                        GetAgentdetail();
                        if (ViewState["PartnerID"] != null)
                        {
                            getuserdetail();
                            if (flagREFREV.Equals("1"))
                            {
                                refundamount();
                            }
                            else
                            {
                                BalanceAfterTransaction = objcommonfun.userdetails(agent_Id);
                                if (Convert.ToDouble(BalanceAfterTransaction) > 0.25)
                                {
                                    deductamount();
                                    objcommonfun.SendSMS(AgMobileNo, "You are not authorise to use this services. This SMS charge@ 0.25 paisa", RefrenceNo, AgMobileNo, stringquery);
                                }
                            }
                        }
                        else
                        {
                            BalanceAfterTransaction = objcommonfun.userdetails(agent_Id);
                            if (Convert.ToDouble(BalanceAfterTransaction) > 0.25)
                            {
                                deductamount();
                                objcommonfun.SendSMS(AgMobileNo, "You have send Wrong Partner ID. Kindly use correct Partner ID This SMS charge@ 0.25 paisa", RefrenceNo, AgMobileNo, stringquery);
                            }
                        }
                    }
                }
                else
                {
                    try
                    {
                        SqlParameter[] paramLoginCount = new SqlParameter[]
                        {
                            new SqlParameter("@AgentmobileNo",AgMobileNo)
                        };
                        SqlHelper.ExecuteNonQuery(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "usp_UpdateLoginCount", paramLoginCount);
                    }
                    catch (Exception ex)
                    {
                        throw (ex);
                    }
                    BalanceAfterTransaction = objcommonfun.userdetails(agent_Id);
                    if (Convert.ToDouble(BalanceAfterTransaction) > 0.25)
                    {
                        deductamount();
                        objcommonfun.SendSMS(AgMobileNo, "Wrong MPIN used. Account will be blocked on three wrong attempts This SMS charge @0.25 paisa", RefrenceNo, AgMobileNo, stringquery);
                    }
                }
            }
            else
            {
                BalanceAfterTransaction = objcommonfun.userdetails(agent_Id);
                if (Convert.ToDouble(BalanceAfterTransaction) > 0.25)
                {
                    deductamount();
                    objcommonfun.SendSMS(AgMobileNo, "Dear Partner, Your account has been blocked due to using wrong MPIN three times", RefrenceNo, AgMobileNo, stringquery);
                    objcommonfun.UpdateUserStatus(AgMobileNo);
                }
            }            
        }
        else
        {
            BalanceAfterTransaction = objcommonfun.userdetails(agent_Id);
            if (Convert.ToDouble(BalanceAfterTransaction) > 0.25)
            {
                deductamount();
                objcommonfun.SendSMS(AgMobileNo, "Your are not authorize to Use SMS services. Kindly contact administrator", RefrenceNo, AgMobileNo, stringquery);
            }
        }        
    }

    public void GetMpin()
    {
        try
        {
            SqlParameter[] get_user_details = new SqlParameter[]
            {
                new SqlParameter("@MobileNo",AgMobileNo)
            };
            DataSet ds = SqlHelper.GetDataSet(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "usp_GetMpin", get_user_details);
            if (ds.Tables[0].Rows.Count > 0)
            {
                ActualMPIN = ds.Tables[0].Rows[0]["Mpin1"].ToString();
                agent_Id = ds.Tables[0].Rows[0]["LOGINID"].ToString();
                LoginCount = Convert.ToInt32(ds.Tables[0].Rows[0]["LOGINCOUNT"].ToString());
                ViewState["Username"] = ds.Tables[0].Rows[0]["USERNAME"].ToString();
            }
        }
        catch (Exception ex)
        {
            string st = ex.Message;
        }
    }

    public void getuserdetail()
    {
        try
        {
            SqlParameter[] getserviceactivation = new SqlParameter[] 
            {
                new SqlParameter("@LOGINID",agent_Id)
            };
            DataSet ds = SqlHelper.GetDataSet(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "UDP_USERDETAILS_forsmserviceActivation", getserviceactivation);
            if (ds.Tables[0].Rows.Count > 0)
            {
                flagREFREV = ds.Tables[0].Rows[0]["SMServicesTRFREV"].ToString();
            }
        }
        catch (Exception ex)
        {
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('There is some problem .Please try again.');"), true);
        }
    }

    public void GetAgentdetail()
    {
        SqlParameter[] getuserdetail = new SqlParameter[]
        {
            new SqlParameter("@Username",ViewState["Userid"].ToString()),
            new SqlParameter ("@Upperlevel",agent_Id)
        };
        DataSet ds = SqlHelper.GetDataSet(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "usp_GetAgentDetail", getuserdetail);
        if (ds.Tables[0].Rows.Count > 0)
        {
            ViewState["PartnerID"]=ds.Tables[0].Rows[0]["Loginid"].ToString();
            ViewState["MobileNo"] = ds.Tables[0].Rows[0]["MobileNo"].ToString();
        }
    }

    private void refundamount()
    {
        if (ViewState["Keyword"].Equals("REV") || ViewState["Keyword"].Equals("Rev") || ViewState["Keyword"].Equals("rev"))
        {
            try
            {
                userdetailP();
                if (Convert.ToDouble( ViewState["Amount"].ToString()) < 500 || Convert.ToDouble( ViewState["Amount"].ToString()) > 5000)
                {
                    BalanceAfterTransaction = objcommonfun.userdetails(agent_Id);
                    if (Convert.ToDouble(BalanceAfterTransaction) > 0.25)
                    {
                        deductamount();
                        objcommonfun.SendSMS(AgMobileNo, "Invalid Amount for Reverse Minimum value for reverse is 500 and maximum is 5000 This SMS charge @ 0.25 paisa", RefrenceNo, AgMobileNo, stringquery);
                    }
                }
                else
                {
                    requestbalance = Convert.ToDecimal(ViewState["Amount"].ToString());
                    if (requestbalance < balanceR)
                    {
                        SqlParameter[] param = new SqlParameter[]
                        {
                            new SqlParameter("@USERMAME",ViewState["Userid"].ToString()),
                            new SqlParameter("@refundedamount",requestbalance),
                            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_sms", param);
                        int result = Convert.ToInt32(param[5].Value);
                        if (result == 1)
                        {
                            objcommonfun.SendSMS(AgMobileNo, "There is some technical problem .Please try again", RefrenceNo, AgMobileNo, stringquery);
                        }
                        else
                        {
                            BalanceAfterTransaction = objcommonfun.userdetails(agent_Id);                                                      
                            objcommonfun.SendSMS(AgMobileNo, "TID " + "" + RefrenceNo + " Amount " + requestbalance + " has been reversed from " + ViewState["Userid"].ToString() + " successfully Your current balance is " + BalanceAfterTransaction + " This SMS charge @ 0.25 paisa", RefrenceNo, AgMobileNo, stringquery);
                            //deductamount();
                            BalanceAfterTransaction = objcommonfun.userdetails(ViewState["PartnerID"].ToString());
                            objcommonfun.SendSMSByAdmin(ViewState["MobileNo"].ToString(), "An amount of Rs. " + requestbalance + " debited from your account on " + Convert.ToDateTime(System.DateTime.Now.ToShortDateString()).ToString("dd-MMM-yyyy") + " at " + DateTime.Now.ToString("HH:mm:ss") + " against txn id " + RefrenceNo + " by " + ViewState["Username"].ToString() + " Your Current Balance is " + BalanceAfterTransaction + "", RefrenceNo, ViewState["PartnerID"].ToString());
                                
                            
                        }
                    }
                    else
                    {
                        BalanceAfterTransaction = objcommonfun.userdetails(agent_Id);
                        if (Convert.ToDouble(BalanceAfterTransaction) > 0.25)
                        {
                            deductamount();
                            objcommonfun.SendSMS(AgMobileNo, "Insufficient Balance for Reversal Only " + balanceR + " can be reverse This SMS charge @ 0.25 paisa", RefrenceNo, AgMobileNo, stringquery);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //CommonFunction.writeToLogFile(Convert.ToString(ex));
            }
        }
        if (ViewState["Keyword"].Equals("TRF") || ViewState["Keyword"].Equals("Trf") || ViewState["Keyword"].Equals("trf"))
        {
            try
            {
                userdetails();
                if (Convert.ToDouble(ViewState["Amount"].ToString()) < 500 || Convert.ToDouble(ViewState["Amount"].ToString()) > 5000)
                {
                    BalanceAfterTransaction = objcommonfun.userdetails(agent_Id);
                    if (Convert.ToDouble(BalanceAfterTransaction) > 0.25)
                    {
                        deductamount();
                        objcommonfun.SendSMS(AgMobileNo, "Invalid Amount for Transfer Minimum value for transfer is 500 and maximum is 5000 This SMS charge @ 0.25 paisa", RefrenceNo, AgMobileNo, stringquery);
                    }
                }
                else
                {
                    requestbalance = Convert.ToDecimal(ViewState["Amount"].ToString());
                    if (requestbalance < balance + Convert.ToDecimal(0.25))
                    {
                        SqlParameter[] PushBalance = new SqlParameter[]
                        {
                            new SqlParameter("@DSCURRENTLEVEL",agent_Id),
                            new SqlParameter("@AgentUserName",ViewState["Userid"].ToString()),
                            new SqlParameter("@TransactionID",RefrenceNo),
                            new SqlParameter("@AMOUNT",requestbalance),
                            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_sms", PushBalance);
                        int result = Convert.ToInt32(PushBalance[7].Value);
                        if (result == 1)
                        {
                            objcommonfun.SendSMS(AgMobileNo, "There is some technical problem .Please try again.", RefrenceNo, AgMobileNo, stringquery);
                        }
                        else
                        {
                            BalanceAfterTransaction = objcommonfun.userdetails(agent_Id);                                                           
                            objcommonfun.SendSMS(AgMobileNo, "TID " + "" + RefrenceNo + " Amount " + requestbalance + " has been transferred to " + ViewState["Userid"].ToString() + " successfully Your current balance is " + BalanceAfterTransaction + " This SMS charge @ 0.25 paisa", RefrenceNo, AgMobileNo, stringquery);
                            //deductamount();
                            BalanceAfterTransaction = objcommonfun.userdetails(ViewState["PartnerID"].ToString());
                            objcommonfun.SendSMSByAdmin(ViewState["MobileNo"].ToString(), "An amount of Rs. " + requestbalance + " credited into your account on " + Convert.ToDateTime(System.DateTime.Now.ToShortDateString()).ToString("dd-MMM-yyyy") + " at " + DateTime.Now.ToString("HH:mm:ss") + " against txn id " + RefrenceNo + " by " + ViewState["Username"].ToString() + " Your Current Balance is " + BalanceAfterTransaction + "", RefrenceNo, ViewState["PartnerID"].ToString());
                            
                        }
                    }
                    else
                    {
                        BalanceAfterTransaction = objcommonfun.userdetails(agent_Id);
                        if (Convert.ToDouble(BalanceAfterTransaction) > 0.25)
                        {
                            deductamount();
                            objcommonfun.SendSMS(AgMobileNo, "Dear Partner, You don’t have sufficient balance to do this transaction. Pls take upload in your login This SMS charge @ 0.25 paisa", RefrenceNo, AgMobileNo, stringquery);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                //CommonFunction.writeToLogFile(Convert.ToString(ex));
            }
        }
    }

    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"]);
               //balance = balance +Convert.ToDecimal(0.25);
            }
        }
        catch (Exception ex)
        {
        }
    }

    public void userdetailP()
    {
        SqlParameter[] get_user_details = new SqlParameter[]
        {
            new SqlParameter("@LOGINID",ViewState["PartnerID"].ToString())
        };
        SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "udp_getavailablebalance", get_user_details);
        if (dr.Read())
        {
            balanceR = Convert.ToDecimal(dr["balance"]);
        }
    }

    public void deductamount()
    {
        try
        {
            SqlParameter[] deductamount = new SqlParameter[]
            {
                new SqlParameter("@Loginid",agent_Id),                
                new SqlParameter("@refrenceno",RefrenceNo),
                new SqlParameter("@balance",BalanceAfterTransaction),
                new SqlParameter("@ServiceName","SMS Charge") 
            };
            DataSet ds = SqlHelper.GetDataSet(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "udp_deductAmountForSMS", deductamount);
        }
        catch (Exception ex)
        {
            //CommonFunction.writeToLogFile(Convert.ToString(ex));
        }
    }    
}
