using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections;
using System.Web;
using System.IO;
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 iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
using System.Web.UI.DataVisualization.Charting;
using System.Drawing.Printing;
using System.Drawing;
using System.Drawing.Text;

using Newtonsoft.Json;
using RestSharp;

namespace SUNWEB
{
    public partial class MenuGroupCreation : 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_MenuGroupCreation = 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 BranchAlias = string.Empty;

        string Vw_Chk = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {

            PID = "53";    // This is for Menugroup 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)
                {
                    LoadBranchName4SuperAdmin();

                    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_MenuGroupCreation"].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 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 ActiveCall()
        {
            string QueryCal = "select ActiveValue from portaldb.usermaster  where Userid=" + Session["UserId"].ToString() + " ";
            ActiveCallvalue = ObjMain.ExecuteScalar(QueryCal);
            if (ActiveCallvalue == "")
            {
                ActiveCallvalue = ObjSel.GetFirstBranch8(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), Session["CM_ID"].ToString());
            }


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

            if (ISHQ != "")
            {
                ActiveCallvalue = ObjSel.GetFirstBranch8(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), Session["CM_ID"].ToString());
                UPDATEBRANCH(ActiveCallvalue);
            }

            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 )
            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_MenuGroupCreation = DtLicense.Rows[0]["MENUGROUPCREATION"].ToString();
                Session["L_MenuGroupCreation"] = L_MenuGroupCreation;
            }
            if (Session["L_MenuGroupCreation"].ToString() == "N" || Session["Page_Acess"].ToString() == "N")
            {
                Response.Redirect("DeniedPage.aspx");
            }
            else
            {

                //btnExcel.Enabled = true;
                //lblMsgTotalSelection.Text = "Total Sale Selection Between" + "&nbsp;&nbsp;&nbsp;" + txtStartDt.Text + "&nbsp;&nbsp;&nbsp;  And &nbsp;&nbsp;&nbsp;" + txtEndDt.Text;
                cd_BranchAlias = cmbBranches.SelectedItem.Text;
                // BindGridview(ActiveCallvalue, txtStartDt.Text, txtEndDt.Text);
                System.Threading.Thread.Sleep(2000);

                btnUpdateMenugroup.Visible = false;
                LoadMenuGroup(Cmb_BranchName);
                LoadMenuGroupData(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)
        {

            if (cmbBranches.SelectedIndex == 0)
            {
                Response.Write("LayoutSetting.aspx");
            }
            else
            {
                DT = ObjUserBL.GetPageRightsDetailsPIDNew(Session["UserId"].ToString(), PID, Microsoft.Security.Application.Encoder.HtmlEncode(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 = Microsoft.Security.Application.Encoder.HtmlEncode(cmbBranches.SelectedItem.Text);    // This will Return Branch FullName 
                    Cmb_BranchName = ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), BranchFullName);
                    UPDATEBRANCH(Cmb_BranchName);

                }
                else
                {
                    BranchFullName = Microsoft.Security.Application.Encoder.HtmlEncode(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);

                }


                if (DtLicense.Rows.Count > 0)
                {


                    L_MenuGroupCreation = DtLicense.Rows[0]["MENUGROUPCREATION"].ToString();
                    Session["L_MenuGroupCreation"] = L_MenuGroupCreation;
                }




                if (Session["L_MenuGroupCreation"].ToString() == "N" || Session["Page_Acess"].ToString() == "N")
                {
                    Response.Redirect("DeniedPage.aspx");
                }

                else
                {
                    // Assign s3 realted Parameter values 
                    // clientname.Value = Session["CM_ID"].ToString();

                    LoadMenuGroup(Cmb_BranchName);
                    btnUpdateMenugroup.Visible = false;
                    LoadMenuGroupData(Cmb_BranchName);


                }
            }
            UPDATEBRANCH(Cmb_BranchName);






        }

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

        protected void btnSaveMenugroup_Click(object sender, EventArgs e)
        {
            BranchFullName = Microsoft.Security.Application.Encoder.HtmlEncode(cmbBranches.SelectedItem.Text);    // This will Return Branch FullName 
            Cmb_BranchName = ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), BranchFullName);
            string Insert_Menugroup_Query = "Insert into {0}.menugroup(MenuGroupName,IsActive,SeqNo) values(@MenuGroupName,@IsActive,@SeqNo);";
            string command = string.Format(Insert_Menugroup_Query, Cmb_BranchName);
            string _is_Active = string.Empty;
            if (chkIsActive.Checked == true)
            {
                _is_Active = "1";
            }
            else if (chkIsActive.Checked == false)
            {
                _is_Active = "0";
            }

            // Get the MaxNo from the Menugroup Table 
            string SeqNO = ObjSel.GetMax_SeqNo_MenuGroup(Cmb_BranchName);


            MySqlParameter[] parameters =
                {
                  new MySqlParameter("@MenuGroupName",txtMenuGroupname.Text.Trim().ToString()),
                  new MySqlParameter("@IsActive",_is_Active),
                  new MySqlParameter("@SeqNo",SeqNO),

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

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




        }

        protected void btnUpdateMenugroup_Click(object sender, EventArgs e)
        {
            BranchFullName = Microsoft.Security.Application.Encoder.HtmlEncode(cmbBranches.SelectedItem.Text);    // This will Return Branch FullName 
            Cmb_BranchName = ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), BranchFullName);
            string Update_Menugroup_Query = " Update {0}.menugroup set MenuGroupName=@MenuGroupName,IsActive=@IsActive, SeqNo=@SeqNo where MenuGroupid=@MenuGroupid ;";
            string command_update = string.Format(Update_Menugroup_Query, Cmb_BranchName);
            string _is_Active = string.Empty;
            if (chkIsActive.Checked == true)
            {
              _is_Active = "1";
            }
            else if (chkIsActive.Checked == false)
            {
              _is_Active = "0";
            }
            MySqlParameter[] parameterss =
                {
                  new MySqlParameter("@MenuGroupName",txtMenuGroupname.Text.Trim().ToString()),
                  new MySqlParameter("@IsActive",_is_Active),
                  new MySqlParameter("@SeqNo",Int32.Parse(hidSeqNo.Value)),
                  new MySqlParameter("@MenuGroupid",Int32.Parse(hidmid.Value)),
                };
            K = ObjMain.ExecuteQuery(command_update, parameterss);


            // Update the MenuTable with MenuGroupid

            #region  Update Menugroupid if we make it inactive -status Anyno to '0'

            if (_is_Active == "0")
            {
                string chkMenugroupid_List = " select * from {0}.Menu  as m where  m.Visibility='Enable' and m.Menugroupid="+ Int32.Parse(hidmid.Value) + " ; ";
                string command = string.Format(chkMenugroupid_List, Cmb_BranchName);

                DT = ObjMain.GetData_DT(command);

                if (DT.Rows.Count > 0)
                   {
                    // Loop the datatable 
                    for (int i = 0; i < DT.Rows.Count; i++)
                    {
                      string  _Rcategoryid = DT.Rows[i]["Categoryid"].ToString();

                        //Update Menu table By Categoryid 
                        string Update_Menu = "Update {0}.Menu  set MenuGroupid=@MenuGroupid where Categoryid=@Categoryid; ";
                        string command_update_Menu = string.Format(Update_Menu, Cmb_BranchName);
                        MySqlParameter[] parameter =
                        {
                          new MySqlParameter("@MenuGroupid",0),
                          new MySqlParameter("@Categoryid",_Rcategoryid),
                          

                        };

                        L = ObjMain.ExecuteQuery(command_update_Menu, parameter);


                    }


                }


            }

            #endregion

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





        }




        public void LoadMenuGroup(string db)
        {
            string Read_Cashback = "SELECT * FROM {0}.menugroup;";
            string command = string.Format(Read_Cashback, db);
            DT = ObjMain.GetData_DT(command);
            grdMenuGroupName.DataSource = DT;
            grdMenuGroupName.DataBind();
        }
        protected void btnmenugroupnameSearch_Click(object sender, EventArgs e)
        {


            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "Show_Model_menugroup();", true);
            BranchFullName = Microsoft.Security.Application.Encoder.HtmlEncode(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 )
            string Get_Query = "SELECT * FROM {0}.menugroup where MenuGroupName like CONCAT('%', @SearchVal, '%')  ";
            string command = string.Format(Get_Query, Cmb_BranchName);

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


            DT = ObjMain.NewGetData_DT(command, parameters);

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


        }

        protected void grdMenuGroupName_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";
            BranchFullName = Microsoft.Security.Application.Encoder.HtmlEncode(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 )

            string _R_mid = (grdMenuGroupName.SelectedRow.FindControl("lblMenuGroupid") as Label).Text;
            hidmid.Value = Convert.ToString(_R_mid);

            string  _SeqNo=(grdMenuGroupName.SelectedRow.FindControl("txtSeqno") as TextBox).Text;
            hidSeqNo.Value = Convert.ToString(_SeqNo);
            txtRSeqNo.Text = _SeqNo;

            string Get_Query = "SELECT * FROM {0}.menugroup where MenuGroupid=@MenuGroupid;";
            string command = string.Format(Get_Query, Cmb_BranchName);

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


            DT = ObjMain.NewGetData_DT(command, parameters);
            txtMenuGroupname.Text = DT.Rows[0]["MenuGroupName"].ToString();
            string _isActive = DT.Rows[0]["IsActive"].ToString();

            if (_isActive == "0")
            {
                chkIsActive.Checked = false;
            }
            else if (_isActive == "1")
            {
                chkIsActive.Checked = true;
            }

            btnUpdateMenugroup.Visible = true;
            btnSaveMenugroup.Visible = false;
            btnUpdateMenugroup.CssClass = "btn btn-primary";


        }

        protected void grdGroupMenuLink_RowCommand(object sender, GridViewCommandEventArgs e)
        {

            if (e.CommandName == "MenuGroupLink")
            {
                int index = Convert.ToInt32(e.CommandArgument);
                GridViewRow row = grdGroupMenuLink.Rows[index];
                string scategoryid = (row.FindControl("lblCategoryID") as Label).Text;
                DropDownList cmbgroupmenu = (row.FindControl("cmbgroupsMenu") as DropDownList);

                string sMenugroupid = (row.FindControl("lblMenugroupid") as Label).Text;

                #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 sCmd = "Update {0}.Menu set Menugroupid=@Menugroupid where categoryid =@categoryid ;";
                string command = string.Format(sCmd, BranchAlias);
                MySqlParameter[] parameters =
                {
                 
                new MySqlParameter("@Menugroupid",cmbgroupmenu.SelectedIndex),
                new MySqlParameter("@categoryid",scategoryid),
                };
                K = ObjMain.ExecuteQuery(command, parameters);
                if (K > 0)
                {

                    
                 LoadMenuGroupData(BranchAlias);
                 ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' MenuGroup assigned Successfully');", true);
                }
                else
                {
                 ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('Something Went Wrong !'); ", true);
                }
            }

        }

        protected void grdGroupMenuLink_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                BranchFullName = Microsoft.Security.Application.Encoder.HtmlEncode(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 )
                             
                Label lblRCategory = (e.Row.FindControl("lblCategoryID") as Label);
                Label lblMenugroupid = (e.Row.FindControl("lblMenugroupid") as Label);
                DropDownList cmbgroupnames = (e.Row.FindControl("cmbgroupsMenu") as DropDownList);
                
                if (Convert.ToInt32(lblMenugroupid.Text) == 0)
                {

                   
                    string Get_GroupQuery = "select * from {0}.Menugroup where Isactive=1;";
                    DataTable dt = new DataTable();
                    string command = string.Format(Get_GroupQuery, Cmb_BranchName);
                    dt = ObjMain.GetData_DT(command);
                    cmbgroupnames.DataSource = dt;
                    cmbgroupnames.DataTextField = "MenuGroupName";
                    cmbgroupnames.DataValueField = "MenuGroupid";
                    cmbgroupnames.DataBind();
                    cmbgroupnames.Items.Insert(0, new System.Web.UI.WebControls.ListItem("Not Assign To Groups", "0"));

                }
                else
                {
                   
                    string Get_GroupQuery = "select * from {0}.Menugroup where Isactive=1;";
                    DataTable dt = new DataTable();
                    string command = string.Format(Get_GroupQuery, Cmb_BranchName);
                    dt = ObjMain.GetData_DT(command);
                    cmbgroupnames.DataSource = dt;
                    cmbgroupnames.DataTextField = "MenuGroupName";
                    cmbgroupnames.DataValueField = "MenuGroupid";
                  

                    cmbgroupnames.DataBind();
                    string _selected_Val = ObjMain.ExecuteScalar("select MenugroupName from "+ Cmb_BranchName + ".Menugroup where MenugroupID=" + lblMenugroupid.Text + " ;");
                    
                    cmbgroupnames.SelectedIndex = cmbgroupnames.Items.IndexOf(cmbgroupnames.Items.FindByText(_selected_Val));   // If you want to find text by TextField.
                    cmbgroupnames.Items.Insert(0, new System.Web.UI.WebControls.ListItem("Not Assign To Groups", "0"));
                }
                


            }



        }

        public void LoadMenuGroupData(string clientdb)
        {
            string query = "select * from  {0}.Menu  as m where  m.Visibility='Enable';";
            string command = string.Format(query, clientdb);
            DT = ObjMain.GetData_DT(command);
            grdGroupMenuLink.DataSource = DT;
            grdGroupMenuLink.DataBind();

        }

        protected void btnLink_Click(object sender, EventArgs e)
        {

            #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

            foreach (GridViewRow gvrow in grdGroupMenuLink.Rows)
            {
                string scategoryid = (gvrow.FindControl("lblCategoryID") as Label).Text;
                DropDownList cmbgroupmenu = (gvrow.FindControl("cmbgroupsMenu") as DropDownList);


                // Get the Menugroupid,
                string _menugroupid = ObjMain.ExecuteScalar("select Menugroupid from "+ BranchAlias + ".Menugroup where MenugroupName='"+ cmbgroupmenu.SelectedItem.Text.ToString().Trim()+ "'; ");

                string sCmd = "Update {0}.Menu set Menugroupid=@Menugroupid where categoryid =@categoryid ;";
                string command = string.Format(sCmd, BranchAlias);
                MySqlParameter[] parameters =
                {

                new MySqlParameter("@Menugroupid",_menugroupid),
                new MySqlParameter("@categoryid",scategoryid),
                };
                K = ObjMain.ExecuteQuery(command, parameters);

            }
            LoadMenuGroupData(BranchAlias);
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' MenuGroup assigned Successfully');", true);




        }


    }
}