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 CLS_BL;
using CLS_DL;
using CLS_PL;
using DocumentFormat.OpenXml.InkML;

namespace SUNWEB
{
    public partial class CRMMembershipcampaign : System.Web.UI.Page
    {
        BL_SELECT ObjSel = new BL_SELECT();
        BLCompany ObjBL = new BLCompany();
        PLCOMMON ObjPL = new PLCOMMON();
        MYSQLCLOUD ObjCloudMain = new MYSQLCLOUD();
        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();
        // 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_CRMMembershipcampaign = string.Empty;
        string Branchidval = string.Empty;
        string BranchFullName = string.Empty;
        string Curr_BranchFullName = string.Empty;
        string Cmb_BranchName = string.Empty;
        string RBranchid = string.Empty;
        string Branchid = string.Empty;

        string HQ = string.Empty;
        string Cm_id = string.Empty;
        string ISHQ = string.Empty;
        DataSet DS = new DataSet();

        string Vw_Chk = string.Empty;
        // Added On 20-06-2022
        string ReadHQ = string.Empty;
        string BranchAlias = string.Empty;
             
       
        string MobValue;
        string Ins_CustQuery = string.Empty;
        string RCustomerID = string.Empty;
      


        protected void Page_Load(object sender, EventArgs e)
        {
               
            PID = "46";         // This is for CRM membershipcampaign   Page 
            if (!IsPostBack)
            {
                txtStartDt.Text = Curr_DateOnly;
                txtEndDt.Text = Curr_DateOnly;
            }
            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)
                {
                    LoadBranchesOnID();
                }
                cd_BranchAlias = cmbBranches.SelectedItem.Text;
                //LoadInventoryListGrid(cd_BranchAlias, txtStartDt.Text, txtEndDt.Text);
            }
            else if (((Convert.ToBoolean(Session["IsMultiBranch"])) == true) && (Session["PortalTypeId"].ToString() == ""))
            {
                if (!IsPostBack)
                {
                    LoadBranchesOnID();
                    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_CRMMembershipcampaign"].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
                        {
                            btnGetReports.Visible = true;

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

                        }


                    }

                }

            }
            else
            {

            }


        }


        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());
            }

            #region  HQ Validation in ActiveCall Function : Starts 
            cd_BranchAlias = ActiveCallvalue;
            // HQ Validation For Loading Branch Name : Dropdown  Added Karthik  On 02-12-21 

            ReadHQ = ObjUserBL.GetBranchFullNameByBranchName(Session["Branch_HQ"].ToString(), cd_BranchAlias);

            if (ReadHQ == "HQ")
            {
                cmbBranches.Items.FindByText(ReadHQ).Selected = true;
            }
            else
            {
                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 )
                cmbBranches.Items.FindByText(Curr_BranchFullName).Selected = true;
                Branchidval = ObjUserBL.GetBranchIDbyName(ActiveCallvalue, ActiveCallvalue);
            }

            #endregion
            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_CRMMembershipcampaign = DtLicense.Rows[0]["CRMMEMBERSHIPCAMPAIGN"].ToString();
                Session["L_CRMMembershipcampaign"] = L_CRMMembershipcampaign;
            }

            if ((Session["L_CRMMembershipcampaign"] == null) || Session["L_CRMMembershipcampaign"].ToString() == "N" || Session["Page_Acess"].ToString() == "N")
            {
                if (cmbBranches.SelectedItem.Text == "HQ")
                {

                    #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
                {
                    Response.Redirect("DeniedPage.aspx");
                }

                btnCBUpdate.Visible = false;
                btnLPUpdate.Visible = false;
                btnUpdatePointExpiry.Visible = false;

                // Call the Funcations 
                LoadPointExpiryMonths();
                LoadLoaltyPoints();
                LoadCashbackGrid();
                LoadLoyaltyPointsGrid();
                LoadPExpiryMonths();

            }
            else
            {
                btnCBUpdate.Visible = false;
                btnLPUpdate.Visible = false;
                btnUpdatePointExpiry.Visible = false;
                // Call the Funcations 
                LoadPointExpiryMonths();
                LoadLoaltyPoints();
                LoadCashbackGrid();
                LoadLoyaltyPointsGrid();
                LoadPExpiryMonths();
            }

        }

        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 = ObjCloudMain.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 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");

            }

        }


        public void LoadLoaltyPoints()
        {
            DT = ObjSel.ReadLoyaltypoints(Session["Branch_HQ"].ToString());
            cmbLPLink.DataSource = DT;
            cmbLPLink.DataTextField = "LPName";
            cmbLPLink.DataValueField = "lpid";
            cmbLPLink.DataBind();
            cmbLPLink.Items.Insert(0, "None");
        }

        public void LoadPointExpiryMonths()
        {
            DT = ObjSel.ReadPointExpiryMonths(Session["Branch_HQ"].ToString());
            cmbPointInMonths.DataSource = DT;
            cmbPointInMonths.DataTextField = "PeMonths";
            cmbPointInMonths.DataValueField = "PeID";
            cmbPointInMonths.DataBind();
            cmbPointInMonths.Items.Insert(0, "Select Pemonths");
        }



        public void LoadCashbackGrid()
        {
            string Read_Cashback = "SELECT * FROM {0}.imembership;";
            string command = string.Format(Read_Cashback, Session["Branch_HQ"].ToString());
            DT = ObjMain.GetData_DT(command);
            grdCashBack.DataSource = DT;
            grdCashBack.DataBind();
        }
        public void LoadLoyaltyPointsGrid()
        {
            string Read_LoyaltyPoints = "SELECT * FROM {0}.iloyaltypoints;";
            string command = string.Format(Read_LoyaltyPoints, Session["Branch_HQ"].ToString());
            DT = ObjMain.GetData_DT(command);
            grdLP.DataSource = DT;
            grdLP.DataBind();
        }
        public void LoadPExpiryMonths()
        {
            string Read_LoyaltyPointsMonths = "SELECT * FROM {0}.iPointExpiryMonths;";
            string command = string.Format(Read_LoyaltyPointsMonths, Session["Branch_HQ"].ToString());
            DT = ObjMain.GetData_DT(command);
            grdPointExpiryMonths.DataSource = DT;
            grdPointExpiryMonths.DataBind();

        }
        protected void btnGetReports_Click(object sender, EventArgs e)
        {

        }

        protected void cmbBranches_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void btnCBSave_Click(object sender, EventArgs e)
        {
            CashBack_Compaign();
            LoadCashbackGrid();
        }

        protected void btnCBUpdate_Click(object sender, EventArgs e)
        {
            // Pass the Correct mid 
            UPT_CashBack_Compaign(hidmid.Value);
            LoadCashbackGrid();
            

        }

        protected void btnLPSave_Click(object sender, EventArgs e)
        {
            
            INS_LoyaltyPoints();
           // LoadLoyaltyPointsGrid();
        }

        protected void btnLPUpdate_Click(object sender, EventArgs e)
        {
            // Pass the Correct Lpid
            UPT_LoyaltyPoints(hidLPid.Value);
            LoadLoyaltyPointsGrid();
        }
           


        /// <summary>
        /// This function for Save the Cashback compaign
        /// </summary>
        public void CashBack_Compaign()
        {

            #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

            string command_MebershipCompaign = "Insert into {0}.imembership (MID,MembershipName,CashBackRate,LpID,PeID,RegistrationDate,Notes)" +
               " Values " +
               " (@MID,@MembershipName,@CashBackRate,@LpID,@PeID,@RegistrationDate,@Notes); ";

            string Insert_MebershipCompaign = string.Format(command_MebershipCompaign, Session["Branch_HQ"].ToString());

            System.Guid _Guid = System.Guid.NewGuid();


            if (cmbLPLink.SelectedIndex == 0)
            {
                MySqlParameter[] parameters =
                  {
                     new MySqlParameter("@MID", _Guid),
                     new MySqlParameter("@MembershipName", txtMembershipName.Text.ToString().Trim()),
                     new MySqlParameter("@CashBackRate", txtCashbackRate.Text.ToString().Trim()),
                     new MySqlParameter("@LpID","None"),
                     new MySqlParameter("@PeID", cmbPointInMonths.SelectedValue),
                     new MySqlParameter("@RegistrationDate", Curr_Date),
                     new MySqlParameter("@Notes", txtNotes.Text),

                    };
                K = ObjMain.ExecuteQuery(Insert_MebershipCompaign, parameters);

                if (K > 0)
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Membership Compaign added  Successfully ');location.href='CRMMembershipcampaign.aspx' ", true);
                }


            }
            else
            {
                MySqlParameter[] parameters =
                     {
                     new MySqlParameter("@MID", _Guid),
                     new MySqlParameter("@MembershipName", txtMembershipName.Text.ToString().Trim()),
                     new MySqlParameter("@CashBackRate", txtCashbackRate.Text.ToString().Trim()),
                     new MySqlParameter("@LpID", cmbLPLink.SelectedValue),
                     new MySqlParameter("@PeID", cmbPointInMonths.SelectedValue),
                     new MySqlParameter("@RegistrationDate", Curr_Date),
                     new MySqlParameter("@Notes", txtNotes.Text),

                    };
                K = ObjMain.ExecuteQuery(Insert_MebershipCompaign, parameters);
                if (K > 0)
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Membership Compaign added  Successfully  ');location.href='CRMMembershipcampaign.aspx' ", true);
                }

            }

        }

        /// <summary>
        /// This Function for Update the Cashback compaign
        /// </summary>
        public void UPT_CashBack_Compaign(string _mid)
        {

            #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

            string UPT_CB_Query = "Update  {0}.imembership set MembershipName=@MembershipName,LpID=@LpID,PeID=@PeID,CashBackRate=@CashBackRate,Notes=@Notes " +
                   " where MID=@MID;";
            string Command_MembershipCompaign = string.Format(UPT_CB_Query, Session["Branch_HQ"].ToString());
            MySqlParameter[] parameters =
                    {
                     new MySqlParameter("@MID", _mid),
                     new MySqlParameter("@LpID", cmbLPLink.SelectedValue),
                     new MySqlParameter("@PeID", cmbPointInMonths.SelectedItem.Value),
                     new MySqlParameter("@MembershipName", txtMembershipName.Text.ToString().Trim()),
                     new MySqlParameter("@CashBackRate", txtCashbackRate.Text.ToString().Trim()),
                     new MySqlParameter("@Notes", txtNotes.Text), 

                    };

            K = ObjMain.ExecuteQuery(Command_MembershipCompaign, parameters);

            if (K > 0)
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Membership Compaign Updated Successfully ');location.href='CRMMembershipcampaign.aspx' ", true);
            }

        }

        /// <summary>
        ///  This functio for Insert the Loyalty Point Compaign 
        /// </summary>
        public void INS_LoyaltyPoints()
        {

            string Command_Insert_LoyaltyPoints = "Insert into  {0}.iloyaltypoints (LpID,LpName,LPRate,RDRate,GenerateDate,Notes,CheckPoints)" +
                " values(@LpID,@LpName,@LPRate,@RDRate,@GenerateDate,@Notes,@CheckPoints) ";

            System.Guid _Guid = System.Guid.NewGuid();

            string Insert_Loyalty_Compaign = string.Format(Command_Insert_LoyaltyPoints, Session["Branch_HQ"].ToString());

            MySqlParameter[] parameters =
                  {
                     new MySqlParameter("@LpID", _Guid),
                     new MySqlParameter("@LpName", txtLPName.Text.ToString().Trim()),
                     new MySqlParameter("@LPRate", txtLpRate.Text.ToString().Trim()),
                     new MySqlParameter("@RDRate", txtRDRate.Text.ToString().Trim()),
                     new MySqlParameter("@GenerateDate", Curr_Date),
                     new MySqlParameter("@Notes", txtLPNotes.Text),
                     new MySqlParameter("@CheckPoints", txtCheckPoints.Text),
                  };
            K = ObjMain.ExecuteQuery(Insert_Loyalty_Compaign, parameters);
            if (K > 0)
            {
              ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' LoyaltyPoints Compaign added  Successfully  ');location.href='CRMMembershipcampaign.aspx'  ", true);
            }

        }
        public void UPT_LoyaltyPoints(string Lpid)
        {
            string command_Update_LoyaltyPoints = "Update  {0}.iloyaltypoints set LpName=@LpName,LPRate=@LPRate,RDRate=@RDRate,Notes=@Notes,CheckPoints=@CheckPoints where LpID=@LpID  ; ";
            string Update_Loyalty_Compaign = string.Format(command_Update_LoyaltyPoints, Session["Branch_HQ"].ToString());
            MySqlParameter[] parameters =
                 {
                     new MySqlParameter("@LpID",Lpid),
                     new MySqlParameter("@LpName", txtLPName.Text.ToString().Trim()),
                     new MySqlParameter("@LPRate", txtLpRate.Text.ToString().Trim()),
                     new MySqlParameter("@RDRate", txtRDRate.Text.ToString().Trim()),
                     new MySqlParameter("@Notes", txtLPNotes.Text),
                     new MySqlParameter("@CheckPoints", txtCheckPoints.Text),
                };

            K = ObjMain.ExecuteQuery(Update_Loyalty_Compaign, parameters);
            if (K > 0)
            {
             ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' LoyaltyPoints Compaign added  Successfully');location.href='CRMMembershipcampaign.aspx' ", true);
             //ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('Timing Generated  Successfully ');location.href='Iorderlasetting.aspx'", true);
            }

        }

        protected void btnCashBackSearch_Click(object sender, EventArgs e)
        {

            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "Show_Model_CashBack();", true);
                   
            string Get_Query = "SELECT * FROM {0}.imembership where MembershipName like CONCAT('%', @SearchVal, '%')  ";
            string command = string.Format(Get_Query, Session["Branch_HQ"].ToString());

            MySqlParameter[] parameters =
               {
                     new MySqlParameter("@SearchVal",txtsMembershipName.Text),
               };


            DT = ObjMain.NewGetData_DT(command, parameters);

            grdCashBack.DataSource = DT;
            grdCashBack.DataBind();
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "Show_Model_CashBack();", true);

           
        }

        protected void grdCashBack_SelectedIndexChanged(object sender, EventArgs e)
        {
            btnCBSave.Visible = false;
            btnCBSave.Enabled = false;
            btnCBUpdate.CssClass = "btn btn-primary";
            btnCBUpdate.Visible = true;
            btnCBUpdate.Enabled = true;
            btnCBUpdate.CssClass = "btn btn-primary";


            string _R_mid = (grdCashBack.SelectedRow.FindControl("lblMID") as Label).Text;
            hidmid.Value =Convert.ToString(_R_mid);
            string Get_Query = "SELECT * FROM {0}.imembership where mid=@mid;";
            string command = string.Format(Get_Query, Session["Branch_HQ"].ToString());

            MySqlParameter[] parameters =
               {
                     new MySqlParameter("@mid",_R_mid ),
               };


            DT = ObjMain.NewGetData_DT(command, parameters);
            txtMembershipName.Text = DT.Rows[0]["MembershipName"].ToString();
            txtCashbackRate.Text= DT.Rows[0]["CashBackRate"].ToString();
            txtNotes.Text= DT.Rows[0]["Notes"].ToString();
            string _Lp_Id= DT.Rows[0]["Lpid"].ToString();
            string _peId= DT.Rows[0]["PeID"].ToString();
            cmbLPLink.SelectedIndex= cmbLPLink.Items.IndexOf(cmbLPLink.Items.FindByValue(_Lp_Id));
            cmbPointInMonths.SelectedIndex= cmbPointInMonths.Items.IndexOf(cmbPointInMonths.Items.FindByValue(_peId));

        }

        protected void btnLPSearch_Click(object sender, EventArgs e)
        {

            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ShowModalLoyaltyPointsList();", true);
            string Get_LP_Query = " SELECT * FROM {0}.iloyaltypoints where  LPName like CONCAT('%', @SearchVal, '%') ;";
            string command = string.Format(Get_LP_Query, Session["Branch_HQ"].ToString());


            MySqlParameter[] parameters =
                {
                     new MySqlParameter("@SearchVal",txtRLPName.Text),
               };
            DT = ObjMain.NewGetData_DT(command, parameters);
            grdLP.DataSource = DT;
            grdLP.DataBind();
        }

        protected void grdLP_SelectedIndexChanged(object sender, EventArgs e)
        {

            btnLPSave.Visible = false;
            btnLPSave.Enabled = false;
            btnLPUpdate.CssClass = "btn btn-primary";
            btnLPUpdate.Visible = true;
            btnLPUpdate.Enabled = true;
            btnLPUpdate.CssClass = "btn btn-primary";
            string _R_Lpid = (grdLP.SelectedRow.FindControl("lblSLpID") as Label).Text;
            hidLPid.Value = Convert.ToString(_R_Lpid);

            string Get_LP_Query = " SELECT * FROM {0}.iloyaltypoints where LPId=@LPId;";
            string command = string.Format(Get_LP_Query, Session["Branch_HQ"].ToString());


            MySqlParameter[] parameters =
               {
                     new MySqlParameter("@LPId",_R_Lpid ),
               };
            DT = ObjMain.NewGetData_DT(command, parameters);

            txtLPName.Text= DT.Rows[0]["LpName"].ToString();
            txtLpRate.Text= DT.Rows[0]["LPRate"].ToString();
            txtRDRate.Text= DT.Rows[0]["RDRate"].ToString();
            txtLPNotes.Text= DT.Rows[0]["Notes"].ToString();
            txtCheckPoints.Text = DT.Rows[0]["Checkpoints"].ToString();


        }

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

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

        protected void btnSavePointExpiry_Click(object sender, EventArgs e)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ShowModalPointExpiry();", true);
            string Insert_P_Expiry_Query = " INSERT INTO  {0}.iPointExpiryMonths (PeMonths)VALUES(@PeMonths); ";
            string command = string.Format(Insert_P_Expiry_Query, Session["Branch_HQ"].ToString());
            MySqlParameter[] parameters =
               {
                     new MySqlParameter("@PeMonths",txtRPointExpiryMonth.Text),
               };

            K = ObjMain.ExecuteQuery(command, parameters);
            if (K > 0)
            {
              ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('Point-Expiry Months added  Successfully');location.href='CRMMembershipcampaign.aspx' ", true);
            }
            else
            {
              ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('Something Went Wrong.'); ", true);
            }

        }

        protected void grdPointExpiryMonths_SelectedIndexChanged(object sender, EventArgs e)
        {
            btnSavePointExpiry.Visible = false;
            btnSavePointExpiry.Enabled = false;
            btnUpdatePointExpiry.CssClass = "btn btn-primary";
            btnUpdatePointExpiry.Visible = true;
            btnUpdatePointExpiry.Enabled = true;
            btnUpdatePointExpiry.CssClass = "btn btn-primary";

            string _R_peid = (grdPointExpiryMonths.SelectedRow.FindControl("lblPEID") as Label).Text;
            hidpeid.Value = Convert.ToString(_R_peid);
            string Get_Query = "SELECT * FROM {0}.iPointExpiryMonths where peid=@peid;";
            string command = string.Format(Get_Query, Session["Branch_HQ"].ToString());
            MySqlParameter[] parameters =
               {
                     new MySqlParameter("@peid",_R_peid ),
               };
            DT = ObjMain.NewGetData_DT(command, parameters);
            txtRPointExpiryMonth.Text = DT.Rows[0]["PeMonths"].ToString();
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ShowModalPointExpiry();", true);
        }

        protected void btnUpdatePointExpiry_Click(object sender, EventArgs e)
        {
         UPT_PointsExpiryMonths(hidpeid.Value);
        }
        public void UPT_PointsExpiryMonths(string peid)
        {
            string command_Update_LoyaltyPoints = "Update  {0}.iPointExpiryMonths set PeMonths=@PeMonths where PEID=@PEID  ; ";
            string Update_Point_Expiry_Months = string.Format(command_Update_LoyaltyPoints, Session["Branch_HQ"].ToString());
            MySqlParameter[] parameters =
                 {
                     new MySqlParameter("@PEID",peid),
                     new MySqlParameter("@PeMonths",Int32.Parse(txtRPointExpiryMonth.Text)),
                 };

            K = ObjMain.ExecuteQuery(Update_Point_Expiry_Months, parameters);
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ShowModalPointExpiry();", true);
            LoadPointExpiryMonths();


            if (K > 0)
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('Points Expiry Months Updated  Successfully');location.href='CRMMembershipcampaign.aspx' ", true);
            }

        }



    }
}