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.Data.SqlClient;
using System.Drawing;
using System.Text;

public partial class PushTransfes : System.Web.UI.Page
{
    decimal balance, cutoffBalance;
    decimal requestbalance;
    CommonFunction objcommonfun = new CommonFunction();
    static string transactionid, LoginId;
    string BalanceAfterTransaction, MobileNo;
    string IPAddress = HttpContext.Current.Request.UserHostAddress.ToString();
    protected void Page_Load(object sender, EventArgs e)
    {
        try
        {
            if (Session["LOGINID"] == null && Session["USERNAME"] == null)
            {
                Response.Redirect("../login.aspx");
            }
            if (!IsPostBack)
            {
                getagentusername();

            }
        }
        catch (Exception ex)
        {
            throw (ex);
        }  
    }
    private void getagentusername()
    {
        SqlParameter[] GetAgent = new SqlParameter[]
        {
            new SqlParameter("@Loginid",Session["LOGINID"].ToString()),
        };
        DataSet ds = SqlHelper.GetDataSet(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "udp_GetDistributerAgent", GetAgent);
        if (ds.Tables[0].Rows.Count > 0)
        {
            ddl_AgentID.DataSource = ds;
            ddl_AgentID.DataTextField = "USERNAME";
            ddl_AgentID.DataValueField = "loginid";
            ddl_AgentID.DataBind();
        }
    }
    protected void ddl_AgentID_SelectedIndexChanged1(object sender, EventArgs e)
    {
        divAgentdetail.Visible = true;
        try
        {
            SqlParameter[] GetAgentDetail = new SqlParameter[]
            {
                new SqlParameter ("@Username",ddl_AgentID.SelectedItem.Text),
            };
            SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "udp_GetDistributerAgentDetail", GetAgentDetail);
            if (dr.Read())
            {
                lbl_AgentAvailabelBalance.Text = Convert.ToString(dr["balance"]);
                lbl_AgentName.Text = Convert.ToString(dr["Firstname"]);
                lbl_AgentLastName.Text = Convert.ToString(dr["Lastname"]);
            }
        }
        catch (Exception ex)
        {
           // lblerror.Text = "" + ex;
            throw (ex);
        }        
    }
    private void refundamount()
    {
        transactionid = TID_GEN();
        userdetails();
        //UserCutOffDetails();
        LoginId = ddl_AgentID.SelectedValue.ToString().Trim();
        requestbalance = Convert.ToDecimal(txt_Amount.Text);
        if (ddl_Actiononamount.SelectedItem.Text == "Roll Back")
        {
            try
            {
                SqlParameter[] get_user_details = new SqlParameter[]
                {
                    new SqlParameter("@LOGINID",ddl_AgentID.SelectedValue.ToString())
                };
                SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "udp_getavailablebalance", get_user_details);
                if (dr.Read())
                {
                    balance = Convert.ToDecimal(dr["balance"]);
                }
                requestbalance = Convert.ToDecimal(txt_Amount.Text);

                if (requestbalance < (balance-UserCutOffDetails(ddl_AgentID.SelectedValue.ToString())))
                {
                    SqlParameter[] param = new SqlParameter[]
                    {
                        new SqlParameter("@USERMAME",ddl_AgentID.SelectedItem.Text),
                        new SqlParameter("@refundedamount",requestbalance),
                        new SqlParameter("@ref_no_refunded",transactionid),
                        new SqlParameter("@remark",txt_Remark.Text),                        
                        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)
                    {
                        lblerror.Text = "There is some technical problem .Please try again";
                        lblerror.ForeColor = Color.Red;
                    }
                    else
                    {
                        GetMobileNo(LoginId);
                        BalanceAfterTransaction = objcommonfun.userdetails(LoginId);
                        string sms = "An amount of Rs. " + requestbalance + " Deducted into your account on " + Convert.ToDateTime(System.DateTime.Now.ToShortDateString()).ToString("dd-MMM-yyyy") + " at " + DateTime.Now.ToString("HH:mm:ss") + " against txn id " + transactionid + " Your Current Balance is " + BalanceAfterTransaction + "";
                        objcommonfun.SendSMSByAdmin(MobileNo, sms, transactionid, LoginId);
                        lblerror.Text = txt_Amount.Text + "Rs. has been Deducted sucessfully from " + ddl_AgentID.SelectedItem.Text;
                        lblerror.ForeColor = Color.Blue;
                        getagentusername();
                        divAgentdetail.Visible = false;
                    }
                }
                else
                {
                    lblerror.Text = "You partner not have enough balance to do this transaction.";
                    lblerror.ForeColor = Color.Red;
                }
            }
            catch (Exception ex)
            {
                //CommonFunction.writeToLogFile(Convert.ToString(ex));    
                throw (ex);
            }
        }
        if (ddl_Actiononamount.SelectedItem.Text == "Credit")
        {
            try
            {
                if (balance > cutoffBalance)
                {
                    if (requestbalance < (balance - UserCutOffDetails(Session["LOGINID"].ToString())))
                    {
                        SqlParameter[] PushBalance = new SqlParameter[]
                    {
                        new SqlParameter("@DSCURRENTLEVEL",Session["LOGINID"].ToString()),
                        new SqlParameter("@AgentUserName",ddl_AgentID.SelectedItem.Text),
                        new SqlParameter("@TransactionID",transactionid),
                        new SqlParameter("@AMOUNT",txt_Amount.Text),
                        new SqlParameter("@Depositedin",txt_BankName.Text),
                        new SqlParameter("@Remarks",txt_Remark.Text),
                        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)
                        {
                            lblerror.Text = "There is some technical problem .Please try again";
                            lblerror.ForeColor = Color.Red;
                        }
                        else
                        {
                            GetMobileNo(LoginId);
                            BalanceAfterTransaction = objcommonfun.userdetails(LoginId);
                            string sms = "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 " + transactionid + " Your Current Balance is " + BalanceAfterTransaction + "";
                            objcommonfun.SendSMSByAdmin(MobileNo, sms, transactionid, LoginId);

                            lblerror.Text = txt_Amount.Text + "Rs. has been sucessfully transfer to " + ddl_AgentID.SelectedItem.Text;
                            lblerror.ForeColor = Color.Blue;
                            getagentusername();
                            divAgentdetail.Visible = false;
                        }
                    }
                    else
                    {
                        lblerror.Text = "You don’t have enough balance to do this transaction. Please take balance in your login.";
                        lblerror.ForeColor = Color.Red;
                    }
                }
                else
                {
                   
                lblerror.Text = "Your balance is low from cutoff balance. Please take balance in your login.";
                lblerror.ForeColor = Color.Red;
            
                }
           
            }
            catch (Exception ex)
            {
                //CommonFunction.writeToLogFile(Convert.ToString(ex));  
                throw (ex);
            }
        }
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            refundamount();
        }
        catch (Exception ex)
        {
            throw (ex);
        }  
    }

    public void GetMobileNo(string Loginid)
    {
        try
        {
            SqlParameter[] loginid = new SqlParameter[]
            {
                new SqlParameter ("@Loginid",Loginid)
            };
            DataSet ds = SqlHelper.GetDataSet(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "Udp_GetRegisteredMobileNo", loginid);
            if (ds.Tables[0].Rows.Count > 0)
            {
                MobileNo = ds.Tables[0].Rows[0]["MobileNo"].ToString();
            }
        }
        catch (Exception ex)
        {
            throw (ex);
        }
    }

    public string RandomString(Random r, int len)
    {
        string str = "1234567890";
        StringBuilder sb = new StringBuilder();

        while ((len--) > 0)
            sb.Append(str[(int)(r.NextDouble() * str.Length)]);

        return sb.ToString();
    }
    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_getavailablebalance", get_user_details);
            if (dr.Read())
            {
                balance = Convert.ToDecimal(dr["balance"]);
            }
            //ViewState["leftbalance"]=Label5.Text;
        }
        catch (Exception ex)
        {
            Server.Transfer("Error.aspx?id=" + ex + "");
            //string st = ex.Message;
        }
    }
    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;
    }
    public decimal UserCutOffDetails(string LoginID)
    {
        try
        {
            SqlParameter[] get_user_details = new SqlParameter[]
            {
                new SqlParameter("@LOGINID",LoginID)
            };

            SqlDataReader dr = SqlHelper.ExecuteReader(SqlHelper.mainConnectionString, CommandType.StoredProcedure, "udp_getcutoffbalance", get_user_details);
            if (dr.Read())
            {
                cutoffBalance = Convert.ToInt32(dr["CuttOffAmount"]);
            }
            return cutoffBalance;
        }
        catch (Exception ex)
        {
            return 0;
        }
    }

}
