using CLS_BL;
using CLS_DL;
using CLS_PL;
using iTextSharp.text;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
using MySql.Data;
using MySql.Data.MySqlClient;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Drawing.Text;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.UI;
using System.Web.UI.DataVisualization.Charting;
using System.Web.UI.WebControls;
using static SUNWEB.InteractiveDashboard;

namespace SUNWEB
{
    public partial class CategoryCustomize : System.Web.UI.Page
    {
        BL_SELECT ObjSel = new BL_SELECT();
        BLCompany ObjBL = new BLCompany();
        PLCOMMON ObjPL = new PLCOMMON();
        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;
        Int32 UpdateTiming = 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 BranchAlias = string.Empty;
        string Branchidval = string.Empty;
        string BranchFullName = string.Empty;
        string Curr_BranchFullName = string.Empty;
        string Cmb_BranchName = string.Empty;

        string L_CategoryCustomize = string.Empty;
        string ReadHQ = string.Empty;
        string HQ = string.Empty;
        string Cm_id = string.Empty;
        string ISHQ = string.Empty;
        DataSet DS = new DataSet();
        string RBranchid = string.Empty;
        string Branchid = string.Empty;
        string Vw_Chk = string.Empty;
        string R_BrachAlias = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {

            PID = "32";    // This is for CategoryCustomize 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_CateforyCustomize"].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={0} ";
            string command = string.Format(QueryCal, Session["UserId"].ToString());
            ActiveCallvalue = ObjMain.ExecuteScalar(command);

            if (ActiveCallvalue == "")
            {
                #region  Default Branch Validation:Either HQ or First Branch Based On IsHQ Ini in PMS 
                string _hq_query = "select IsHQ from  portaldb.companymaster where cm_id=" + Session["CM_ID"] + " ;";
                string _Is_HQ_Enabled = Convert.ToString(ObjMain.ExecuteScalar(_hq_query));
                if (_Is_HQ_Enabled == "1")
                {
                    ActiveCallvalue = ObjSel.GetHQ(Session["Branch_HQ"].ToString());

                }
                else if (_Is_HQ_Enabled == "0")
                {
                    ActiveCallvalue = ObjSel.GETBrachAlias8(Session["CM_ID"].ToString(), Session["Branch_HQ"].ToString(), Session["UserId"].ToString());
                }

                #endregion




            }
            #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_CategoryCustomize = DtLicense.Rows[0]["CATEGORYCUSTOMIZE"].ToString();
                Session["L_CategoryCustomize"] = L_CategoryCustomize;
            }
            if ((Session["L_CategoryCustomize"] == null)||Session["L_CategoryCustomize"].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

                        LoadCategoryGrid(BranchAlias);
                        UPDATEBRANCH(BranchAlias);

                }
                    else
                    {
                        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;

                }
                #endregion

                cd_BranchAlias = cmbBranches.SelectedItem.Text;
                // BindGridview(ActiveCallvalue, tx
                // tStartDt.Text, txtEndDt.Text);
                LoadCategoryGrid(BranchAlias);

                UPDATEBRANCH(BranchAlias);
            }

        }


        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 LoadBranchName()
        {
            DtNormalUser = ObjUserBL.GetBranchOnLoginValues(Session["Branch_HQ"].ToString(), Session["UserId"].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 Query = "select cd_branchalias from {0}.companydetails where cm_id={1} and cd_branchid =" + cmbBranches.SelectedValue + ";";
            string command = string.Format(Query, "portaldb", Session["CM_ID"].ToString());
            R_BrachAlias = ObjMain.ExecuteScalar(command);
            

            UPDATEBRANCH(R_BrachAlias);
            ActiveCall();

            //System.Threading.Thread.Sleep(1000);
            //if (cmbBranches.SelectedIndex == 0)
            //{
            //    Response.Redirect("CategoryCustomize.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_7"] = Isdowld_Acess;
            //    }

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

            //    if (ISHQ != "")
            //    {
            //        ActiveCallvalue = ObjSel.GetFirstBranch(Session["Branch_HQ"].ToString());
            //        UPDATEBRANCH(ActiveCallvalue);
            //    }
            //    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_CategoryCustomize = DtLicense.Rows[0]["CATEGORYCUSTOMIZE"].ToString();
            //        Session["L_CategoryCustomize"] = L_CategoryCustomize;
            //    }

            //    if ((Session["L_CategoryCustomize"]== null )|| Session["L_CategoryCustomize"].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

            //            UPDATEBRANCH(BranchAlias);
            //            LoadCategoryGrid(BranchAlias);
            //        }
            //        else
            //        {
            //            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;

            //        }
            //        #endregion


            //        UPDATEBRANCH(Cmb_BranchName);
            //        LoadCategoryGrid(BranchAlias);
            //    }
            //}
            // Update the current Branch Selection in db





        }

        public void LoadCategoryGrid(string Branch_AliasName)
        {

            // Prevention SQL Injection  : 11-10-21 
            // Prevention XSS 
            // Parameterized approaches 


            //string query = " select   M.MenuId,M.ParentMenuId,M.Title,M.Description,M.Url,M.CategoryId,M.SeqNo,M.Visibility ,case  M.visibility when 'Y' then 'Enable'  when 'N' Then 'Disable' end as  CurrentStatus  from " + Branch_AliasName + ".menu as M inner join   " + Branch_AliasName + ".inventorycategories  AS I On M.Categoryid=I.Categoryid  order by visibility desc,seqno asc;";
            string query = " select   M.MenuId,M.ParentMenuId,M.Title,M.Description,M.Url,M.CategoryId,M.SeqNo,M.Visibility , " +
                           " case  M.visibility  " +
                           " when 'Y' then 'Enable' " +
                           " when 'N' Then 'Disable' " +
                           " end as  CurrentStatus,time(FromTime) as FromTime,time(ToTime) as ToTime, " +
                           " Case ActiveTiming " +
                           " When '0' then 'false' " +
                           " When '1' then 'true' " +
                           " end as ActiveTiming " +
                           " from {0}.menu as M inner join " +
                           " {0}.inventorycategories  AS I On M.Categoryid=I.Categoryid  order by visibility desc,seqno asc,M.Description asc; ";

            string command = string.Format(query, Branch_AliasName);
            Dt2 = ObjMain.GetData_DT(command);
            grdCategoryCustom.DataSource = Dt2;
            grdCategoryCustom.DataBind();

        }

        protected void grdCategoryCustom_RowCommand(object sender, GridViewCommandEventArgs e)
        {

            // Prevention SQL Injection  : 11-10-21 
            // Prevention XSS 
            // Parameterized approaches 

            if (e.CommandName == "Enable")
            {
                int index = Convert.ToInt32(e.CommandArgument);
                GridViewRow row = grdCategoryCustom.Rows[index];
                string RCategoryid = (row.FindControl("lblCategoryNo1") as Label).Text;
                string RCategoryname = (row.FindControl("lblCategoryName") as Label).Text;
                string RSeqNo = (row.FindControl("txtSeqno") as TextBox).Text;
                string RVisibility = (row.FindControl("lblVisiblityStatus") as Label).Text;

                // Provide the Update Concept here 
                if (cmbBranches.SelectedIndex != 0)
                {
                    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 )

                    // Update Query 
                    if (RVisibility.ToString().Trim() == "Disable")
                    {
                        string UPTQuery = "UPDATE {0}.menu  SET Visibility='Enable' , SeqNo=@SeqNo  where CategoryId=@CategoryId ";
                        string command = string.Format(UPTQuery, Cmb_BranchName);

                        MySqlParameter[] parameters =
                           {
                             new MySqlParameter("@Visibility","Enable"),
                             new MySqlParameter("@SeqNo",RSeqNo),
                             new MySqlParameter("@CategoryId",RCategoryid),
                            };

                        K = ObjMain.ExecuteQuery(command, parameters);
                        if (K > 0)
                        {
                            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Weborder Category Updated ');location.href='CategoryCustomize.aspx'", true);
                        }
                    }
                    else if (RVisibility.ToString().Trim() == "Enable")
                    {
                        string UPTQuery = "UPDATE {0}.menu  SET  SeqNo=@SeqNo  where CategoryId=@CategoryId ";
                        string command = string.Format(UPTQuery, Cmb_BranchName);

                        MySqlParameter[] parameters =
                          {
                             
                             new MySqlParameter("@SeqNo",RSeqNo),
                             new MySqlParameter("@CategoryId",RCategoryid),
                            };

                        K = ObjMain.ExecuteQuery(command, parameters);
                        if (K > 0)
                        {
                            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Weborder Category Updated ');location.href='CategoryCustomize.aspx'", true);
                        }
                    }
                }
            }

            if (e.CommandName == "Disable")
            {
                int index = Convert.ToInt32(e.CommandArgument);
                GridViewRow row = grdCategoryCustom.Rows[index];
                string RCategoryid = (row.FindControl("lblCategoryNo1") as Label).Text;
                string RCategoryname = (row.FindControl("lblCategoryName") as Label).Text;
                string RSeqNo = (row.FindControl("txtSeqno") as TextBox).Text;
                string RVisibility = (row.FindControl("lblVisiblityStatus") as Label).Text;


                // Provide the Update Concept here 
                if (cmbBranches.SelectedIndex != 0)
                {
                    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 )
                    // Update Query 
                    if (RVisibility.ToString().Trim() == "Enable")
                    {
                        string UPTQuery = "UPDATE {0}.menu  SET Visibility=@Visibility , SeqNo=@SeqNo  where CategoryId=@CategoryId ";
                        string command = string.Format(UPTQuery, Cmb_BranchName);
                        MySqlParameter[] parameters =
                          {
                            
                             new MySqlParameter("@Visibility","Disable"),
                             new MySqlParameter("@SeqNo",RSeqNo),
                             new MySqlParameter("@CategoryId",RCategoryid),
                            };


                        K = ObjMain.ExecuteQuery(command,parameters);
                        if (K > 0)
                        {
                            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Weborder Category Updated ');location.href='CategoryCustomize.aspx'", true);
                        }
                    }
                    else if (RVisibility.ToString().Trim() == "Disable") 
                    {
                        string UPTQuery = "UPDATE {0}.menu  SET  SeqNo=@SeqNo  where CategoryId=@CategoryId ";
                        string command = string.Format(UPTQuery, Cmb_BranchName);

                        MySqlParameter[] parameters =
                          {
                             new MySqlParameter("@SeqNo",RSeqNo),
                             new MySqlParameter("@CategoryId",RCategoryid),
                          };

                        K = ObjMain.ExecuteQuery(command, parameters);
                        if (K > 0)
                        {
                            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Weborder Category Updated ');location.href='CategoryCustomize.aspx'", true);
                        }
                    }
                }
            }

            if (e.CommandName == "Save") //John added on 14-June-2021
            {
                int index = Convert.ToInt32(e.CommandArgument);
                GridViewRow row = grdCategoryCustom.Rows[index];
                string RCategoryid = (row.FindControl("lblCategoryNo1") as Label).Text;
                string txtFromTime = (row.FindControl("txtFromtime") as TextBox).Text;
                string txtToTime = (row.FindControl("txtTotime") as TextBox).Text;
                CheckBox chkActiveTiming = (row.FindControl("chkActive") as CheckBox);
                int chkValue;
                if (chkActiveTiming.Checked == false)
                {
                    chkValue = 0;
                }
                else
                {
                    chkValue = 1;
                }

                if (cmbBranches.SelectedIndex != 0)
                {

                    // Prevention SQL Injection  : 11-10-21 
                    // Prevention XSS 
                    // Parameterized approaches 

                    //CONCAT(DATE(DateTimeField),' 12:34:56');
                    BranchFullName = Microsoft.Security.Application.Encoder.HtmlEncode(cmbBranches.SelectedItem.Text);
                    Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);
                    string sQuery = "Update {0}.Menu Set FromTime=@FromTime ,ToTime=@ToTime,ActiveTiming=@ActiveTiming where CategoryId= @CategoryId ";
                    string command = string.Format(sQuery, Cmb_BranchName, txtFromTime, txtToTime);

                    MySqlParameter[] parameters =
                         {
                             new MySqlParameter("@FromTime",Convert.ToDateTime(txtFromTime)),
                             new MySqlParameter("@ToTime",Convert.ToDateTime(txtToTime)),
                             new MySqlParameter("@ActiveTiming",chkValue),
                             new MySqlParameter("@CategoryId",RCategoryid),
                        };

                    UpdateTiming = ObjMain.ExecuteQuery(command, parameters);
                    if (UpdateTiming > 0)
                    {
                        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Category Timing Successfully Updated. ');location.href='CategoryCustomize.aspx'", true);
                    }
                    else
                    {
                        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Failed to Update Category Timing, Please Contact Suntoyo Support. ');location.href='CategoryCustomize.aspx'", true);
                    }
                }
            }
        }

        protected void grdCategoryCustom_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                CheckBox chkActiveTiming = (CheckBox)e.Row.FindControl("chkActive");
                TextBox txtFromtime = (TextBox)e.Row.FindControl("txtFromtime");
                TextBox txtTotime = (TextBox)e.Row.FindControl("txtTotime");
                Button  btnLsave = (Button)e.Row.FindControl("btnSave");
                Button btnLenable = (Button)e.Row.FindControl("btnEnable");
                Button btndisable = (Button)e.Row.FindControl("btnDisable");
                if (chkActiveTiming.Checked == false)
                {
                    txtFromtime.Enabled = false;
                    txtTotime.Enabled = false;
                }


                #region User's  Write Permission Added 
                if (Session["Write_Acess"].ToString() == "N")
                {
                    btnLsave.CssClass = "alert-danger";
                    btnLsave.Enabled = false;
                    btnLsave.ToolTip = " Write Permission Not Allowed for this user ! ";


                    btnLenable.CssClass= "alert-danger";
                    btnLenable.Enabled = false;
                    btnLenable.ToolTip = " Write Permission Not Allowed for this user ! ";

                    btndisable.CssClass = "alert-danger";
                    btndisable.Enabled = false;
                    btndisable.ToolTip= " Write Permission Not Allowed for this user ! ";

                }
                #endregion

            }
            //
            //{
            //    if (e.Row.Cells[2].Text != "")//orderstatus index
            //    {
            //        e.Row.Enabled = false;
            //    }
            //    else
            //    {
            //        e.Row.Enabled = true;

            //    }

            //}
        }

        protected void chkActive_Changed(object sender, EventArgs e)
        {
            foreach (GridViewRow gvrow in grdCategoryCustom.Rows)
            {
                CheckBox chkRow = (gvrow.Cells[8].FindControl("chkActive") as CheckBox);
                TextBox txtFromTime = (gvrow.Cells[6].FindControl("txtFromtime") as TextBox);
                TextBox txtToTime = (gvrow.Cells[6].FindControl("txtTotime") as TextBox);

                if (chkRow.Checked)
                {
                    //if checked do something
                    txtFromTime.Enabled = true;
                    txtToTime.Enabled = true;
                }
                else
                {
                    txtFromTime.Enabled = false;
                    txtToTime.Enabled = false;
                }
            }           
            //CheckBox chkActiveTiming = (CheckBox)e.Row.FindControl("chkActive");
            //TextBox txtFromtime = (TextBox)e.Row.FindControl("txtFromtime");
            //TextBox txtTotime = (TextBox)e.Row.FindControl("txtTotime");
            //if (chkActiveTiming.Checked == false)
            //{
            //    txtFromtime.Enabled = false;
            //    txtTotime.Enabled = false;
            //}


            //CheckBox cbox = sender as CheckBox;
            //if (cbox.Checked == true)
            //{

            //}
            //else
            //{
            //}

        }

        protected void btnSave_Click(object sender, EventArgs e)
        {

        }

    }
}