using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using System.Configuration;
using MySql.Data.MySqlClient;
using MySql.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using SunWeb.Model;
using System.Web.Services;
using CLS_BL;
using CLS_DL;
using CLS_PL;
using log4net.Repository.Hierarchy;

namespace SUNWEB
{
    public partial class CampaignAdjustment : System.Web.UI.Page
    {
        BL_API ObjApi = new BL_API();
        BL_API objAPI = new BL_API();
        BL_SELECT ObjSel = new BL_SELECT();
        BLCompany ObjBL = new BLCompany();
        PLCOMMON ObjPL = new PLCOMMON();
        JSONTODATATABLE DTJson = new JSONTODATATABLE();
        BL_USER ObjUserBL = new BL_USER(); //This Object for All User and Page Related fuctions included 
        PLCUSTOMER ObjCustPL = new PLCUSTOMER();
        Int32 K = 0;
        Int32 L = 0;
        Int32 S = 0;
        string ConStr = ConfigurationManager.ConnectionStrings["ConMysql"].ConnectionString;
        string ConStr_Rds = ConfigurationManager.ConnectionStrings["ConRDS"].ConnectionString;
        string Curr_Date = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        string Curr_DateOnly = System.DateTime.Now.ToString("yyyy-MM-dd");
        DateTime MonthstartDt;
        DataSet ds = new DataSet();
        MYSQLDB ObjMain = new MYSQLDB();
        DataTable DT = new DataTable();
        DataTable Dt2 = new DataTable();
        DataTable DtLicense = new DataTable();
        DataTable DtSuperAdmin = new DataTable();
        DataTable DtMultiBranch = new DataTable();
        DataTable DtNormalUser = new DataTable();
        DataTable DTProductSale = new DataTable();
        MySqlCommand Cmdv = new MySqlCommand();
        DataTable DtMemberList = new DataTable();
        DataTable DTMemberDL = new DataTable();
        // User Variables 
        string UserId = string.Empty;
        string UserName = string.Empty;
        string PortalTypeId = string.Empty;
        string cd_Id = string.Empty;
        string Datapath = string.Empty;
        string cd_BranchAlias = string.Empty;
        string IsMultiBranch = string.Empty;
        string IsSuperAdmin = string.Empty;
        string ActiveCallvalue = string.Empty;
        // License Variables ..
        string PID = string.Empty;
        string Page_Acess = string.Empty;
        string Read_Acess = string.Empty;
        string Write_Acess = string.Empty;
        string Isdowld_Acess = string.Empty;
        string Rcd_id = string.Empty;
        string RPortalid = string.Empty;
        string Useridvalue = string.Empty;
        string QueryCurr_Select = string.Empty;
        string L_MaxUserCnt = string.Empty;

        string L_compaignAdjustment = string.Empty;
        string Branchidval = string.Empty;
        string BranchFullName = string.Empty;
        string Curr_BranchFullName = string.Empty;
        string Cmb_BranchName = string.Empty;

        string HQ = string.Empty;
        string Cm_id = string.Empty;
        string ISHQ = string.Empty;
        DataSet DS = new DataSet();
        string Vw_Chk = string.Empty;
        string RBranchid = string.Empty;
        string Branchid = string.Empty;
        string ReadHQ = string.Empty;
        string BranchAlias = string.Empty;

        string MobValue;
        string Ins_CustQuery = string.Empty;
        string RCustomerID = string.Empty;

        string AES_Key = string.Empty;
        string en_userName = string.Empty;

        string en_CustomerName = string.Empty;
        string en_Mobile = string.Empty;
        string en_password = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {
            PID = "51";                   // This is for CompaignAdjustment Page 
            customeridmsg.Visible = false;
            customeridmsg1.Visible = false;

            if (!IsPostBack)
            {

            }
            MonthstartDt = new DateTime(System.DateTime.Now.Year, System.DateTime.Now.Month, 1);
            if (Session["UserName"] == null)
            {
                Response.Redirect("Login.aspx");
            }
            if (((Convert.ToBoolean(Session["IsSuperAdmin"])) == true) && (Session["PortalTypeId"].ToString() == "") && ((Convert.ToBoolean(Session["IsMultiBranch"])) == true))
            {
                if (!IsPostBack)
                {
                    LoadBranchesOnID();

                    string QueryCal = "select ActiveValue from portaldb.usermaster  where Userid=" + Session["UserId"].ToString() + " ";
                    ActiveCallvalue = ObjMain.ExecuteScalar(QueryCal);
                    if (ActiveCallvalue != " " || ActiveCallvalue != "Select Branch")
                    {
                        ActiveCall();
                    }
                }
            }
            else if (((Convert.ToBoolean(Session["IsSuperAdmin"])) == true) && (Session["PortalTypeId"].ToString() == ""))
            {
                if (!IsPostBack)
                {
                    LoadBranchName4SuperAdmin();
                }
                cd_BranchAlias = cmbBranches.SelectedItem.Text;
                //LoadInventoryListGrid(cd_BranchAlias, txtStartDt.Text, txtEndDt.Text);
            }
            else if (((Convert.ToBoolean(Session["IsMultiBranch"])) == true) && (Session["PortalTypeId"].ToString() == ""))
            {
                if (!IsPostBack)
                {
                    LoadBranchName();
                    ActiveCall();
                }
            }
            else if (((Session["PortalTypeId"].ToString() != "") || (Convert.ToBoolean(Session["IsSuperAdmin"])) == false) && ((Convert.ToBoolean(Session["IsMultiBranch"])) == false))
            {
                cmbBranches.Enabled = false;
                cmbBranches.Visible = false;

                Cm_id = ObjSel.GETcmid(Session["Cd_Id"].ToString());  // Get cm_id
                HQ = ObjSel.Get_HQ(Cm_id);     // Get the HQ Value
                Curr_BranchFullName = ObjSel.GetBranchFullName(HQ, Session["Branch_HQ"].ToString());
                lblBranchAliasName.ForeColor = System.Drawing.Color.DodgerBlue;
                lblBranchAliasName.Text = "Branch Name" + "&nbsp;" + "-" + "&nbsp;" + Curr_BranchFullName + "&nbsp; ";

                cd_BranchAlias = Session["Branch_HQ"].ToString();
                Datapath = Session["DataPath"].ToString();
                PortalTypeId = Session["PortalTypeId"].ToString();

                DT = ObjUserBL.GetPageRightsDetailsPid(Session["UserId"].ToString(), PID);
                if (DT.Rows.Count > 0)
                {
                    Page_Acess = DT.Rows[0]["Acess_status"].ToString();
                    Read_Acess = DT.Rows[0]["Read_Access"].ToString();
                    Write_Acess = DT.Rows[0]["Write_Access"].ToString();
                    Isdowld_Acess = DT.Rows[0]["IDwld_Access"].ToString();

                    Session["Page_Acess"] = Page_Acess;
                    Session["Read_Acess"] = Read_Acess;
                    Session["Write_Acess"] = Write_Acess;
                    Session["Isdowld_Acess"] = Isdowld_Acess;
                }
                if ((Session["L_compaignAdjustment"].ToString() == "N") || (Session["Page_Acess"].ToString() == "N"))
                {
                    Response.Redirect("DeniedPage.aspx");
                }
                else
                {
                    // lblMsgTotalSelection.Text = "Item Sale  Between" + "&nbsp;&nbsp;&nbsp;&nbsp;" + txtStartDt.Text + "&nbsp;&nbsp;&nbsp;  and  &nbsp;&nbsp;&nbsp;" + txtEndDt.Text;
                    if (!IsPostBack)
                    {
                        if (Session["Isdowld_Acess"].ToString() == "N")
                        {
                            // btnExcel.Enabled = false;
                            Response.Write(@"<script language='javascript'>alert('No Access To download.')</script>");
                        }
                        else
                        {


                            if (cmbBranches.Visible == false)
                            {
                                //  BindGridview(Session["Branch_HQ"].ToString(), txtStartDt.Text, txtEndDt.Text);
                            }

                        }


                    }

                }

            }
            else
            {

            }


        }

        public void LoadBranchesOnID()
        {
            DT = ObjUserBL.GetBranchIDList(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), Session["CM_ID"].ToString());
            StringBuilder StrBObj = new StringBuilder();

            for (int i = 0; i < DT.Rows.Count; i++)
            {
                DataRow dr = DT.Rows[i];
                RBranchid = dr["Branchid"].ToString();
                if (StrBObj.Length != 0)
                {
                    RBranchid = "," + RBranchid;
                    StrBObj.Append("  " + RBranchid + "");
                }
                else
                {
                    string _get_HQ = ObjSel.GetHQ_Status(Session["CM_ID"].ToString());
                    if (_get_HQ == "0")
                    {
                        //UPDATEBRANCH(Cmb_BranchName);
                        //Response.Redirect(Request.RawUrl);
                        Branchid = RBranchid;
                        StrBObj.Append("SELECT  Branchid ,BranchName,branchfullname,datapath FROM " + Session["Branch_HQ"].ToString() + ".branches where branchid in ( " + Branchid + " ");
                    }
                    else if (_get_HQ == "1")
                    {
                        Branchid = RBranchid;
                        StrBObj.Append("SELECT  Branchid ,BranchName,branchfullname,datapath FROM " + Session["Branch_HQ"].ToString() + ".branches where branchid in (1 , " + Branchid + " ");
                    }


                }


            }
            StrBObj.Append(")");
            Dt2 = ObjMain.GetData_DT(StrBObj.ToString());

            if (Dt2.Rows.Count > 0)
            {
                cmbBranches.DataSource = Dt2;
                cmbBranches.DataTextField = "branchfullname";
                cmbBranches.DataValueField = "Branchid";
                cmbBranches.DataBind();
                cmbBranches.Items.Insert(0, "Select Branch");
            }

        }




        public void Load_CampaingnType()
        {
            cmbCampaignType.Items.Add("Cash Back");
            cmbCampaignType.Items.Add("Points");
            cmbCampaignType.Items.Insert(0, "Select CampaignType");
            cmbCampaignType.DataBind();

        }
        public void ActiveCall()
        {
            string QueryCal = "select ActiveValue from portaldb.usermaster  where Userid=" + Session["UserId"].ToString() + " ";
            ActiveCallvalue = ObjMain.ExecuteScalar(QueryCal);
            if (ActiveCallvalue == "")
            {
                ActiveCallvalue = ObjSel.GetFirstBranch(Session["Branch_HQ"].ToString());
            }


            ISHQ = ObjMain.ExecuteScalar("select BranchName from " + ActiveCallvalue + ".branches where Branchname='" + ActiveCallvalue + "' and branchID=1;");  //now 

            if (ISHQ != "")
            {
                // ActiveCallvalue = ObjSel.GetFirstBranch(Session["Branch_HQ"].ToString());
                UPDATEBRANCH(ActiveCallvalue);
            }


            if (ActiveCallvalue.Contains("hq"))
            {

                cmbBranches.Items.FindByText("HQ").Selected = true;


                //  Call the Loading Functions 
                System.Threading.Thread.Sleep(2000);
                Session["BranchDB"] = ActiveCallvalue;
                ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "LoadcompaignTypeText('" + Session["BranchDB"].ToString() + "');", true);
                ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "LoadcompaignTypeText2('" + Session["BranchDB"].ToString() + "');", true);
                // Getting The Current Page Name 
                //_pagename will return CampaignAdjustment.aspx
                string _pagename = System.IO.Path.GetFileName(Request.Url.ToString());
                if (_pagename.Equals("CampaignAdjustment.aspx"))
                {
                    Cmb_BranchName = Session["Branch_HQ"].ToString();

                    if (!IsPostBack)
                    {
                        Load_Campaingn();
                        Load_CampaingnType();
                    }



                    LoadMemberDataList(Cmb_BranchName);
                    LoadMemberDataList1(Cmb_BranchName);
                }


            }
            else
            {
                cd_BranchAlias = ActiveCallvalue;
                Curr_BranchFullName = ObjUserBL.GetBranchCurr_BranchVal(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), cd_BranchAlias);
                Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), Curr_BranchFullName);  // This will Return BranchName( Actual Database Name )
                Session["BranchDB"] = Cmb_BranchName;
                cmbBranches.Items.FindByText(Curr_BranchFullName).Selected = true;
                Branchidval = ObjUserBL.GetBranchIDbyName(ActiveCallvalue, ActiveCallvalue);

                if (Branchidval != "")
                {
                    DT = ObjUserBL.GetPageRightsDetailsPIDNew(Session["UserId"].ToString(), PID, Branchidval);
                }
                else
                {
                    DT = ObjUserBL.GetPageRightsDetailsPIDNew(Session["UserId"].ToString(), PID, Session["Fistbranch"].ToString());

                }


                if (DT.Rows.Count > 0)
                {
                    Page_Acess = DT.Rows[0]["Acess_status"].ToString();
                    Read_Acess = DT.Rows[0]["Read_Access"].ToString();
                    Write_Acess = DT.Rows[0]["Write_Access"].ToString();
                    Isdowld_Acess = DT.Rows[0]["IDwld_Access"].ToString();

                    Session["Page_Acess"] = Page_Acess;
                    Session["Read_Acess"] = Read_Acess;
                    Session["Write_Acess"] = Write_Acess;
                    Session["Isdowld_Acess"] = Isdowld_Acess;
                }
                Rcd_id = ObjMain.ExecuteScalar("select cd_id from portaldb.companydetails where cd_branchid=" + cmbBranches.SelectedItem.Value + " and cd_branchalias='" + ActiveCallvalue + "';");
                RPortalid = ObjMain.ExecuteScalar("select portaltypeid  from portaldb.invoicedetails where cd_id=" + Rcd_id + ";");
                DtLicense = ObjUserBL.GetLicenseDetails(RPortalid);
                if (DtLicense.Rows.Count > 0)
                {
                    L_compaignAdjustment = DtLicense.Rows[0]["CAMPAIGNADJUSTMENT"].ToString();
                    Session["L_compaignAdjustment"] = L_compaignAdjustment;
                }
                if (Session["L_compaignAdjustment"].ToString() == "N" || Session["Page_Acess"].ToString() == "N")
                {
                    Response.Redirect("DeniedPage.aspx");
                }
                else
                {
                    cd_BranchAlias = cmbBranches.SelectedItem.Text;
                    //  Call the Loading Functions 
                    System.Threading.Thread.Sleep(2000);

                    ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "LoadcompaignTypeText('" + Session["BranchDB"].ToString() + "');", true);
                    ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "LoadcompaignTypeText2('" + Session["BranchDB"].ToString() + "');", true);
                    // Getting The Current Page Name 
                    //_pagename will return CampaignAdjustment.aspx
                    string _pagename = System.IO.Path.GetFileName(Request.Url.ToString());
                    if (_pagename.Equals("CampaignAdjustment.aspx"))
                    {
                        Cmb_BranchName = Session["Branch_HQ"].ToString();


                        if (!IsPostBack)
                        {
                            Load_Campaingn();
                            Load_CampaingnType();
                        }

                        LoadMemberDataList(Cmb_BranchName);
                        LoadMemberDataList1(Cmb_BranchName);
                    }
                }



            }




        }

        public void LoadBranchName()
        {
            DtNormalUser = ObjUserBL.GetBranchOnLoginValues8(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), Session["CM_ID"].ToString());
            if (DtNormalUser.Rows.Count > 0)
            {
                cmbBranches.DataSource = DtNormalUser;
                cmbBranches.DataTextField = "branchfullname";
                cmbBranches.DataValueField = "Branchid";
                cmbBranches.DataBind();
                cmbBranches.Items.Insert(0, "Select Branch");
            }
        }
        public void LoadBranchName4SuperAdmin()
        {
            DtSuperAdmin = ObjUserBL.GetBranchOnSuperAdmin8(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), Session["CM_ID"].ToString());
            if (DtSuperAdmin.Rows.Count > 0)
            {
                cmbBranches.DataSource = DtSuperAdmin;
                cmbBranches.DataTextField = "branchfullname";
                cmbBranches.DataValueField = "Branchid";
                cmbBranches.DataBind();
                cmbBranches.Items.Insert(0, "Select Branch");
            }
        }
        public void UPDATEBRANCH(string ActiveCallvalue)
        {
            if (!string.IsNullOrEmpty(Session["UserId"] as string))
            {
                Useridvalue = Session["UserId"].ToString();
                QueryCurr_Select = "Update portaldb.usermaster set ActiveValue='" + ActiveCallvalue + "' where Userid=" + Useridvalue + "";
                S = ObjMain.ExecuteNonQuery(QueryCurr_Select);
            }
            else
            {
                Response.Redirect("Login.aspx");

            }

        }


        protected void btnGetReports_Click(object sender, EventArgs e)
        {

        }

        protected void cmbBranches_SelectedIndexChanged(object sender, EventArgs e)
        {

            string Is_CashBack = "";
            string Is_PointRedemption = "";

            if (cmbBranches.SelectedIndex == 0)
            {
                Response.Write("CampaignAdjustment.aspx");
            }
            else
            {
                DT = ObjUserBL.GetPageRightsDetailsPIDNew(Session["UserId"].ToString(), PID, cmbBranches.SelectedItem.Value);
                if (DT.Rows.Count > 0)
                {
                    Page_Acess = DT.Rows[0]["Acess_status"].ToString();
                    Read_Acess = DT.Rows[0]["Read_Access"].ToString();
                    Write_Acess = DT.Rows[0]["Write_Access"].ToString();
                    Isdowld_Acess = DT.Rows[0]["IDwld_Access"].ToString();
                    Session["Page_Acess"] = Page_Acess;
                    Session["Read_Acess"] = Read_Acess;
                    Session["Write_Acess"] = Write_Acess;
                    Session["Isdowld_Acess"] = Isdowld_Acess;
                }

                if (cmbBranches.SelectedIndex == 1)
                {

                    BranchFullName = cmbBranches.SelectedItem.Text;    // This will Return Branch FullName 
                    Cmb_BranchName = ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), BranchFullName);
                    UPDATEBRANCH(Cmb_BranchName);
                    Session["BranchDB"] = Cmb_BranchName;
                }
                else
                {
                    BranchFullName = cmbBranches.SelectedItem.Text;    // This will Return Branch FullName 
                    Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);  // This will Return BranchName( Actual Database Name )
                    Rcd_id = ObjMain.ExecuteScalar("select cd_id from portaldb.companydetails where cd_branchid=" + cmbBranches.SelectedItem.Value + " and cd_branchalias='" + Cmb_BranchName + "';");
                    RPortalid = ObjMain.ExecuteScalar("select portaltypeid  from portaldb.invoicedetails where cd_id=" + Rcd_id + ";");
                    DtLicense = ObjUserBL.GetLicenseDetails(RPortalid);
                    Session["BranchDB"] = Cmb_BranchName;
                }
                if (DtLicense.Rows.Count > 0)
                {
                    L_compaignAdjustment = DtLicense.Rows[0]["CAMPAIGNADJUSTMENT"].ToString();
                    Session["L_compaignAdjustment"] = L_compaignAdjustment;
                }
                if ((Session["L_compaignAdjustment"] == null) || Session["L_compaignAdjustment"].ToString() == "N" || Session["Page_Acess"].ToString() == "N")
                {
                    if (cmbBranches.SelectedIndex == 1)
                    {
                        // btnExcel.Enabled = true;
                        #region  Validation Between HQ Branch and Normal Branch 
                        BranchFullName = cmbBranches.SelectedItem.Text;          // This will Return Branch FullName 
                        if (BranchFullName == "HQ")
                        {
                            BranchAlias = Session["Branch_HQ"].ToString();
                        }
                        else
                        {
                            BranchFullName = cmbBranches.SelectedItem.Text;      // This will Return Branch FullName 
                            Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);  // This will Return BranchName( Actual Database Name )
                            BranchAlias = Cmb_BranchName;
                        }

                        Is_CashBack = Get_Generic_Webordingini(BranchAlias, "46");
                        Is_PointRedemption = Get_Generic_Webordingini(BranchAlias, "47");

                        if (Is_CashBack == "1")
                        {
                            ClearForms();
                            ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "LoadcompaignTypeText('" + Session["BranchDB"].ToString() + "');", true);
                        }
                        if (Is_PointRedemption == "1")
                        {
                            ClearForms();
                            ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "LoadcompaignTypeText2('" + Session["BranchDB"].ToString() + "');", true);
                        }


                        #endregion
                        string _pagename = System.IO.Path.GetFileName(Request.Url.ToString());
                        if (_pagename.Equals("CampaignAdjustment.aspx"))
                        {
                            Cmb_BranchName = Session["Branch_HQ"].ToString();

                            if (!IsPostBack)
                            {
                                Load_Campaingn();
                                Load_CampaingnType();

                            }

                            LoadMemberDataList(Cmb_BranchName);
                            LoadMemberDataList1(Cmb_BranchName);

                        }
                    }
                    else
                    {
                        Response.Redirect("DeniedPage.aspx");
                    }
                }
                else if (Session["Write_Acess"].ToString() == "N")
                {
                    Response.Redirect("DeniedPage.aspx");
                }
                else
                {
                    #region  Validation Between HQ Branch and Normal Branch 
                    BranchFullName = cmbBranches.SelectedItem.Text;             // This will Return Branch FullName 
                    if (BranchFullName == "HQ")
                    {
                        BranchAlias = Session["Branch_HQ"].ToString();
                    }
                    else
                    {
                        BranchFullName = cmbBranches.SelectedItem.Text;         // This will Return Branch FullName 
                        Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);  // This will Return BranchName( Actual Database Name )
                        BranchAlias = Cmb_BranchName;
                    }
                    Session["BranchDB"] = BranchAlias;
                    #endregion
                    string _pagename = System.IO.Path.GetFileName(Request.Url.ToString());
                    if (_pagename.Equals("CampaignAdjustment.aspx"))
                    {
                        Cmb_BranchName = Session["Branch_HQ"].ToString();
                        if (!IsPostBack)
                        {
                            Load_Campaingn();
                            Load_CampaingnType();

                        }
                        LoadMemberDataList(Cmb_BranchName);
                        LoadMemberDataList1(Cmb_BranchName);

                    }

                }
            }
            UPDATEBRANCH(BranchAlias);
            Is_CashBack = Get_Generic_Webordingini(BranchAlias, "46");
            Is_PointRedemption = Get_Generic_Webordingini(BranchAlias, "47");
            if (Is_CashBack == "1")
            {
                ClearForms();
                ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "LoadcompaignTypeText('" + Session["BranchDB"].ToString() + "');", true);
            }
            if (Is_PointRedemption == "1")
            {
                ClearForms();
                ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "LoadcompaignTypeText2('" + Session["BranchDB"].ToString() + "');", true);
            }


        }

        protected void btnMemSearch_Click(object sender, EventArgs e)
        {
            BranchAlias = Session["Branch_HQ"].ToString();
            Load_SearchData(BranchAlias, txtMobSearch.Text.ToString().Trim());
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ShowModalMemberInformationList();", true);
        }

        public void Load_SearchData(string BranchNam, string SearchTxt)
        {


            if (cmbBranches.Visible == false)
            {

                BranchAlias = Session["Branch_HQ"].ToString();

            }
            else
            {
                BranchFullName = cmbBranches.SelectedItem.Text;     // This will Return Branch FullName 
                Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);  // This will Return BranchName( Actual Database Name )
                BranchAlias = Session["Branch_HQ"].ToString();
            }


            #region UserName Decrption 
            if (Cmb_BranchName != "")
            {
                AES_Key = ObjApi.Get_AESKey(Cmb_BranchName);
                en_userName = ObjSel.EncryptString(SearchTxt, AES_Key);
            }


            #endregion


            //string QuerySrc = "Select CustomerID,Mobile,CustomerName  From   {0}.icustomers  Where  Mobile like CONCAT('%', @Mobile, '%')  ;";
            string QuerySrc = "Select CustomerID,UserName,CustomerName  From   {0}.icustomers  Where  UserName=@UserName;";
            string command = string.Format(QuerySrc, BranchAlias);

            MySqlParameter[] parameters =
                   {
                     new MySqlParameter("@UserName",en_userName),
                   };

            DtMemberList = ObjMain.NewGetData_DT(command, parameters);


            DataTable temp_dt = new DataTable();

            if (DtMemberList.Rows.Count > 0)
            {

                for (int i = 0; i < DtMemberList.Rows.Count; i++)
                {

                    string _dt_customerid = DtMemberList.Rows[0]["CustomerID"].ToString();
                    string _dt_UserName = DtMemberList.Rows[0]["UserName"].ToString();
                    string _dt_CustomerName = DtMemberList.Rows[0]["CustomerName"].ToString();



                    if (temp_dt.Rows.Count > 0)
                    {
                        DataRow Dr = temp_dt.NewRow();
                        Dr["CustomerID"] = _dt_customerid;
                        Dr["UserName"] = ObjSel.DecryptString(_dt_UserName, AES_Key);
                        Dr["CustomerName"] = ObjSel.DecryptString(_dt_CustomerName, AES_Key);

                        temp_dt.Rows.Add(Dr);
                    }
                    else
                    {
                        temp_dt.Columns.Add("CustomerID", typeof(string));
                        temp_dt.Columns.Add("UserName", typeof(string));
                        temp_dt.Columns.Add("CustomerName", typeof(string));

                        DataRow Dr = temp_dt.NewRow();
                        Dr["CustomerID"] = _dt_customerid;
                        Dr["UserName"] = ObjSel.DecryptString(_dt_UserName, AES_Key);
                        Dr["CustomerName"] = ObjSel.DecryptString(_dt_CustomerName, AES_Key);

                        temp_dt.Rows.Add(Dr);
                    }


                }

                grdMember.DataSource = temp_dt;
                grdMember.DataBind();
            }
            else
            {
                customeridmsg.Visible = true;
                grdMember.DataSource = null;
                grdMember.DataBind();
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ShowModalIcustomers();", true);

            }




        }

        public void Load_SearchData1(string BranchNam, string SearchTxt)
        {

            if (cmbBranches.Visible == false)
            {

                BranchAlias = Session["Branch_HQ"].ToString();

            }
            else
            {
                BranchFullName = cmbBranches.SelectedItem.Text;     // This will Return Branch FullName 
                Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);  // This will Return BranchName( Actual Database Name )
                BranchAlias = Session["Branch_HQ"].ToString();
            }


            #region UserName Decrption 
            if (BranchAlias != "")
            {
                AES_Key = ObjApi.Get_AESKey(Cmb_BranchName);
                en_userName = ObjSel.EncryptString(SearchTxt, AES_Key);
            }


            #endregion


            //string QuerySrc = "Select CustomerID,Mobile,CustomerName  From   {0}.icustomers  Where  Mobile like CONCAT('%', @Mobile, '%')  ;";
            string QuerySrc = "Select CustomerID,UserName,CustomerName  From   {0}.icustomers  Where  UserName=@UserName;";
            string command = string.Format(QuerySrc, BranchAlias);

            MySqlParameter[] parameters =
                   {
                     new MySqlParameter("@UserName",en_userName),
                   };

            DtMemberList = ObjMain.NewGetData_DT(command, parameters);


            DataTable temp_dt = new DataTable();

            if (DtMemberList.Rows.Count > 0)
            {

                for (int i = 0; i < DtMemberList.Rows.Count; i++)
                {

                    string _dt_customerid = DtMemberList.Rows[0]["CustomerID"].ToString();
                    string _dt_UserName = DtMemberList.Rows[0]["UserName"].ToString();
                    string _dt_CustomerName = DtMemberList.Rows[0]["CustomerName"].ToString();



                    if (temp_dt.Rows.Count > 0)
                    {
                        DataRow Dr = temp_dt.NewRow();
                        Dr["CustomerID"] = _dt_customerid;
                        Dr["UserName"] = ObjSel.DecryptString(_dt_UserName, AES_Key);
                        Dr["CustomerName"] = ObjSel.DecryptString(_dt_CustomerName, AES_Key);

                        temp_dt.Rows.Add(Dr);
                    }
                    else
                    {
                        temp_dt.Columns.Add("CustomerID", typeof(string));
                        temp_dt.Columns.Add("UserName", typeof(string));
                        temp_dt.Columns.Add("CustomerName", typeof(string));

                        DataRow Dr = temp_dt.NewRow();
                        Dr["CustomerID"] = _dt_customerid;
                        Dr["UserName"] = ObjSel.DecryptString(_dt_UserName, AES_Key);
                        Dr["CustomerName"] = ObjSel.DecryptString(_dt_CustomerName, AES_Key);

                        temp_dt.Rows.Add(Dr);
                    }


                }

                grdMember1.DataSource = temp_dt;
                grdMember1.DataBind();
            }
            else
            {
                customeridmsg1.Visible = true;
                grdMember1.DataSource = null;
                grdMember1.DataBind();
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ShowModalIcustomers1();", true);

            }


        }

        public void LoadMemberDataList(string sDb)
        {

            if (cmbBranches.Visible == false)
            {

                BranchAlias = Session["Branch_HQ"].ToString();

            }
            else
            {
                BranchFullName = cmbBranches.SelectedItem.Text;     // This will Return Branch FullName 
                Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);  // This will Return BranchName( Actual Database Name )
                BranchAlias = Session["Branch_HQ"].ToString();
            }

            DtMemberList = ObjSel.GetMemberList(BranchAlias);
            DataTable temp_dt = new DataTable();

            #region UserName Decrption 
            if (Cmb_BranchName != "")
            {
                AES_Key = ObjApi.Get_AESKey(Cmb_BranchName);

            }


            #endregion


            if (DtMemberList.Rows.Count > 0)
            {
                foreach (DataRow row in DtMemberList.Rows)
                {
                    string value = row.Field<string>("UserName");
                    row.SetField("UserName", ObjSel.DecryptString(value, AES_Key));
                    string value1 = row.Field<string>("CustomerName");
                    row.SetField("CustomerName", ObjSel.DecryptString(value1, AES_Key));

                }
                grdMember.DataSource = DtMemberList;
                grdMember.DataBind();

            }



            //if (DtMemberList.Rows.Count > 0)
            //{




            //    for (int i = 0; i < DtMemberList.Rows.Count; i++)
            //    {
            //        string _dt_customerid = string.Empty;
            //        string _dt_UserName = string.Empty;
            //        string _dt_CustomerName = string.Empty;


            //        _dt_customerid = DtMemberList.Rows[i]["CustomerID"].ToString();
            //        _dt_UserName = DtMemberList.Rows[i]["UserName"].ToString();
            //        _dt_CustomerName = DtMemberList.Rows[i]["CustomerName"].ToString();
            //        if (temp_dt.Rows.Count > 0)
            //        {
            //            DataRow Dr = temp_dt.NewRow();
            //            Dr["CustomerID"] = _dt_customerid;
            //            Dr["UserName"] = ObjSel.DecryptString(_dt_UserName, AES_Key);
            //            Dr["CustomerName"] = ObjSel.DecryptString(_dt_CustomerName, AES_Key);
            //            temp_dt.Rows.Add(Dr);
            //        }
            //        else
            //        {
            //            temp_dt.Columns.Add("CustomerID", typeof(string));
            //            temp_dt.Columns.Add("UserName", typeof(string));
            //            temp_dt.Columns.Add("CustomerName", typeof(string));

            //            DataRow Dr = temp_dt.NewRow();
            //            Dr["CustomerID"] = _dt_customerid;
            //            Dr["UserName"] = ObjSel.DecryptString(_dt_UserName, AES_Key);
            //            Dr["CustomerName"] = ObjSel.DecryptString(_dt_CustomerName, AES_Key);

            //            temp_dt.Rows.Add(Dr);
            //        }


            //    }
            //    grdMember.DataSource = temp_dt;
            //    grdMember.DataBind();
            //}

        }

        public void LoadMemberDataList1(string sDb)
        {

            if (cmbBranches.Visible == false)
            {

                BranchAlias = Session["Branch_HQ"].ToString();

            }
            else
            {
                BranchFullName = cmbBranches.SelectedItem.Text;     // This will Return Branch FullName 
                Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);  // This will Return BranchName( Actual Database Name )
                BranchAlias = Session["Branch_HQ"].ToString();
            }

            DtMemberList = ObjSel.GetMemberList(BranchAlias);
            DataTable temp_dt = new DataTable();

            #region UserName Decrption 
            if (Cmb_BranchName != "")
            {
                AES_Key = ObjApi.Get_AESKey(Cmb_BranchName);

            }


            #endregion


            if (DtMemberList.Rows.Count > 0)
            {
                foreach (DataRow row in DtMemberList.Rows)
                {
                    string value = row.Field<string>("UserName");
                    row.SetField("UserName", ObjSel.DecryptString(value, AES_Key));
                    string value1 = row.Field<string>("CustomerName");
                    row.SetField("CustomerName", ObjSel.DecryptString(value1, AES_Key));
                }

                grdMember1.DataSource = DtMemberList;
                grdMember1.DataBind();
            }





        }

        protected void grdMember_SelectedIndexChanged(object sender, EventArgs e)
        {
            // XSS Attack Prevention 
            if (cmbBranches.Visible == false)
            {
                BranchAlias = Session["Branch_HQ"].ToString();
            }
            else
            {
                if (cmbBranches.SelectedItem.Text == "HQ")
                {
                    // btnExcel.Enabled = true;
                    // HQ Validation    02-12-21
                    BranchFullName = cmbBranches.SelectedItem.Text;    // This will Return Branch FullName 
                    Cmb_BranchName = ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), BranchFullName);
                    UPDATEBRANCH(Cmb_BranchName);
                    BranchAlias = Session["Branch_HQ"].ToString();
                }
                else
                {
                    BranchFullName = cmbBranches.SelectedItem.Text;     // This will Return Branch FullName 
                    Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);  // This will Return BranchName( Actual Database Name )
                    BranchAlias = Cmb_BranchName;
                }
            }


            string Is_CashBack = Get_Generic_Webordingini(BranchAlias, "46");
            string Is_PointRedemption = Get_Generic_Webordingini(BranchAlias, "47");
            string Is_Membership = Get_Generic_Webordingini(BranchAlias, "45");
            string _lpid = string.Empty;

            if (Is_CashBack == "1")
            {
                // show the cashback rate 
                ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "LoadcompaignTypeText('" + Session["BranchDB"].ToString() + "');", true);

                #region UserName Decrption 
                if (Cmb_BranchName != "")
                {
                    AES_Key = ObjApi.Get_AESKey(Cmb_BranchName);

                }
                #endregion

                RCustomerID = (grdMember.SelectedRow.FindControl("lblCustomerID") as Label).Text;
                DTMemberDL = ObjSel.ReadMemberInformations(Session["Branch_HQ"].ToString(), RCustomerID);

                txtCID.Text = DTMemberDL.Rows[0]["CID"].ToString();
                string R_customerName = DTMemberDL.Rows[0]["CustomerName"].ToString();
                string r_username = DTMemberDL.Rows[0]["UserName"].ToString();
                txtUserName.Text = ObjSel.DecryptString(r_username, AES_Key);
                txtCustomerName.Text = ObjSel.DecryptString(R_customerName, AES_Key);


                hidMembershipType.Value = DTMemberDL.Rows[0]["MembershipType"].ToString();
                txtActiveCompaignType.Text = "Cashback";

                #region Read Membership  Information  
                string BarerTokenVal = objAPI.GetBarerToken();
                string _membership_result = objAPI.iCRM_GetMembershipByMembershipId(Session["Branch_HQ"].ToString(), BarerTokenVal, hidMembershipType.Value);
                var membership_json_result = JsonConvert.DeserializeObject(_membership_result).ToString();
                var _membership_result_values = JsonConvert.DeserializeObject<imembershipModel>(membership_json_result);
                string _membershipid = Convert.ToString(_membership_result_values.MembershipID);
                // Mid  
                string _mid = _membership_result_values.MID;
                // Membershipname 
                string _membershipname = _membership_result_values.MembershipName;
                // Cashback rate
                double _cashback_rate = _membership_result_values.CashBackRate;
                // Lpid 
                _lpid = _membership_result_values.LpID;
                string _regdate = Convert.ToString(_membership_result_values.RegistrationDate);
                // Assign cashback rate
                txtRate.Text = Convert.ToString(_cashback_rate);
                #endregion

                #region ReadCashBackValue 

                string _cashback_result = objAPI.iCRM_CashbackBalance_By_CID(Session["Branch_HQ"].ToString(), BarerTokenVal, txtCID.Text.ToString().Trim());
                var cashback_json_result = JsonConvert.DeserializeObject(_cashback_result).ToString();
                var _cashback_result_values = JsonConvert.DeserializeObject<CashBackBalanceModel>(cashback_json_result);
                string _cid = _cashback_result_values.CID;
                string _mobileno = _cashback_result_values.Mobile;
                // Cashback Balance Value 
                decimal _cashback_bal = _cashback_result_values.CashBackBalance;
                txtCurrentValue.Text = Convert.ToString(_cashback_bal);
                #endregion


            }
            if (Is_PointRedemption == "1")
            {
                // show the loyalty point rate 
                string BarerTokenVal = objAPI.GetBarerToken();
                ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "LoadcompaignTypeText2('" + Session["BranchDB"].ToString() + "');", true);


                #region UserName Decrption 
                if (Cmb_BranchName != "")
                {
                    AES_Key = ObjApi.Get_AESKey(Cmb_BranchName);

                }
                #endregion


                RCustomerID = (grdMember.SelectedRow.FindControl("lblCustomerID") as Label).Text;
                DTMemberDL = ObjSel.ReadMemberInformations(Session["Branch_HQ"].ToString(), RCustomerID);


                string username1 = DTMemberDL.Rows[0]["UserName"].ToString();
                txtUserName.Text = ObjSel.DecryptString(username1, AES_Key);
                txtCID.Text = DTMemberDL.Rows[0]["CID"].ToString();

                string customername1 = DTMemberDL.Rows[0]["CustomerName"].ToString();
                txtCustomerName.Text = ObjSel.DecryptString(customername1, AES_Key);
                hidMembershipType.Value = DTMemberDL.Rows[0]["MembershipType"].ToString();
                txtActiveCompaignType.Text = "Points";

                #region Read Membership  Information  

                string _membership_result = objAPI.iCRM_GetMembershipByMembershipId(Session["Branch_HQ"].ToString(), BarerTokenVal, hidMembershipType.Value);
                var membership_json_result = JsonConvert.DeserializeObject(_membership_result).ToString();
                var _membership_result_values = JsonConvert.DeserializeObject<imembershipModel>(membership_json_result);
                string _membershipid = Convert.ToString(_membership_result_values.MembershipID);
                // Mid  
                string _mid = _membership_result_values.MID;
                // Membershipname 
                string _membershipname = _membership_result_values.MembershipName;
                // Cashback rate
                double _cashback_rate = _membership_result_values.CashBackRate;
                // Lpid 
                _lpid = _membership_result_values.LpID;
                string _regdate = Convert.ToString(_membership_result_values.RegistrationDate);

                #endregion


                #region  Read the CurrentPoint 

                // Added Karthi  28-09-2024  : Need To Sync with Devazure Code 
                // Old Approach to Get the Balance Point By Cid
                //string result_currentPoint = objAPI.iCRM_Get_CurrentPointByCID(Session["Branch_HQ"].ToString(), BarerTokenVal, txtCID.Text.ToString().Trim());
                string result_currentPoint = objAPI.API_GET_ICurrentPoints(BarerTokenVal, Session["Branch_HQ"].ToString(), txtCID.Text.ToString().Trim());
                var json_currentpoint = JsonConvert.DeserializeObject(result_currentPoint).ToString();
                var json_curentpoint_values = JsonConvert.DeserializeObject<CurrentPointModel>(json_currentpoint);
                double _currentPoints = json_curentpoint_values.CurrentPoint;

                txtCurrentValue.Text = Convert.ToString(_currentPoints);
                #endregion

                #region Get the LPRate
                string Query_Selectj = "SELECT  LPRate  FROM {0}.iloyaltypoints WHERE  LPid='" + _lpid + "' ;";
                string commandj = string.Format(Query_Selectj, Session["Branch_HQ"].ToString());
                string _LpRate = ObjMain.ExecuteScalar(commandj);
                txtRate.Text = _LpRate;

                #endregion

            }


        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (cmbBranches.Visible == true)
            {
                #region  Validation Between HQ Branch and Normal Branch 
                BranchFullName = cmbBranches.SelectedItem.Text;                // This will Return Branch FullName 
                if (BranchFullName == "HQ")
                {
                    BranchAlias = Session["Branch_HQ"].ToString();
                }
                else
                {
                    BranchFullName = cmbBranches.SelectedItem.Text;            // This will Return Branch FullName 
                    Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);  // This will Return BranchName( Actual Database Name )
                    BranchAlias = Cmb_BranchName;

                }
                #endregion
            }
            else
            {
                BranchAlias = Session["Branch_HQ"].ToString();
            }

            // 1. Check is it under SuntoyoCrm  Throuhg PMS 
            string QueryA = "select Iscrm from portaldb.companydetails  where cd_branchalias='" + BranchAlias + "';";
            string Is_Suntoyo_CRM = ObjMain.ExecuteScalar(QueryA);

            if (Is_Suntoyo_CRM == "2")
            {
                string Is_Membership = Get_Generic_Webordingini(BranchAlias, "45");
                if (Is_Membership == "1")
                {


                    string Is_CashBack = Get_Generic_Webordingini(BranchAlias, "46");
                    string Is_PointRedemption = Get_Generic_Webordingini(BranchAlias, "47");
                    string BarerTokenVal = objAPI.GetBarerToken();
                    #region Read Membership  Information  
                    string _membership_result = objAPI.iCRM_GetMembershipByMembershipId(Session["Branch_HQ"].ToString(), BarerTokenVal, hidMembershipType.Value);
                    var membership_json_result = JsonConvert.DeserializeObject(_membership_result).ToString();
                    var _membership_result_values = JsonConvert.DeserializeObject<imembershipModel>(membership_json_result);
                    string _membershipid = Convert.ToString(_membership_result_values.MembershipID);

                    // Mid  
                    string _mid = _membership_result_values.MID;
                    // Membershipname 
                    string _membershipname = _membership_result_values.MembershipName;
                    // Cashback rate
                    double _cashback_rate = _membership_result_values.CashBackRate;
                    // Lpid 
                    string _lpid = _membership_result_values.LpID;
                    string _regdate = Convert.ToString(_membership_result_values.RegistrationDate);

                    // Get the PeId 
                    Int32 _PeID =   _membership_result_values.PeID;
                    // Using Peid get the Pemonth    
                    string _pemonth_result = objAPI.API_GET_PEMonths_By_Peid(BarerTokenVal, Session["Branch_HQ"].ToString(), _PeID);
                    var _pemonth_json_result = JsonConvert.DeserializeObject(_pemonth_result).ToString();
                    var _pemonth_result_values = JsonConvert.DeserializeObject<iPointExpiryMonths>(_pemonth_json_result);
                    // Read PeMonths
                    int  _R_PeMonths = _pemonth_result_values.PeMonths;


                    #endregion


                    #region  CashBack Adjustment 
                    if (Is_CashBack == "1")
                    {

                        string _prefix = "ADJC";
                        string _Generated_RefNo = _prefix + ObjSel.GeneratePointsAdjustNo(Session["Branch_HQ"].ToString());
                        #region ReadCashBackValue 

                        string _cashback_result = objAPI.iCRM_CashbackBalance_By_CID(Session["Branch_HQ"].ToString(), BarerTokenVal, txtCID.Text.ToString().Trim());
                        var cashback_json_result = JsonConvert.DeserializeObject(_cashback_result).ToString();
                        var _cashback_result_values = JsonConvert.DeserializeObject<CashBackBalanceModel>(cashback_json_result);



                        string _cid = string.Empty;
                        string _mobileno = string.Empty;
                        // Cashback Balance Value 
                        decimal _cashback_bal = _cashback_result_values.CashBackBalance;

                        if (_cid != "")
                        {
                            _cid = _cashback_result_values.CID;
                            _mobileno = _cashback_result_values.Mobile;
                        }
                        else
                        {
                            _cid = txtCID.Text.ToString().Trim();
                            _mobileno = txtUserName.Text.ToString().Trim();
                        }


                        #endregion

                        #region   CashBack-Adjustment Transaction in icashbacktrans Table 
                        //1.Insert cashback row (By Api)
                        // Parameters 
                        string cbid = Guid.NewGuid().ToString();
                        int transType = 0;
                        int transStatus = 0;
                        DateTime _TransDate = Convert.ToDateTime(DateTime.Now.ToString());
                        string _notes = txtNotes.Text;
                        decimal amount = Convert.ToDecimal(txtAdjustValue.Text);
                        // CashBack Transaction POST CALL 
                        iCRM_SendCashBackTransaction(cbid, _cid, _mobileno, _Generated_RefNo, transType, amount, Convert.ToDecimal(_cashback_rate), Convert.ToString(_TransDate), transStatus, Convert.ToString(cmbBranches.SelectedValue), _notes);
                        #endregion

                        decimal _cashback_new_Bal = Convert.ToDecimal(txtAdjustValue.Text) + _cashback_bal;

                        #region   Cashback Transaction Log  in ICompaignAdjustment  Table 
                        //2.Insert Adjustment row (by Query)
                        string QueryB = " Insert into {0}.ICompaignAdjustment(ReferenceNo,CID,Rate,PreviousCashbackValue,CashBackAdjAmount,CashBackBal," +
                                        " PreviousPoint,AdjustPoints,TotalPoints,CompaignType,Branch,Notes,CreatedBy,CreatedDate)" +
                                        " values(@ReferenceNo,@CID,@Rate,@PreviousCashbackValue,@CashBackAdjAmount,@CashBackBal,@PreviousPoint," +
                                        " @AdjustPoints,@TotalPoints,@CompaignType,@Branch,@Notes,@CreatedBy,@CreatedDate); ";
                        MySqlParameter[] mySqlParameters =
                           {
                                new MySqlParameter("@ReferenceNo",_Generated_RefNo),
                                new MySqlParameter("@CID", _cid),
                                new MySqlParameter("@Rate",Convert.ToDecimal(_cashback_rate)),
                                new MySqlParameter("@PreviousCashbackValue", _cashback_bal),
                                new MySqlParameter("@CashBackAdjAmount",Convert.ToDecimal(txtAdjustValue.Text)),
                                new MySqlParameter("@CashBackBal", _cashback_new_Bal),
                                new MySqlParameter("@PreviousPoint",0),
                                new MySqlParameter("@AdjustPoints",0),
                                new MySqlParameter("@TotalPoints",0),
                                new MySqlParameter("@CompaignType","CashBack"),
                                new MySqlParameter("@Branch", cmbBranches.SelectedItem.Text),
                                new MySqlParameter("@Notes",txtNotes.Text),
                                new MySqlParameter("@CreatedBy",txtCreatedBy.Text.ToString().Trim()),
                                new MySqlParameter("@CreatedDate",_TransDate),
                            };

                        string command = string.Format(QueryB, Session["Branch_HQ"].ToString());
                        K = ObjMain.ExecuteQuery(command, mySqlParameters);
                        if (K > 0)
                        {
                            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Cashback Adjustment added Successfully');location.href='CampaignAdjustment.aspx'", true);
                        }
                        else
                        {
                            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('Something went wrong ');location.href='CampaignAdjustment.aspx'", true);
                        }


                        #endregion

                    }
                    #endregion
                    #region Points Adjustmemt 
                    if (Is_PointRedemption == "1")
                    {
                        string _prefix = "ADJP";
                        string _Generated_RefNo = _prefix + ObjSel.GeneratePointsAdjustNo(Session["Branch_HQ"].ToString());
                        DateTime _TransDate = Convert.ToDateTime(DateTime.Now.ToString());
                        DateTime _DateofExpiry = Convert.ToDateTime(DateTime.Now.AddYears(1));
                        string _CashierID = "1";
                        int _TransStatus = 0;

                        #region Get the LPRate
                        string Query_Selectj = "SELECT  LPRate  FROM {0}.iloyaltypoints WHERE  LPid='" + _lpid + "' ;";
                        string commandj = string.Format(Query_Selectj, Session["Branch_HQ"].ToString());
                        string _LpRate = ObjMain.ExecuteScalar(commandj);
                        #endregion

                        #region Get the PointExpiryOn 
                        string Query_Select_PointExpiryOn = "SELECT PointExpiryOn  FROM {0}.iCurrentPoints WHERE CID='"+ txtCID.Text.ToString().Trim() + "' ;";
                        string command_Point_Expiry = string.Format(Query_Select_PointExpiryOn, Session["Branch_HQ"].ToString());
                        string _PointExpiry = ObjMain.ExecuteScalar(command_Point_Expiry);

                        DateTime _pointexpirydate = Convert.ToDateTime(Curr_Date).AddMonths(_R_PeMonths);
                        #endregion



                        // Added Karthi  28-09-2024  
                        // Old Approach to Get the Balance Point By Cid
                        //string result_currentPoint = objAPI.iCRM_Get_CurrentPointByCID(Session["Branch_HQ"].ToString(), BarerTokenVal, txtCID.Text.ToString().Trim());
                        string result_currentPoint = objAPI.API_GET_ICurrentPoints(BarerTokenVal, Session["Branch_HQ"].ToString(), txtCID.Text.ToString().Trim());
                        var json_currentpoint = JsonConvert.DeserializeObject(result_currentPoint).ToString();
                        var json_curentpoint_values = JsonConvert.DeserializeObject<CurrentPointModel>(json_currentpoint);
                        double _currentPoints = json_curentpoint_values.CurrentPoint;
                        double _new_currentpoints = _currentPoints + Convert.ToDouble(txtAdjustValue.Text);
                        //#1.  ICRM : Point Redemption POST Call 
                        ICRM_LoyaltyPointsRedemptionTransaction(_lpid, _Generated_RefNo, _Generated_RefNo, cmbBranches.SelectedItem.Text, txtCID.Text.ToString().Trim(), 0, Convert.ToDouble(txtAdjustValue.Text), 0, _new_currentpoints, Convert.ToDecimal(_LpRate), _TransDate, _DateofExpiry, _CashierID, _TransStatus);
                        //#2   Insert Adjustment row (by Query)  


                        #region Point Redemption Transaction Log in  ICompaignAdjustment  Table 

                        string QueryB = "Insert into {0}.ICompaignAdjustment(ReferenceNo,CID,Rate,PreviousCashbackValue,CashBackAdjAmount,CashBackBal," +
                                       " PreviousPoint,AdjustPoints,TotalPoints,CompaignType,Branch,Notes,CreatedBy,CreatedDate)" +
                                       " values(@ReferenceNo,@CID,@Rate,@PreviousCashbackValue,@CashBackAdjAmount,@CashBackBal,@PreviousPoint," +
                                       " @AdjustPoints,@TotalPoints,@CompaignType,@Branch,@Notes,@CreatedBy,@CreatedDate); ";
                        MySqlParameter[] mySqlParameters =
                        {
                                new MySqlParameter("@ReferenceNo",_Generated_RefNo),
                                new MySqlParameter("@CID", txtCID.Text.ToString().Trim()),
                                new MySqlParameter("@Rate",Convert.ToDecimal(_LpRate)),
                                new MySqlParameter("@PreviousCashbackValue",0),
                                new MySqlParameter("@CashBackAdjAmount",0),
                                new MySqlParameter("@CashBackBal", 0),
                                new MySqlParameter("@PreviousPoint",Convert.ToDouble( txtCurrentValue.Text)),
                                new MySqlParameter("@AdjustPoints",Convert.ToDouble(txtAdjustValue.Text)),
                                new MySqlParameter("@TotalPoints",_new_currentpoints),
                                new MySqlParameter("@CompaignType","Points"),
                                new MySqlParameter("@Branch", cmbBranches.SelectedItem.Text),
                                new MySqlParameter("@Notes",txtNotes.Text),
                                new MySqlParameter("@CreatedBy",txtCreatedBy.Text.ToString().Trim()),
                                new MySqlParameter("@CreatedDate", _TransDate),
                            };

                        string command = string.Format(QueryB, Session["Branch_HQ"].ToString());
                        K = ObjMain.ExecuteQuery(command, mySqlParameters);
                        
                        #region Update the Current Point after the PointAdjustment ..
                        // Existing one without- PointExpiryOn hided on 04-09-25 
                        // UpdateCurrentPointValueByCID(txtCID.Text.ToString().Trim(), _new_currentpoints, Session["Branch_HQ"].ToString());  
                        UpdateCurrentPointWithPointExpiryByCID(txtCID.Text.ToString().Trim(), _new_currentpoints, Session["Branch_HQ"].ToString(), _pointexpirydate);
                        #endregion
                        if (K > 0)
                        {
                            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Points Adjustment added Successfully');location.href='CampaignAdjustment.aspx'", true);
                        }
                        else
                        {
                            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('Something went wrong ');location.href='CampaignAdjustment.aspx'", true);
                        }
                        #endregion
                        
                    }
                    #endregion


                }

            }
            else
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('Suntoyo ICRM Not Enabled In PMS');", true);
            }

        }

        public void UpdateCurrentPointValueByCID(string cid, double currentPoint, string hq)
        {
            ICurrentPoints cp = new ICurrentPoints();
            cp.cid = cid;
            cp.currentPoints = currentPoint;
            cp.dbName = hq;
            var FinalJson = cp;
            var json2PutCall = JsonConvert.SerializeObject(FinalJson, Formatting.Indented);
            string sBearerToken = objAPI.GetBarerToken();
            string Jsonresult = objAPI.UpdateCurrentPointValue(sBearerToken, json2PutCall);
           
        }
        public void UpdateCurrentPointWithPointExpiryByCID(string cid, double currentPoint, string hq, DateTime _pointexpiry )
        {
            ICurrentPoints cp = new ICurrentPoints();
            cp.cid = cid;
            cp.currentPoints = currentPoint;
            cp.PointExpiryOn = _pointexpiry;
            cp.dbName = hq;
            var FinalJson = cp;
            var json2PutCall = JsonConvert.SerializeObject(FinalJson, Formatting.Indented);
            string sBearerToken = objAPI.GetBarerToken();
            string Jsonresult = objAPI.UpdateCurrentPointValueWithPointExpiryMonths(sBearerToken, json2PutCall);

        }

        public void iCRM_SendCashBackTransaction(string _cbid, string _cid, string _mobileno, string _transid, int _transType, decimal _amount, decimal _cashbackrate, string _businessdate, int _transstatus, string _branchid, string _notes)
        {
            CashBackTransModel cashBackTrans = new CashBackTransModel();
            cashBackTrans.CBID = _cbid;
            cashBackTrans.CID = _cid;
            cashBackTrans.Mobile = _mobileno;
            cashBackTrans.TransID = _transid;
            cashBackTrans.TransType = _transType;
            cashBackTrans.Amount = Convert.ToDouble(_amount);
            cashBackTrans.CashBackRate = Convert.ToDouble(_cashbackrate);
            cashBackTrans.BusinessDate = Convert.ToDateTime(_businessdate);
            cashBackTrans.TransStatus = _transstatus;
            cashBackTrans.BranchID = Convert.ToInt32(_branchid);
            cashBackTrans.Notes = _notes;

            string BearerToken = objAPI.GetBarerToken();

            var FinalResult = cashBackTrans;
            string json2PostData_crm_cashback = JsonConvert.SerializeObject(FinalResult, Formatting.Indented);
            if (json2PostData_crm_cashback != "")
            {

                string _db = Session["Branch_HQ"].ToString();
                objAPI.iCRM_CashbackTransactionCreate(_db, BearerToken, json2PostData_crm_cashback);

            }

        }

        public void ICRM_LoyaltyPointsRedemptionTransaction(string _lpid, string _TransID, string _TransNo, string _BranchName, string _CID, decimal _Amount, double _Points, double _RDPoints, double _CurrentPoint, decimal _LPRate, DateTime _TransDate, DateTime _DateofExpiry, string _CashierID, int _TransStatus)
        {
            LoyaltyPointsDetailsTransactionModel loyaltyPoints = new LoyaltyPointsDetailsTransactionModel();
            loyaltyPoints.LpID = _lpid;
            loyaltyPoints.TransID = _TransID;
            loyaltyPoints.TransNo = _TransNo;
            loyaltyPoints.BranchName = _BranchName;
            loyaltyPoints.CID = _CID;
            loyaltyPoints.Amount = _Amount;
            loyaltyPoints.Points = _Points;
            loyaltyPoints.RDPoints = _RDPoints;
            loyaltyPoints.CurrentPoint = _CurrentPoint;
            loyaltyPoints.LPRate = _LPRate;
            loyaltyPoints.TransDate = _TransDate;
            loyaltyPoints.DateofExpiry = _DateofExpiry;
            loyaltyPoints.CashierID = _CashierID;
            loyaltyPoints.TransStatus = _TransStatus;
            var FinalResult = loyaltyPoints;
            string Joson2PostData_points_redemption = JsonConvert.SerializeObject(FinalResult, Formatting.Indented);
            string BearerToken = objAPI.GetBarerToken();
            if (Joson2PostData_points_redemption != "")
            {
                string _db = Session["Branch_HQ"].ToString();
                objAPI.iCRM_ILoyaltyPointsDetail_Create(_db, BearerToken, Joson2PostData_points_redemption);
            }


        }

        protected void btnClear_Click(object sender, EventArgs e)
        {
            ClearForms();

        }

        public void ClearForms()
        {
            RtxtUserName.Text = "";
            txtUserName.Text = "";
            txtCustomerName.Text = "";
            txtCID.Text = "";
            txtActiveCompaignType.Text = "";
            txtRate.Text = "";
            txtCurrentValue.Text = "";
            txtAdjustValue.Text = "";
            txtCreatedBy.Text = "";
        }
        private string Get_Generic_Webordingini(string DB, string IniID)
        {
            if (cmbBranches.Visible == true)
            {
                #region  Validation Between HQ Branch and Normal Branch 
                BranchFullName = cmbBranches.SelectedItem.Text;      // This will Return Branch FullName 
                if (BranchFullName == "HQ")
                {
                    BranchAlias = Session["Branch_HQ"].ToString();
                }
                else
                {
                    BranchFullName = cmbBranches.SelectedItem.Text;     // This will Return Branch FullName 
                    Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);  // This will Return BranchName( Actual Database Name )
                    BranchAlias = Cmb_BranchName;

                }
                #endregion
            }
            else
            {
                BranchAlias = Session["Branch_HQ"].ToString();
            }




            BL_API objAPI = new BL_API();
            string returnvalue = string.Empty;
            string sBearerToken = objAPI.GetBarerToken();

            string JSONRetValue = objAPI.API_GET_INIWebOrderingIniValue(sBearerToken, DB, IniID);
            var sObject = "[" + JsonConvert.DeserializeObject(JSONRetValue).ToString().Trim() + "]";
            DataTable dtResult = (DataTable)JsonConvert.DeserializeObject(sObject, (typeof(DataTable)));
            if (dtResult.Rows.Count == 0)
            {
                returnvalue = "";
            }
            else
            {
                returnvalue = (dtResult.Rows[0]["ini_value"]).ToString();
            }
            return returnvalue;
        }



        [WebMethod]
        public static string IsCashbackEnable(string DB)
        {
            try
            {
                BL_SELECT objSel = new BL_SELECT();
                DataTable DT = new DataTable();
                BL_API ObjApi = new BL_API();

                string IniID = "46"; //  ICRM:Cashback 
                string BarereTokenVal = ObjApi.GetBarerToken();
                string JSONRetVal = ObjApi.API_GET_INIWebOrderingIniValue(BarereTokenVal, DB, IniID);
                var sObject = JsonConvert.DeserializeObject(JSONRetVal);
                return sObject.ToString();
                //string BarerTokenVal = 
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }



        [WebMethod]
        public static string IsPointredemptionEnable(string DB)
        {
            try
            {
                BL_SELECT objSel = new BL_SELECT();
                DataTable DT = new DataTable();
                BL_API ObjApi = new BL_API();

                string IniID = "47"; //  ICRM: PointRedemption
                string BarereTokenVal = ObjApi.GetBarerToken();
                string JSONRetVal = ObjApi.API_GET_INIWebOrderingIniValue(BarereTokenVal, DB, IniID);
                var sObject = JsonConvert.DeserializeObject(JSONRetVal);
                return sObject.ToString();

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        protected void grdCompaignAdjustList_RowDataBound(object sender, GridViewRowEventArgs e)
        {

        }

        public DataTable Get_CampaignGrid()
        {

            if (cmbBranches.Visible == false)
            {

                BranchAlias = Session["Branch_HQ"].ToString();

            }
            else
            {
                BranchFullName = cmbBranches.SelectedItem.Text;     // This will Return Branch FullName 
                Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);  // This will Return BranchName( Actual Database Name )
                BranchAlias = Session["Branch_HQ"].ToString();
            }



            DataTable dt = new DataTable();
            string Compaingnlist_Query = "select * from {0}.ICompaignAdjustment as CA INNER JOIN   {0}.ICustomers as C  on   CA.cid=C.cid ;";
            string command = string.Format(Compaingnlist_Query, Session["Branch_HQ"].ToString());
            dt = ObjMain.GetData_DT(command);



            #region UserName Decrption 
            if (Cmb_BranchName != "")
            {
                AES_Key = ObjApi.Get_AESKey(Cmb_BranchName);

            }
            #endregion

            if (dt.Rows.Count > 0)
            {
                foreach (DataRow row in dt.Rows)
                {
                    string value = row.Field<string>("UserName");
                    row.SetField("UserName", ObjSel.DecryptString(value, AES_Key));
                    string value1 = row.Field<string>("CustomerName");
                    row.SetField("CustomerName", ObjSel.DecryptString(value1, AES_Key));
                }


            }

            return dt;
        }
        public void Load_Campaingn()
        {
            grdCompaignAdjustList.DataSource = Get_CampaignGrid();
            grdCompaignAdjustList.DataBind();
        }

        protected void grdMember1_SelectedIndexChanged(object sender, EventArgs e)
        {

            // XSS Attack Prevention 
            if (cmbBranches.Visible == false)
            {
                BranchAlias = Session["Branch_HQ"].ToString();
            }
            else
            {
                if (cmbBranches.SelectedItem.Text == "HQ")
                {
                    // btnExcel.Enabled = true;
                    // HQ Validation    02-12-21
                    BranchFullName = cmbBranches.SelectedItem.Text;        // This will Return Branch FullName 
                    Cmb_BranchName = ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), BranchFullName);
                    UPDATEBRANCH(Cmb_BranchName);
                    BranchAlias = Session["Branch_HQ"].ToString();
                }
                else
                {
                    BranchFullName = cmbBranches.SelectedItem.Text;      // This will Return Branch FullName 
                    Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);  // This will Return BranchName( Actual Database Name )
                    BranchAlias = Cmb_BranchName;
                }
            }

            #region UserName Decrption 
            if (Cmb_BranchName != "")
            {
                AES_Key = ObjApi.Get_AESKey(Cmb_BranchName);

            }
            #endregion


            string Is_CashBack = Get_Generic_Webordingini(BranchAlias, "46");
            string Is_PointRedemption = Get_Generic_Webordingini(BranchAlias, "47");

            if (Is_CashBack == "1")
            {
                // show the cashback rate 
                ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "LoadcompaignTypeText('" + Session["BranchDB"].ToString() + "');", true);

            }

            if (Is_PointRedemption == "1")
            {
                // show the loyalty point rate 
                ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "LoadcompaignTypeText2('" + Session["BranchDB"].ToString() + "');", true);

            }

            RCustomerID = (grdMember1.SelectedRow.FindControl("lblCustomerID1") as Label).Text;
            DTMemberDL = ObjSel.ReadMemberInformations(Session["Branch_HQ"].ToString(), RCustomerID);
            txtRMobileNo.Text = DTMemberDL.Rows[0]["Mobile"].ToString();
            txtRcid.Text = DTMemberDL.Rows[0]["CID"].ToString();
            string r_customername = DTMemberDL.Rows[0]["CustomerName"].ToString();
            txtRCustomerName.Text = ObjSel.DecryptString(r_customername, AES_Key);
            string r_username = DTMemberDL.Rows[0]["UserName"].ToString();
            RtxtUserName.Text = ObjSel.DecryptString(r_username, AES_Key);
        }
        protected void btnSearch1_Click(object sender, EventArgs e)
        {
            BranchAlias = Session["Branch_HQ"].ToString();
            Load_SearchData1(BranchAlias, txtUserName1.Text.ToString().Trim());
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ShowModalMemberInformationList1();", true);


        }

        protected void btnSearchCampaignAdjust_Click(object sender, EventArgs e)
        {
            //#1. using Mobileno 
            // 1. By MobileNo
            // 2. By MobileNo with campaignType
            // 3. By MobileNo with Branch 
            //#2. StartDt and EndDt  
            // 1. StartDt and EndDt - All Data 
            // 2. StartDt and EndDt - with MobileNo
            // 3. StartDt and EndDt - With CampaignType 

            if (cmbBranches.Visible == false)
            {

                BranchAlias = Session["Branch_HQ"].ToString();

            }
            else
            {
                BranchFullName = cmbBranches.SelectedItem.Text;     // This will Return Branch FullName 
                Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);  // This will Return BranchName( Actual Database Name )
                BranchAlias = Session["Branch_HQ"].ToString();
            }



            #region UserName Decrption 
            if (Cmb_BranchName != "")
            {
                AES_Key = ObjApi.Get_AESKey(Cmb_BranchName);

            }
            #endregion

            if (RtxtUserName.Text != "" && txtStartDt.Text == "" && txtEndDt.Text == "" && cmbCampaignType.SelectedItem.Text == "Select CampaignType")
            {

                DataTable DT = new DataTable();
                string Query1 = "select * from {0}.ICompaignAdjustment as CA INNER JOIN   {0}.ICustomers as C  on   CA.cid=C.cid   where C.UserName=@UserName ;";
                string command = string.Format(Query1, Session["Branch_HQ"].ToString());
                MySqlParameter[] parameters =
                 {
                     new MySqlParameter("@UserName",RtxtUserName.Text.ToString().Trim()),
                 };
                DT = ObjMain.NewGetData_DT(command, parameters);



                if (DT.Rows.Count > 0)
                {
                    foreach (DataRow row in DT.Rows)
                    {
                        string value = row.Field<string>("UserName");
                        row.SetField("UserName", ObjSel.DecryptString(value, AES_Key));
                        string value1 = row.Field<string>("CustomerName");
                        row.SetField("CustomerName", ObjSel.DecryptString(value1, AES_Key));
                    }


                }



                grdCompaignAdjustList.DataSource = DT;
                grdCompaignAdjustList.DataBind();

            }
            else if (txtStartDt.Text != " " && txtEndDt.Text != " " && RtxtUserName.Text == "" && cmbCampaignType.SelectedItem.Text == "Select CampaignType")
            {
                DataTable DT = new DataTable();
                string Query2 = "select * from {0}.ICompaignAdjustment as CA INNER JOIN   {0}.ICustomers as C  on   CA.cid=C.cid   where date(CA.CreatedDate) between  @StartDt AND @EndDt;";
                string command2 = string.Format(Query2, Session["Branch_HQ"].ToString());
                MySqlParameter[] parameters =
                 {

                  new MySqlParameter("@StartDt",txtStartDt.Text),
                  new MySqlParameter("@EndDt",txtEndDt.Text),
                 };
                DT = ObjMain.NewGetData_DT(command2, parameters);


                if (DT.Rows.Count > 0)
                {
                    foreach (DataRow row in DT.Rows)
                    {
                        string value = row.Field<string>("UserName");
                        row.SetField("UserName", ObjSel.DecryptString(value, AES_Key));
                        string value1 = row.Field<string>("CustomerName");
                        row.SetField("CustomerName", ObjSel.DecryptString(value1, AES_Key));
                    }


                }



                grdCompaignAdjustList.DataSource = DT;
                grdCompaignAdjustList.DataBind();
            }
            else if (RtxtUserName.Text != "" && txtStartDt.Text != "" && txtEndDt.Text != "" && cmbCampaignType.SelectedItem.Text == "Select CampaignType")
            {
                DataTable DT = new DataTable();
                string Query3 = "select * from {0}.ICompaignAdjustment as CA INNER JOIN   {0}.ICustomers as C  on   CA.cid=C.cid   where C.UserName=@UserName AND   date(CA.CreatedDate) between  @StartDt AND @EndDt;";
                string command3 = string.Format(Query3, Session["Branch_HQ"].ToString());
                MySqlParameter[] parameters =
                 {
                  new MySqlParameter("@UserName",RtxtUserName.Text),
                  new MySqlParameter("@StartDt",txtStartDt.Text),
                  new MySqlParameter("@EndDt",txtEndDt.Text),
                 };
                DT = ObjMain.NewGetData_DT(command3, parameters);

                if (DT.Rows.Count > 0)
                {
                    foreach (DataRow row in DT.Rows)
                    {
                        string value = row.Field<string>("UserName");
                        row.SetField("UserName", ObjSel.DecryptString(value, AES_Key));
                        string value1 = row.Field<string>("CustomerName");
                        row.SetField("CustomerName", ObjSel.DecryptString(value1, AES_Key));
                    }


                }

                grdCompaignAdjustList.DataSource = DT;
                grdCompaignAdjustList.DataBind();

            }
            else if (cmbCampaignType.SelectedIndex != 0 && txtStartDt.Text == "" && txtEndDt.Text == "" && RtxtUserName.Text == "")
            {
                // NO other selection : cmbCampaignType alone 
                DataTable DT = new DataTable();
                string Query4 = "select * from {0}.ICompaignAdjustment as CA INNER JOIN   {0}.ICustomers as C  on   CA.cid=C.cid   where CA.CompaignType=@CompaignType;";
                string command4 = string.Format(Query4, Session["Branch_HQ"].ToString());
                MySqlParameter[] parameters =
                 {
                  new MySqlParameter("@CompaignType",cmbCampaignType.SelectedItem.Text),
                 };
                DT = ObjMain.NewGetData_DT(command4, parameters);

                if (DT.Rows.Count > 0)
                {
                    foreach (DataRow row in DT.Rows)
                    {
                        string value = row.Field<string>("UserName");
                        row.SetField("UserName", ObjSel.DecryptString(value, AES_Key));
                        string value1 = row.Field<string>("CustomerName");
                        row.SetField("CustomerName", ObjSel.DecryptString(value1, AES_Key));
                    }


                }
                grdCompaignAdjustList.DataSource = DT;
                grdCompaignAdjustList.DataBind();


            }
            else if (cmbCampaignType.SelectedIndex != 0 && txtStartDt.Text != "" && txtEndDt.Text != "" && RtxtUserName.Text == "")
            {
                // Date selection along with  cmbCampaignType

                DataTable DT = new DataTable();
                string Query4 = "select * from {0}.ICompaignAdjustment as CA INNER JOIN   {0}.ICustomers as C  on   CA.cid=C.cid   where  date(CA.CreatedDate) between  @StartDt AND @EndDt AND  CA.CompaignType=@CompaignType;";
                string command4 = string.Format(Query4, Session["Branch_HQ"].ToString());
                MySqlParameter[] parameters =
                 {
                  new MySqlParameter("@StartDt",txtStartDt.Text),
                  new MySqlParameter("@EndDt",txtEndDt.Text),
                  new MySqlParameter("@CompaignType",cmbCampaignType.SelectedItem.Text),
                 };
                DT = ObjMain.NewGetData_DT(command4, parameters);

                if (DT.Rows.Count > 0)
                {
                    foreach (DataRow row in DT.Rows)
                    {
                        string value = row.Field<string>("UserName");
                        row.SetField("UserName", ObjSel.DecryptString(value, AES_Key));
                        string value1 = row.Field<string>("CustomerName");
                        row.SetField("CustomerName", ObjSel.DecryptString(value1, AES_Key));
                    }


                }
                grdCompaignAdjustList.DataSource = DT;
                grdCompaignAdjustList.DataBind();


            }
            else if (cmbCampaignType.SelectedIndex != 0 && txtStartDt.Text == "" && txtEndDt.Text == "" && RtxtUserName.Text != "")
            {
                //  Date selection and mobileno  along with  cmbCampaignType
                DataTable DT = new DataTable();
                string Query4 = "select * from {0}.ICompaignAdjustment as CA INNER JOIN   {0}.ICustomers as C  on   CA.cid=C.cid   where C.UserName=@UserName   AND  CA.CompaignType=@CompaignType;";
                string command4 = string.Format(Query4, Session["Branch_HQ"].ToString());
                MySqlParameter[] parameters =
                 {
                  new MySqlParameter("@UserName",RtxtUserName.Text),
                  new MySqlParameter("@CompaignType",cmbCampaignType.SelectedItem.Text),
                 };
                DT = ObjMain.NewGetData_DT(command4, parameters);

                if (DT.Rows.Count > 0)
                {
                    foreach (DataRow row in DT.Rows)
                    {
                        string value = row.Field<string>("UserName");
                        row.SetField("UserName", ObjSel.DecryptString(value, AES_Key));
                        string value1 = row.Field<string>("CustomerName");
                        row.SetField("CustomerName", ObjSel.DecryptString(value1, AES_Key));
                    }


                }
                grdCompaignAdjustList.DataSource = DT;
                grdCompaignAdjustList.DataBind();

            }

            else if (cmbCampaignType.SelectedIndex != 0 && txtStartDt.Text != "" && txtEndDt.Text != "" && RtxtUserName.Text != "")
            {
                //  Date selection and mobileno  along with  cmbCampaignType
                DataTable DT = new DataTable();
                string Query4 = "select * from {0}.ICompaignAdjustment as CA INNER JOIN   {0}.ICustomers as C  on   CA.cid=C.cid   where C.UserName=@UserName  AND  date(CA.CreatedDate) between  @StartDt AND @EndDt AND  CA.CompaignType=@CompaignType;";
                string command4 = string.Format(Query4, Session["Branch_HQ"].ToString());
                MySqlParameter[] parameters =
                 {
                  new MySqlParameter("@UserName",RtxtUserName.Text),
                  new MySqlParameter("@StartDt",txtStartDt.Text),
                  new MySqlParameter("@EndDt",txtEndDt.Text),
                  new MySqlParameter("@CompaignType",cmbCampaignType.SelectedItem.Text),
                 };
                DT = ObjMain.NewGetData_DT(command4, parameters);

                if (DT.Rows.Count > 0)
                {
                    foreach (DataRow row in DT.Rows)
                    {
                        string value = row.Field<string>("UserName");
                        row.SetField("UserName", ObjSel.DecryptString(value, AES_Key));
                        string value1 = row.Field<string>("CustomerName");
                        row.SetField("CustomerName", ObjSel.DecryptString(value1, AES_Key));
                    }


                }
                grdCompaignAdjustList.DataSource = DT;
                grdCompaignAdjustList.DataBind();

            }


        }

        protected void btnClear1_Click(object sender, EventArgs e)
        {
            txtRcid.Text = "";
            txtRCustomerName.Text = "";
            txtRMobileNo.Text = "";
            txtStartDt.Text = "";
            txtEndDt.Text = "";
            cmbCampaignType.SelectedIndex = 0;
            RtxtUserName.Text = "";
        }

        protected void btnAddNew_Click(object sender, EventArgs e)
        {
            Response.Redirect(HttpContext.Current.Request.Url.ToString(), true);

        }

        protected void btnAddnew1_Click(object sender, EventArgs e)
        {
            Response.Redirect(HttpContext.Current.Request.Url.ToString(), true);
        }
    }
}