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;
    decimal requestbalance;
    //int requestbalance;
    string transactionid;
    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()
    {
        try
        {
            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();
            }
        }
        catch (Exception ex)
        {
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('There is some technical problem. Please try again');"), true);
        }
    }
    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)
        {
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('There is some technical problem. Please try again');"), true);
        }        
    }
    private void refundamount()
    {
        Random rand = new Random();
        rand.Next(0, 1);
        for (int i = 0; i <= 1; i++)
        {
            transactionid = RandomString(rand, 12);
        }
        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)
                {
                    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
                    {
                        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)
            {
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('There is some technical problem. Please try again');"), true);
            }
        }
        if (ddl_Actiononamount.SelectedItem.Text == "Credit")
        {
            try
            {
                userdetails();
                requestbalance = Convert.ToDecimal(txt_Amount.Text);
                if (requestbalance < balance)
                {                    
                    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
                    {
                        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;
                }
            }
            catch (Exception ex)
            {
                Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('There is some technical problem. Please try again');"), true);
            }
        }
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        try
        {
            refundamount();
        }
        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"]);
            }
        }
        catch (Exception ex)
        {
            Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "OhCrap", String.Format("alert('There is some technical problem. Please try again');"), true);
        }
    }
   
}
