using CLS_BL;
using CLS_DL;
using CLS_PL;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using iTextSharp.text;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
using MySql.Data;
using MySql.Data.MySqlClient;
using Newtonsoft.Json;
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.HtmlControls;
using System.Web.UI.WebControls;
namespace SUNWEB
{
    public partial class WebStockSetting : 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 Q = 0;
        string ConStr = ConfigurationManager.ConnectionStrings["ConMysql"].ConnectionString;
        string ConStr_Rds = ConfigurationManager.ConnectionStrings["ConRDS"].ConnectionString;
        string Curr_Date = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        string Curr_DateOnly = System.DateTime.Now.ToString("yyyy-MM-dd");
        DateTime MonthstartDt;
        DataSet ds = new DataSet();
        MYSQLDB ObjMain = new MYSQLDB();
        DataTable DT = new DataTable();
        DataTable Dt2 = new DataTable();
        DataTable DtLicense = new DataTable();
        DataTable DtSuperAdmin = new DataTable();
        DataTable DtMultiBranch = new DataTable();
        DataTable DtNormalUser = new DataTable();
        DataTable DTProductSale = new DataTable();
        MySqlCommand Cmdv = new MySqlCommand();
        DataTable DtinventoryCnt = new DataTable();
        DataTable DtRead = new DataTable();
        // User Variables 
        string UserId = string.Empty;
        string UserName = string.Empty;
        string PortalTypeId = string.Empty;
        string cd_Id = string.Empty;
        string Datapath = string.Empty;
        string cd_BranchAlias = string.Empty;
        string IsMultiBranch = string.Empty;
        string IsSuperAdmin = string.Empty;
        string ActiveCallvalue = string.Empty;
        // License Variables ..
        string PID = string.Empty;
        string Page_Acess = string.Empty;
        string Read_Acess = string.Empty;
        string Write_Acess = string.Empty;
        string Isdowld_Acess = string.Empty;
        string Rcd_id = string.Empty;
        string RPortalid = string.Empty;
        string Useridvalue = string.Empty;
        string QueryCurr_Select = string.Empty;
        string L_MaxUserCnt = string.Empty;

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

        string HQ = string.Empty;
        string Cm_id = string.Empty;
        string ISHQ = string.Empty;
        DataSet DS = new DataSet();
        string BranchAlias=string.Empty;
        string sActive = string.Empty;
        string Vw_Chk = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {

            PID = "71";    // This is for Webstockcount 


            if (!IsPostBack)
            {
               
            }
            MonthstartDt = new DateTime(System.DateTime.Now.Year, System.DateTime.Now.Month, 1);
            if (Session["UserName"] == null)
            {
                Response.Redirect("Login.aspx");
            }
            if (((Convert.ToBoolean(Session["IsSuperAdmin"])) == true) && (Session["PortalTypeId"].ToString() == "") && ((Convert.ToBoolean(Session["IsMultiBranch"])) == true))
            {
                if (!IsPostBack)
                {
                    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_WebStockSetting"].ToString() == "N") || (Session["Page_Acess"].ToString() == "N"))
                {
                    Response.Redirect("DeniedPage.aspx");
                }
                else
                {
                    // lblMsgTotalSelection.Text = "Item Sale  Between" + "&nbsp;&nbsp;&nbsp;&nbsp;" + txtStartDt.Text + "&nbsp;&nbsp;&nbsp;  and  &nbsp;&nbsp;&nbsp;" + txtEndDt.Text;
                    if (!IsPostBack)
                    {
                        if (Session["Isdowld_Acess"].ToString() == "N")
                        {
                            // btnExcel.Enabled = false;
                            Response.Write(@"<script language='javascript'>alert('No Access To download.')</script>");
                        }
                        else
                        {
                            

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

                        }


                    }

                }

            }
            else
            {

            }


        }


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


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

            if (ISHQ != "")
            {
                ActiveCallvalue = ObjSel.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);
            DT = ObjUserBL.GetPageRightsDetailsPIDNew(Session["UserId"].ToString(), PID, Branchidval);
            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_WebStockSetting = DtLicense.Rows[0]["WEBSTOCKPRESET"].ToString();
                Session["L_WebStockSetting"] = L_WebStockSetting;
            }
            if (Session["L_WebStockSetting"].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);

                INS_WebStock(ActiveCallvalue);
                LoadWebStockList(ActiveCallvalue);
                LoadInventoryview();
                System.Threading.Thread.Sleep(2000);

            }

        }


        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 cmbBranches_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbBranches.SelectedIndex == 0)
            {
                Response.Write("Iorderlasetting.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;
                }

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

                if (ISHQ != "")
                {
                    ActiveCallvalue = ObjSel.GetFirstBranch7(Session["Branch_HQ"].ToString(), Session["UserId"].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=" + Microsoft.Security.Application.Encoder.HtmlEncode(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_MaxUserCnt = DtLicense.Rows[0]["UserCnt"].ToString();
                    L_WebStockSetting = DtLicense.Rows[0]["WEBSTOCKPRESET"].ToString();
                    Session["L_WebStockSetting"] = L_WebStockSetting;


                }

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

                }
                else if (Session["Write_Acess"].ToString() == "N")
                {
                    //btnGeneratebyinventoryid.Enabled = false;
                    //btnGenerateIorderlaTiming.Enabled = false;
                    
                }
                else
                {
                    // INS_ScheduleFlag(Cmb_BranchName);
                    // LoadInventoryview();
                    // btnGeneratebyinventoryid.Enabled = true;
                    // btnGenerateIorderlaTiming.Enabled = true;
                    // LoadBaseTiming(Cmb_BranchName);
                    INS_WebStock(ActiveCallvalue);
                    LoadWebStockList(Cmb_BranchName);
                    LoadInventoryview();
                }
            }
            UPDATEBRANCH(Cmb_BranchName);

        }

        protected void grdWebStockSetting_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "Update")
            {
                int index = Convert.ToInt32(e.CommandArgument);
                GridViewRow row = grdWebStockSetting.Rows[index];
                string RInventoryid = (row.FindControl("lblInventoryid") as Label).Text;
                string RBarcode = (row.FindControl("lblBarcode") as Label).Text;
                string RPresetvalue = (row.FindControl("txtWebPresetValue") as TextBox).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 )

                    string UPTQuery = "UPDATE {0}.WebstockPreset  SET PreSetValue=@PreSetValue  where Inventoryid=@Inventoryid ";
                    string command = string.Format(UPTQuery, Cmb_BranchName);

                    MySqlParameter[] parameters =
                       {
                             new MySqlParameter("@PreSetValue",RPresetvalue),
                             new MySqlParameter("@Inventoryid",RInventoryid),
                        };

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



                }


              }
            }


        public void INS_WebStock(string sdb)
        {

            // Local Variable 

            string Inventoryid = string.Empty;
            string Barcode = string.Empty;
            DataTable Dtwebstock = new DataTable();
            //#1 Check the Webstock table Record  count 

            string webstock_query = " select * from {0}.`WebstockPreset`";
            string webstock_command = string.Format(webstock_query, sdb);
            Dtwebstock = ObjMain.GetData_DT(webstock_command);

            //#2 Get Inventory Table Record Count 

            string InventoryRowCountQuery = "select * from {0}.Inventory; ";
            string Inventory_command = string.Format(InventoryRowCountQuery, sdb);
            DtinventoryCnt = ObjMain.GetData_DT(Inventory_command);

            //#3. If PriceFlag  is NULL 
            if (Dtwebstock.Rows.Count == 0)
            {
                // Call Insert Function

                string ReadInventoryids = "select Inventoryid,Barcode from {0}.inventory order by Inventoryid; ";
                string commandReads = string.Format(ReadInventoryids, sdb);
                DtRead = ObjMain.GetData_DT(commandReads);

                for (int i = 0; i < DtRead.Rows.Count; i++)
                {
                    DataRow dr = DtRead.Rows[i];

                    Inventoryid = dr["Inventoryid"].ToString();
                    Barcode = dr["BarCode"].ToString();

                    // #1.2 IF Not Exist   
                    // Call Insert  Function : PriceFlag
                    #region   Insert Portion
                    string Ins_webstock = " insert into {0}.WebstockPreset (Inventoryid,Barcode,PreSetValue,PresetTime,TriggerDate)" +
                                           " values " +
                                           " (@Inventoryid,@Barcode,@PreSetValue,@PresetTime,@TriggerDate);";
                    string Ins_command = string.Format(Ins_webstock, sdb);
                    MySqlParameter[] parameters =
                        {
                             new MySqlParameter("@Inventoryid",Inventoryid),
                             new MySqlParameter("@Barcode",Barcode),
                             new MySqlParameter("@PreSetValue","1000"),
                             new MySqlParameter("@PresetTime",DateTime.Today.AddDays(1)),
                             new MySqlParameter("@TriggerDate",DateTime.Today),

                        };
                    Q = ObjMain.ExecuteQuery(Ins_command, parameters);

                    #endregion
                }


            }
            //#4. If webstock  < Inventory 
            else if (Dtwebstock.Rows.Count < DtinventoryCnt.Rows.Count)
            {

                string CheckA = string.Empty;

                //#1.1 IF Inventoryid is exist  in  PriceFlag Table Ignore to Insert 

                string ReadInventoryids = "select Inventoryid,Barcode from {0}.inventory order by Inventoryid; ";
                string commandReads = string.Format(ReadInventoryids, sdb);
                DtRead = ObjMain.GetData_DT(commandReads);

                for (int i = 0; i < DtRead.Rows.Count; i++)
                {
                    DataRow dr = DtRead.Rows[i];

                    Inventoryid = dr["Inventoryid"].ToString();
                    Barcode = dr["BarCode"].ToString();

                    // #1.2 IF Inventoryid is  Exist  in WebstockPreset  Ignore to Insert  
                    // Check the Inventoryid in 'WebstockPreset'

                    string ReadInventoryidOnwebstock = "select Inventoryid from {0}.WebstockPreset where  Inventoryid=@Inventoryid ; ";
                    string command_Rwebstock = string.Format(ReadInventoryidOnwebstock, sdb);
                    MySqlParameter[] parameters_webstock =
                    {
                     new MySqlParameter("@Inventoryid",Inventoryid),
                    };
                    CheckA = ObjMain.NewExecuteScalar(command_Rwebstock, parameters_webstock);

                    if (CheckA != "")
                    {
                        // Record Already Exist In WebstockPreset : Ignore for insert 
                    }
                    else
                    {
                        // Call Insert  Function : WebstockPreset  

                        #region   Insert Portion
                        string Ins_webstock = " insert into {0}.WebstockPreset (Inventoryid,Barcode,PreSetValue,PresetTime,TriggerDate)" +
                                               " values " +
                                               " (@Inventoryid,@Barcode,@PreSetValue,@PresetTime,@TriggerDate);";
                        string Ins_command = string.Format(Ins_webstock, sdb);
                        MySqlParameter[] parameters =
                            {
                             new MySqlParameter("@Inventoryid",Inventoryid),
                             new MySqlParameter("@Barcode",Barcode),
                             new MySqlParameter("@PreSetValue",100),
                             new MySqlParameter("@PresetTime",DateTime.Today.AddDays(1)),
                             new MySqlParameter("@TriggerDate",DateTime.Today),

                        };
                        Q = ObjMain.ExecuteQuery(Ins_command, parameters);

                        #endregion


                    }


                }



            }
            else
            {
                // Nothing To :  Run 
            }




        }

        protected void grdWebStockSetting_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            int rowIndex = e.RowIndex;
            GridViewRow row = grdWebStockSetting.Rows[rowIndex];

            string presetValue = ((TextBox)row.FindControl("txtWebPresetValue")).Text;
            string presetTime = ((TextBox)row.FindControl("txtPresetTime")).Text;
            string inventoryId = ((Label)row.FindControl("lblInventoryid")).Text;

            // Save to DB

            // 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 )

                string UPTQuery = "UPDATE {0}.WebstockPreset  SET PreSetValue=@PreSetValue  where Inventoryid=@Inventoryid ";
                string command = string.Format(UPTQuery, Cmb_BranchName);

                MySqlParameter[] parameters =
                   {
                             new MySqlParameter("@PreSetValue",presetValue),
                             new MySqlParameter("@Inventoryid",inventoryId),
                        };

                K = ObjMain.ExecuteQuery(command, parameters);

                if (K > 0)
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' WebStock Preset value Updated.');location.href='WebStockSetting.aspx'", true);
                }



                // Rebind grid
                grdWebStockSetting.EditIndex = -1;
                LoadWebStockList(Cmb_BranchName);



            }
        }


        protected void grdWebStockSetting_RowDataBound(object sender, GridViewRowEventArgs e)
        {

        }

        public void LoadWebStockList(string  db, string Inventoryid="All")
        {
            if (cmbBranches.Visible == false)
            {
              BranchAlias = Session["Branch_HQ"].ToString();
            }
            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 )
              BranchAlias = Cmb_BranchName;
            }
            if (Inventoryid == "All")
            {
              DT = ObjMain.GetData_DT("Select WebSTID, Inventoryid,Barcode,PreSetValue,time(PresetTime) as PresetTime,TriggerDate  from " + BranchAlias + ".`WebstockPreset`;  ");
            }
            else if(Inventoryid!="All")
            {

              DT = ObjMain.GetData_DT("Select WebSTID, Inventoryid,Barcode,PreSetValue,time(PresetTime) as PresetTime,TriggerDate  from " + BranchAlias + ".`WebstockPreset` where   Inventoryid="+Inventoryid +";  ");
            }
            grdWebStockSetting.DataSource = DT;
            grdWebStockSetting.DataBind();

        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {
            if (cmbBranches.Visible == false)
            {
             BranchAlias = Session["Branch_HQ"].ToString();
            }
            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 )
                BranchAlias = Cmb_BranchName;
            }

            string UPTQuery = string.Empty;
            string command = string.Empty;

            if (txtWebpresetvalue.Text != "" && txtWebPresetTime.Text != "")
            {

                UPTQuery = "UPDATE {0}.WebstockPreset  SET PreSetValue=@PreSetValue,PresetTime=@PresetTime;";
                command = string.Format(UPTQuery, Cmb_BranchName);

                MySqlParameter[] parameters =
                           {
                             new MySqlParameter("@PreSetValue", Convert.ToDecimal(txtWebpresetvalue.Text)),
                             new MySqlParameter("@PresetTime",Convert.ToDateTime( txtWebPresetTime.Text)),

                        };

                S = ObjMain.ExecuteQuery(command, parameters);


            }
            else if (txtWebpresetvalue.Text != "" && txtWebPresetTime.Text == "")
            {
                 UPTQuery = "UPDATE {0}.WebstockPreset  SET PreSetValue=@PreSetValue;";
                 command = string.Format(UPTQuery, Cmb_BranchName);

                MySqlParameter[] parameters =
                           {
                             new MySqlParameter("@PreSetValue", Convert.ToDecimal(txtWebpresetvalue.Text)),
                             //new MySqlParameter("@PresetTime",Convert.ToDateTime( txtWebPresetTime.Text)),

                        };

                S = ObjMain.ExecuteQuery(command, parameters);

            }
            else if (txtWebpresetvalue.Text == "" && txtWebPresetTime.Text != "")
            {
                UPTQuery = "UPDATE {0}.WebstockPreset  SET PresetTime=@PresetTime;";
                command = string.Format(UPTQuery, Cmb_BranchName);

                MySqlParameter[] parameters =
                           {
                             //new MySqlParameter("@PreSetValue", Convert.ToDecimal(txtWebpresetvalue.Text)),
                             new MySqlParameter("@PresetTime",Convert.ToDateTime( txtWebPresetTime.Text)),

                        };

                S = ObjMain.ExecuteQuery(command, parameters);

            }


            #region   SERVICE RUN WebstockCount 
            String R_value = ObjMain.ExecuteScalar(" select inivalue from  " + BranchAlias + ".weborderinginisetting where id = 83;");
            String R_PresetTime = ObjMain.ExecuteScalar(" SELECT PresetTime FROM " + BranchAlias + ".WebstockPreset Limit 1;");


            if (R_value == "1" && R_PresetTime!=" ")
            {
                #region  - > Procedure 1- Update
                string C_Query = string.Empty;
                Int32 C_Q1 = 0;
                try
                {
                    #region Drop Procedure if exist..
                    string dropStatement = @"DROP PROCEDURE IF EXISTS {0}.`UpdateWebStockFromPreset` ; ";
                    string command_dropsql = string.Format(dropStatement, BranchAlias);
                    K = ObjMain.ExecuteNonQuery(command_dropsql);
                    #endregion

                    #region Create Procedure 
                    string createStatement = @"
                    CREATE DEFINER=`suntoyoroot`@`%` PROCEDURE {0}.UpdateWebStockFromPreset()
                    BEGIN
                    UPDATE {0}.Inventory AS I
                    JOIN {0}.WebstockPreset AS P ON I.InventoryID = P.InventoryID
                    SET I.webstockcount = P.PreSetValue;
                    UPDATE {0}.WebstockPreset  set TriggerDate=CONVERT_TZ(now(), '+00:00', '+08:00');
                    END; ";
                    string commmand_Proc1 = string.Format(createStatement, BranchAlias);
                    C_Q1 = ObjMain.ExecuteNonQuery(commmand_Proc1);
                    #endregion
                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    C_Query = string.Empty;
                    C_Q1 = 0;
                }

                #endregion

                #region  - > Procedure 2 - Create Events

                try
                {
                    #region Drop Procedure if exist..
                    string dropStatement = @"DROP PROCEDURE IF EXISTS {0}.`GetNextWebStockEventTime` ; ";
                    string command_dropsql = string.Format(dropStatement, BranchAlias);
                    K = ObjMain.ExecuteNonQuery(command_dropsql);

                    #endregion

                    C_Query = @"
                    CREATE DEFINER=`suntoyoroot`@`%` PROCEDURE {0}.GetNextWebStockEventTime()
                    BEGIN
                        DECLARE R_presetTime TIME;
                        DECLARE fullDateTimeSG DATETIME;
                        DECLARE fullDateTimeUTC DATETIME;

                        -- Get preset time (time only)
                        SELECT time(presetTime) INTO R_presetTime
                        FROM {0}.WebstockPreset
                        LIMIT 1;

                        -- Combine today's date with preset time to get full datetime in SG time
                        SET fullDateTimeSG = STR_TO_DATE(CONCAT(CURDATE(), ' ', R_presetTime), '%Y-%m-%d %H:%i:%s');

                        -- Convert from Singapore time (+08:00) to UTC (+00:00)
                        SET fullDateTimeUTC = CONVERT_TZ(fullDateTimeSG, '+08:00', '+00:00');

                        -- Return UTC datetime
                        SELECT fullDateTimeUTC AS NextRunTime;
                    END;
                    ";
                    string commmand_Proc1 = string.Format(C_Query, BranchAlias);
                    C_Q1 = ObjMain.ExecuteNonQuery(commmand_Proc1);

                    // Call the Procedure .. 

                    string cmd_Calldml = "CALL  {0}.GetNextWebStockEventTime();";
                    string commmand_DROPAndCREATE = string.Format(cmd_Calldml, BranchAlias);
                    


                    var nextRunTime = Convert.ToDateTime(ObjMain.ExecuteScalar(commmand_DROPAndCREATE));
                    string dropSql = "DROP EVENT IF EXISTS {0}.RunWebStockUpdate";
                    string commmand_DROP = string.Format(dropSql, BranchAlias);
                    K = ObjMain.ExecuteNonQuery(commmand_DROP);

                    string createSql = string.Format(@"
                    CREATE DEFINER=`suntoyoroot`@`%` EVENT {0}.RunWebStockUpdate
                    ON SCHEDULE EVERY 1 DAY
                    STARTS '{1:yyyy-MM-dd HH:mm:ss}'
                    DO CALL {0}.UpdateWebStockFromPreset();",
                    BranchAlias, nextRunTime);

                    L = ObjMain.ExecuteNonQuery(createSql);

                }
                catch (Exception ex)
                {
                    throw ex;
                }
                finally
                {
                    C_Query = string.Empty;
                    C_Q1 = 0;
                }

                #endregion

            }
            else
            {
                // No Need to call anything 

            }

            #endregion
            if (S > 0)
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' WebStock Preset value Updated.');location.href='WebStockSetting.aspx'", true);
            }

        }

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

                }
                #endregion
            }
            else
            {
                BranchAlias = Session["Branch_HQ"].ToString();
            }
            if (cmbSearch.SelectedIndex == 1)
            {
                //txtSearchVal.Text = "";
                LoadInventoryview();
                txtSearchVal.Enabled = true;
            }
            else if (cmbSearch.SelectedIndex == 2)
            {
                //txtSearchVal.Text = "";
                LoadInventoryview();
            }
            else if (cmbSearch.SelectedIndex == 3)
            {
                //txtSearchVal.Text = "";
                LoadInventoryview();
                txtSearchVal.Enabled = true;
            }
            else if (cmbSearch.SelectedIndex == 4)
            {
                //txtSearchVal.Text = "";
                LoadInventoryview();
            }
            else if (cmbSearch.SelectedIndex == 5)
            {
                //txtSearchVal.Text = "";
                LoadInventoryview();
                txtSearchVal.Enabled = true;
            }
            if (cmbSearch.SelectedIndex == 6)
            {
                //txtSearchVal.Text = "";
                txtSearchVal.Enabled = true;
            }
            else if (cmbSearch.SelectedIndex == 1 || cmbSearch.SelectedIndex == 2 || cmbSearch.SelectedIndex == 3 || cmbSearch.SelectedIndex == 4 || cmbSearch.SelectedIndex == 5 || cmbSearch.SelectedIndex == 6)
            {

            }
            else
            {
                LoadInventoryview();
            }

            if (cmbSearch.SelectedIndex == 7)
            {

                txtSearchVal.Text = "";

            }



        }

        protected void txtSearchVal_TextChanged(object sender, EventArgs e)
        {
            string sActive = string.Empty;

            txtSearchVal.CssClass = "form-control";

            //Page.ClientScript.RegisterStartupScript(this.GetType(), "hash", "location.hash = '#GridContend';", true);
            // ModalPopupExtender7.Show();
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ShowModalInventoryList();", true);

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

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



            if (cmbSearch.SelectedIndex == 0)
            {
                //John added This All Condition
                if (chkActiveonly.Checked == true)// John added 02-Nov-2020 Active/InActive Include inside Query
                {
                    sActive = " where I.active <> 0";
                }
                else
                {
                    sActive = " where I.active = 0";
                }

                // Prevents SQL Injections 
                // Parameterized approach 

                string Inv_Qry1 = "select * from {0}.inventory as I join  {0}.inventorycategories  as c ON I.Categoryid=c.categoryid " + sActive;
                string command1 = string.Format(Inv_Qry1, BranchAlias);
                // Append the Database's Variable along with the query 
                DT = ObjMain.GetData_DT(command1);
                grdInventoryView.DataSource = DT;
                grdInventoryView.DataBind();
            }
            else if (cmbSearch.SelectedIndex == 1)
            {
                if (chkActiveonly.Checked == true) // John added 02-Nov-2020 Active/InActive Include inside Query
                {
                    sActive = " and I.active <> 0";
                }
                else
                {
                    sActive = " and I.active = 0";
                }

                string Inv_Qry1 = "select * from {0}.inventory as I join  {0}.inventorycategories  as c ON I.Categoryid=c.categoryid where I.Inventoryid=@SearchVal " + sActive;
                string command2 = string.Format(Inv_Qry1, BranchAlias);

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

                DT = ObjMain.NewGetData_DT(command2, parameters);

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

            }
            else if (cmbSearch.SelectedIndex == 2)
            {
                if (chkActiveonly.Checked == true)// John added 02-Nov-2020 Active/InActive Include inside Query
                {
                    sActive = " and I.active <> 0";
                }
                else
                {
                    sActive = " and I.active = 0";
                }


                string Inv_Qry2 = "select * from {0}.inventory as I join  {0}.inventorycategories  as c ON I.Categoryid=c.categoryid where  I.barcode like CONCAT('%', @SearchVal, '%') " + sActive;
                string command3 = string.Format(Inv_Qry2, BranchAlias);

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

                DT = ObjMain.NewGetData_DT(command3, parameters);
                grdInventoryView.DataSource = DT;
                grdInventoryView.DataBind();

            }

            else if (cmbSearch.SelectedIndex == 3)
            {
                if (chkActiveonly.Checked == true) // John added 02-Nov-2020 Active/InActive Include inside Query
                {
                    sActive = " and I.active <> 0";
                }
                else
                {
                    sActive = " and I.active = 0";
                }


                string Inv_Qry3 = "select * from {0}.inventory as I join  {0}.inventorycategories  as c ON I.Categoryid=c.categoryid where  I.InventoryName like CONCAT('%', @SearchVal, '%') " + sActive;
                string command4 = string.Format(Inv_Qry3, BranchAlias);

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

                DT = ObjMain.NewGetData_DT(command4, parameters);

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


            }
            else if (cmbSearch.SelectedIndex == 4)
            {
                if (chkActiveonly.Checked == true) // John added 02-Nov-2020 Active/InActive Include inside Query
                {
                    sActive = " and I.active <> 0";
                }
                else
                {
                    sActive = " and I.active = 0";
                }
                string Inv_Qry4 = "select * from {0}.inventory as I join  {0}.inventorycategories  as c ON I.Categoryid=c.categoryid where  I.Description like CONCAT('%', @SearchVal, '%') " + sActive;

                string command5 = string.Format(Inv_Qry4, BranchAlias);

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

                DT = ObjMain.NewGetData_DT(command5, parameters);

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

            }

            else if (cmbSearch.SelectedIndex == 5)
            {
                if (chkActiveonly.Checked == true) // John added 02-Nov-2020 Active/InActive Include inside Query
                {
                    sActive = " and I.active <> 0";
                }
                else
                {
                    sActive = " and I.active = 0";
                }

                string Inv_Qry4 = "select * from {0}.inventory as I join  {0}.inventorycategories  as c ON I.Categoryid=c.categoryid where Price =@Price  OR price2 =@Price OR price3 =@Price OR  price3 =@Price " + sActive;
                string command6 = string.Format(Inv_Qry4, BranchAlias);
                MySqlParameter[] parameters =
                 {
                     new MySqlParameter("@Price", txtSearchVal.Text.ToString().Trim()) ,
                  };

                DT = ObjMain.NewGetData_DT(command6, parameters);
                grdInventoryView.DataSource = DT;
                grdInventoryView.DataBind();


            }


            else if (cmbSearch.SelectedIndex == 6)
            {
                string sActivex = string.Empty;

                if (chkActiveonly.Checked == true) // John added 02-Nov-2020 Active/InActive Include inside Query
                {
                    sActivex = " and I.active <> 0";
                }
                else
                {
                    sActivex = " and I.active = 0";
                }


                //string Inv_Qry5 = "select * from " + BranchAlias + ".inventory as I join  " + BranchAlias + ".inventorycategories  as c ON I.Categoryid=c.categoryid ORDER BY I.inventoryID asc LIMIT " + txtTop.Text.ToString().Trim() + "";
                string Inv_Qry5 = "Select *,sum(pquantity-(CutQuantity+RetailQty))as OnHandICA from {0}.inventory as I " +
                                " join {0}.inventorycategories  as c ON I.Categoryid=c.categoryid " +
                                " join {0}.inventorycostaverage ic on ic.inventoryid=i.inventoryid where c.categoryname like CONCAT('%', @SearchVal, '%')    " + sActivex + "    group by I.inventoryid";
                string command7 = string.Format(Inv_Qry5, BranchAlias);
                MySqlParameter[] parameters =
                  {
                     new MySqlParameter("@SearchVal",txtSearchVal.Text.ToString().Trim()),
                  };

                DT = ObjMain.NewGetData_DT(command7, parameters);
                grdInventoryView.DataSource = DT;
                grdInventoryView.DataBind();
                //txtSearchVal.Text = "";

            }

            else if (cmbSearch.SelectedIndex == 7)
            {
                if (chkActiveonly.Checked == true) // John added 02-Nov-2020 Active/InActive Include inside Query
                {
                    sActive = " and I.active <> 0";
                }
                else
                {
                    sActive = " and I.active = 0";
                }

                string sCmdMBarcode = "Select * from {0}.inventory as A join {0}.inventorycategories as B on A.CategoryID = B.CategoryID Where Class = '10' and BarCode like CONCAT('%', @SearchVal, '%') " + sActive;


                string command8 = string.Format(sCmdMBarcode, BranchAlias);
                MySqlParameter[] parameters =
                  {
                     new MySqlParameter("@SearchVal", txtSearchVal.Text.ToString().Trim()) ,
                  };

                DT = ObjMain.NewGetData_DT(command8, parameters);

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

            }



            // Groups Condition
            if (cmbSearch.SelectedIndex == 8)
            {
                string group1Value = "group1";
                LoadGroupDetail(group1Value, txtSearchVal.Text.ToString().Trim());

            }
            else if (cmbSearch.SelectedIndex == 9)
            {
                string group2Value = "group2";
                LoadGroupDetail(group2Value, txtSearchVal.Text.ToString().Trim());

            }
            else if (cmbSearch.SelectedIndex == 10)
            {
                string group3Value = "group3";
                LoadGroupDetail(group3Value, txtSearchVal.Text.ToString().Trim());

            }

            else if (cmbSearch.SelectedIndex == 11)
            {
                string group4Value = "group4";
                LoadGroupDetail(group4Value, txtSearchVal.Text.ToString().Trim());

            }
            else if (cmbSearch.SelectedIndex == 12)
            {
                string group5Value = "group5";
                LoadGroupDetail(group5Value, txtSearchVal.Text.ToString().Trim());

            }



        }

        public void LoadGroupDetail(string groupname, string SearchText)
        {



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

                }
                #endregion

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




            if (chkActiveonly.Checked == true)
            {
                sActive = " and I.active <> 0";
            }
            else
            {
                sActive = " and I.active = 0";
            }


            string Inv_Qry5 = "Select *,sum(pquantity-(CutQuantity+RetailQty))as OnHandICA from {0}.inventory as I " +
                       " join {0}.inventorycategories  as c ON I.Categoryid=c.categoryid " +
                       " join {0}.inventorycostaverage ic on ic.inventoryid=i.inventoryid where   I.{1} like  CONCAT('%',@SearchText,'%')   " + sActive + "    group by I.inventoryid";

            string command = string.Format(Inv_Qry5, BranchAlias, groupname);

            MySqlParameter[] parameters =
                {
                     new MySqlParameter("@SearchText",SearchText.ToString().Trim()),

                    };


            DT = ObjMain.NewGetData_DT(command, parameters);
            grdInventoryView.DataSource = DT;
            grdInventoryView.DataBind();
            //txtSearchVal.Text = "";

        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            string sActive = string.Empty;

            txtSearchVal.CssClass = "form-control";
            

            //Page.ClientScript.RegisterStartupScript(this.GetType(), "hash", "location.hash = '#GridContend';", true);
            //  ModalPopupExtender7.Show();
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ShowModalInventoryList();", true);

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

                }
                #endregion

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

            if (cmbSearch.SelectedIndex == 0)
            {
                //John added This All Condition
                if (chkActiveonly.Checked == true)// John added 02-Nov-2020 Active/InActive Include inside Query
                {
                    sActive = " where I.active <> 0";
                }
                else
                {
                    sActive = " where I.active = 0";
                }
                string Inv_Qry1 = "select * from {0}.inventory as I join  {0}.inventorycategories  as c ON I.Categoryid=c.categoryid " + sActive;
                string NewQuery = string.Format(Inv_Qry1, BranchAlias);

                DT = ObjMain.GetData_DT(NewQuery);
                grdInventoryView.DataSource = DT;
                grdInventoryView.DataBind();
            }
            else if (cmbSearch.SelectedIndex == 1)
            {
                if (chkActiveonly.Checked == true) // John added 02-Nov-2020 Active/InActive Include inside Query
                {
                    sActive = " and I.active <> 0";
                }
                else
                {
                    sActive = " and I.active = 0";
                }

                string Inv_Qry1 = "select * from {0}.inventory as I join  {0}.inventorycategories  as c ON I.Categoryid=c.categoryid where I.Inventoryid=@SearchVal   " + sActive;
                string command = string.Format(Inv_Qry1, BranchAlias);

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

                DT = ObjMain.NewGetData_DT(command, parameters);
                // DT = ObjMain.GetData_DT(Inv_Qry1);     Existing code 
                grdInventoryView.DataSource = DT;
                grdInventoryView.DataBind();

            }
            else if (cmbSearch.SelectedIndex == 2)
            {
                if (chkActiveonly.Checked == true)// John added 02-Nov-2020 Active/InActive Include inside Query
                {
                    sActive = " and I.active <> 0";
                }
                else
                {
                    sActive = " and I.active = 0";
                }


                string Inv_Qry2 = "select * from {0}.inventory as I join  {0}.inventorycategories  as c ON I.Categoryid=c.categoryid where  I.barcode like CONCAT('%', @SearchVal, '%')  " + sActive;

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

                string command = string.Format(Inv_Qry2, BranchAlias);
                DT = ObjMain.NewGetData_DT(command, parameters);
                //  DT = ObjMain.GetData_DT(Inv_Qry2);  Exiting Code 
                grdInventoryView.DataSource = DT;
                grdInventoryView.DataBind();

            }
            else if (cmbSearch.SelectedIndex == 3)
            {
                if (chkActiveonly.Checked == true) // John added 02-Nov-2020 Active/InActive Include inside Query
                {
                    sActive = " and I.active <> 0";
                }
                else
                {
                    sActive = " and I.active = 0";
                }


                string Inv_Qry3 = "select * from {0}.inventory as I join  {0}.inventorycategories  as c ON I.Categoryid=c.categoryid where  I.InventoryName like CONCAT('%', @SearchVal, '%') " + sActive;

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

                string command = string.Format(Inv_Qry3, BranchAlias);
                DT = ObjMain.NewGetData_DT(command, parameters);
                grdInventoryView.DataSource = DT;
                grdInventoryView.DataBind();

            }
            else if (cmbSearch.SelectedIndex == 4)
            {
                if (chkActiveonly.Checked == true) // John added 02-Nov-2020 Active/InActive Include inside Query
                {
                    sActive = " and I.active <> 0";
                }
                else
                {
                    sActive = " and I.active = 0";
                }
                string Inv_Qry4 = "select * from {0}.inventory as I join  {0}.inventorycategories  as c ON I.Categoryid=c.categoryid where  I.Description like CONCAT('%', @SearchVal, '%') " + sActive;

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

                string command = string.Format(Inv_Qry4, BranchAlias);
                DT = ObjMain.NewGetData_DT(command, parameters);
                grdInventoryView.DataSource = DT;
                grdInventoryView.DataBind();

            }
            else if (cmbSearch.SelectedIndex == 5)
            {
                if (chkActiveonly.Checked == true) // John added 02-Nov-2020 Active/InActive Include inside Query
                {
                    sActive = " and I.active <> 0";
                }
                else
                {
                    sActive = " and I.active = 0";
                }

                string Inv_Qry4 = "select * from {0}.inventory as I join  {0}.inventorycategories  as c ON I.Categoryid=c.categoryid where Price =@SearchVal  OR price2 =@SearchVal OR price3 =@SearchVal OR  price4 =@SearchVal " + sActive;
                string command = string.Format(Inv_Qry4, BranchAlias);

                MySqlParameter[] parameters =
                {
                 new MySqlParameter("@SearchVal",txtSearchVal.Text.ToString().Trim()),
                };
                DT = ObjMain.NewGetData_DT(command, parameters);
                grdInventoryView.DataSource = DT;
                grdInventoryView.DataBind();


            }
            else if (cmbSearch.SelectedIndex == 6)
            {
                string sActivex = string.Empty;

                if (chkActiveonly.Checked == true) // John added 02-Nov-2020 Active/InActive Include inside Query
                {
                    sActivex = " and I.active <> 0";
                }
                else
                {
                    sActivex = " and I.active = 0";
                }


                //string Inv_Qry5 = "select * from " + BranchAlias + ".inventory as I join  " + BranchAlias + ".inventorycategories  as c ON I.Categoryid=c.categoryid ORDER BY I.inventoryID asc LIMIT " + txtTop.Text.ToString().Trim() + "";
                string Inv_Qry5 = "Select *,sum(pquantity-(CutQuantity+RetailQty))as OnHandICA from {0}.inventory as I " +
                                " join {0}.inventorycategories  as c ON I.Categoryid=c.categoryid " +
                                " join {0}.inventorycostaverage ic on ic.inventoryid=i.inventoryid where c.categoryname like CONCAT('%', @SearchVal, '%')   " + sActivex + "    group by I.inventoryid";

                string command = string.Format(Inv_Qry5, BranchAlias);
                MySqlParameter[] parameters =
                {
                 new MySqlParameter("@SearchVal",txtSearchVal.Text.ToString().Trim()),
                };
                DT = ObjMain.NewGetData_DT(command, parameters);
                grdInventoryView.DataSource = DT;
                grdInventoryView.DataBind();
                //txtSearchVal.Text = "";

            }
            else if (cmbSearch.SelectedIndex == 7)
            {
                if (chkActiveonly.Checked == true) // John added 02-Nov-2020 Active/InActive Include inside Query
                {
                    sActive = " and I.active <> 0";
                }
                else
                {
                    sActive = " and I.active = 0";
                }

                string sCmdMBarcode = "Select * from {0}.inventory as I join {0}.inventorycategories as B on I.CategoryID = B.CategoryID Where Class = '10' and BarCode like CONCAT('%', @SearchVal, '%') " + sActive;


                string command = string.Format(sCmdMBarcode, BranchAlias);
                MySqlParameter[] parameters =
                {
                 new MySqlParameter("@SearchVal",txtSearchVal.Text.ToString().Trim()),
                };
                DT = ObjMain.NewGetData_DT(command, parameters);
                grdInventoryView.DataSource = DT;
                grdInventoryView.DataBind();

            }

            // Groups Condition
            if (cmbSearch.SelectedIndex == 8)
            {
                string group1Value = "group1";
                LoadGroupDetail(group1Value, txtSearchVal.Text.ToString().Trim());

            }
            else if (cmbSearch.SelectedIndex == 9)
            {
                string group2Value = "group2";
                LoadGroupDetail(group2Value, txtSearchVal.Text.ToString().Trim());

            }
            else if (cmbSearch.SelectedIndex == 10)
            {
                string group3Value = "group3";
                LoadGroupDetail(group3Value, txtSearchVal.Text.ToString().Trim());

            }
            else if (cmbSearch.SelectedIndex == 11)
            {
                string group4Value = "group4";
                LoadGroupDetail(group4Value, txtSearchVal.Text.ToString().Trim());

            }
            else if (cmbSearch.SelectedIndex == 12)
            {
                string group5Value = "group5";
                LoadGroupDetail(group5Value, txtSearchVal.Text.ToString().Trim());

            }
            // Search Option for Takeaway 
            else if (cmbSearch.SelectedIndex == 14)
            {
                if (chkActiveonly.Checked == true) // John added 02-Nov-2020 Active/InActive Include inside Query
                {
                    sActive = " and I.active <> 0";
                }
                else
                {
                    sActive = " and I.active = 0";
                }

                //string sCmdMBarcode = "Select * from {0}.inventory as A join {0}.inventorycategories as B on A.CategoryID = B.CategoryID Where Class = '10' and BarCode like CONCAT('%', @SearchVal, '%') " + sActive;

                string sCmdMBarcode = "select * from {0}.inventory as I  join  {0}.Webtakeawaychargeonly as TA ON I.Taid=TA.id join {0}.inventorycategories  as c ON I.Categoryid=c.categoryid  where TA.Takeawaycaption  like CONCAT('%', @SearchVal, '%') " + sActive;


                string command = string.Format(sCmdMBarcode, BranchAlias);
                MySqlParameter[] parameters =
                {
                 new MySqlParameter("@SearchVal",txtSearchVal.Text.ToString().Trim()),
                };
                DT = ObjMain.NewGetData_DT(command, parameters);
                grdInventoryView.DataSource = DT;
                grdInventoryView.DataBind();

            }
            else if (cmbSearch.SelectedIndex == 15)
            {
                if (chkActiveonly.Checked == true)
                {
                    sActive = " and I.active <> 0";
                }
                else
                {
                    sActive = " and I.active = 0";
                }
                string Inv_Qry4 = "select * from {0}.inventory as I join  {0}.inventorycategories  as c ON I.Categoryid=c.categoryid where  I.StockCode like CONCAT('%', @SearchVal, '%') " + sActive;

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

                string command = string.Format(Inv_Qry4, BranchAlias);
                DT = ObjMain.NewGetData_DT(command, parameters);
                grdInventoryView.DataSource = DT;
                grdInventoryView.DataBind();

            }



        }

        protected void grdInventoryView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {

            if (cmbBranches.Visible == false)
            {
                grdInventoryView.PageIndex = e.NewPageIndex;
                LoadInventoryview(Session["Branch_HQ"].ToString());
            }
            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


                grdInventoryView.PageIndex = e.NewPageIndex;
                // LoadInventoryview();
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ShowModalInventoryList();", true);

            }


            if (cmbSearch.SelectedIndex == 0)
            {
                #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


                //John added This All Condition
                if (chkActiveonly.Checked == true)// John added 02-Nov-2020 Active/InActive Include inside Query
                {
                    sActive = " where I.active <> 0";
                }
                else
                {
                    sActive = " where I.active = 0";
                }
                string Inv_Qry1 = "select * from {0}.inventory as I join  {0}.inventorycategories  as c ON I.Categoryid=c.categoryid " + sActive;
                string NewQuery = string.Format(Inv_Qry1, BranchAlias);

                DT = ObjMain.GetData_DT(NewQuery);

                grdInventoryView.PageIndex = e.NewPageIndex;
                grdInventoryView.DataSource = DT;
                grdInventoryView.DataBind();
            }
            else if (cmbSearch.SelectedIndex == 1)
            {
                #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


                if (chkActiveonly.Checked == true) // John added 02-Nov-2020 Active/InActive Include inside Query
                {
                    sActive = " and I.active <> 0";
                }
                else
                {
                    sActive = " and I.active = 0";
                }

                string Inv_Qry1 = "select * from {0}.inventory as I join  {0}.inventorycategories  as c ON I.Categoryid=c.categoryid where I.Inventoryid=@SearchVal   " + sActive;
                string command = string.Format(Inv_Qry1, BranchAlias);

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

                DT = ObjMain.NewGetData_DT(command, parameters);
                // DT = ObjMain.GetData_DT(Inv_Qry1);     Existing code 
                grdInventoryView.PageIndex = e.NewPageIndex;
                grdInventoryView.DataSource = DT;

                grdInventoryView.DataBind();

            }
            else if (cmbSearch.SelectedIndex == 2)
            {

                #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

                if (chkActiveonly.Checked == true)// John added 02-Nov-2020 Active/InActive Include inside Query
                {
                    sActive = " and I.active <> 0";
                }
                else
                {
                    sActive = " and I.active = 0";
                }


                string Inv_Qry2 = "select * from {0}.inventory as I join  {0}.inventorycategories  as c ON I.Categoryid=c.categoryid where  I.barcode like CONCAT('%', @SearchVal, '%')  " + sActive;

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

                string command = string.Format(Inv_Qry2, BranchAlias);
                DT = ObjMain.NewGetData_DT(command, parameters);
                //  DT = ObjMain.GetData_DT(Inv_Qry2);  Exiting Code 

                grdInventoryView.PageIndex = e.NewPageIndex;
                grdInventoryView.DataSource = DT;
                grdInventoryView.DataBind();

            }
            else if (cmbSearch.SelectedIndex == 3)
            {

                #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

                if (chkActiveonly.Checked == true) // John added 02-Nov-2020 Active/InActive Include inside Query
                {
                    sActive = " and I.active <> 0";
                }
                else
                {
                    sActive = " and I.active = 0";
                }


                string Inv_Qry3 = "select * from {0}.inventory as I join  {0}.inventorycategories  as c ON I.Categoryid=c.categoryid where  I.InventoryName like CONCAT('%', @SearchVal, '%') " + sActive;

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

                string command = string.Format(Inv_Qry3, BranchAlias);
                DT = ObjMain.NewGetData_DT(command, parameters);
                grdInventoryView.PageIndex = e.NewPageIndex;
                grdInventoryView.DataSource = DT;
                grdInventoryView.DataBind();

            }
            else if (cmbSearch.SelectedIndex == 4)
            {
                #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

                if (chkActiveonly.Checked == true) // John added 02-Nov-2020 Active/InActive Include inside Query
                {
                    sActive = " and I.active <> 0";
                }
                else
                {
                    sActive = " and I.active = 0";
                }
                string Inv_Qry4 = "select * from {0}.inventory as I join  {0}.inventorycategories  as c ON I.Categoryid=c.categoryid where  I.Description like CONCAT('%', @SearchVal, '%') " + sActive;

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

                string command = string.Format(Inv_Qry4, BranchAlias);
                DT = ObjMain.NewGetData_DT(command, parameters);
                grdInventoryView.PageIndex = e.NewPageIndex;
                grdInventoryView.DataSource = DT;
                grdInventoryView.DataBind();

            }
            else if (cmbSearch.SelectedIndex == 5)
            {
                #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

                if (chkActiveonly.Checked == true) // John added 02-Nov-2020 Active/InActive Include inside Query
                {
                    sActive = " and I.active <> 0";
                }
                else
                {
                    sActive = " and I.active = 0";
                }

                string Inv_Qry4 = "select * from {0}.inventory as I join  {0}.inventorycategories  as c ON I.Categoryid=c.categoryid where Price =@SearchVal  OR price2 =@SearchVal OR price3 =@SearchVal OR  price4 =@SearchVal " + sActive;
                string command = string.Format(Inv_Qry4, BranchAlias);

                MySqlParameter[] parameters =
                {
                 new MySqlParameter("@SearchVal",txtSearchVal.Text.ToString().Trim()),
                };
                DT = ObjMain.NewGetData_DT(command, parameters);
                grdInventoryView.PageIndex = e.NewPageIndex;
                grdInventoryView.DataSource = DT;
                grdInventoryView.DataBind();


            }
            else if (cmbSearch.SelectedIndex == 6)
            {
                #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 sActivex = string.Empty;

                if (chkActiveonly.Checked == true) // John added 02-Nov-2020 Active/InActive Include inside Query
                {
                    sActivex = " and I.active <> 0";
                }
                else
                {
                    sActivex = " and I.active = 0";
                }


                //string Inv_Qry5 = "select * from " + BranchAlias + ".inventory as I join  " + BranchAlias + ".inventorycategories  as c ON I.Categoryid=c.categoryid ORDER BY I.inventoryID asc LIMIT " + txtTop.Text.ToString().Trim() + "";
                string Inv_Qry5 = "Select *,sum(pquantity-(CutQuantity+RetailQty))as OnHandICA from {0}.inventory as I " +
                                " join {0}.inventorycategories  as c ON I.Categoryid=c.categoryid " +
                                " join {0}.inventorycostaverage ic on ic.inventoryid=i.inventoryid where c.categoryname like CONCAT('%', @SearchVal, '%')   " + sActivex + "    group by I.inventoryid";

                string command = string.Format(Inv_Qry5, BranchAlias);
                MySqlParameter[] parameters =
                {
                 new MySqlParameter("@SearchVal",txtSearchVal.Text.ToString().Trim()),
                };
                DT = ObjMain.NewGetData_DT(command, parameters);
                grdInventoryView.PageIndex = e.NewPageIndex;
                grdInventoryView.DataSource = DT;
                grdInventoryView.DataBind();
                //txtSearchVal.Text = "";

            }
            else if (cmbSearch.SelectedIndex == 7)
            {
                #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

                if (chkActiveonly.Checked == true) // John added 02-Nov-2020 Active/InActive Include inside Query
                {
                    sActive = " and I.active <> 0";
                }
                else
                {
                    sActive = " and I.active = 0";
                }

                string sCmdMBarcode = "Select * from {0}.inventory as A join {0}.inventorycategories as B on A.CategoryID = B.CategoryID Where Class = '10' and BarCode like CONCAT('%', @SearchVal, '%') " + sActive;


                string command = string.Format(sCmdMBarcode, BranchAlias);
                MySqlParameter[] parameters =
                {
                 new MySqlParameter("@SearchVal",txtSearchVal.Text.ToString().Trim()),
                };
                DT = ObjMain.NewGetData_DT(command, parameters);
                grdInventoryView.PageIndex = e.NewPageIndex;
                grdInventoryView.DataSource = DT;
                grdInventoryView.DataBind();

            }

            // Groups Condition
            if (cmbSearch.SelectedIndex == 8)
            {
                string group1Value = "group1";
                grdInventoryView.PageIndex = e.NewPageIndex;
                LoadGroupDetail(group1Value, txtSearchVal.Text.ToString().Trim());

            }
            else if (cmbSearch.SelectedIndex == 9)
            {
                string group2Value = "group2";
                grdInventoryView.PageIndex = e.NewPageIndex;
                LoadGroupDetail(group2Value, txtSearchVal.Text.ToString().Trim());

            }
            else if (cmbSearch.SelectedIndex == 10)
            {
                string group3Value = "group3";
                grdInventoryView.PageIndex = e.NewPageIndex;
                LoadGroupDetail(group3Value, txtSearchVal.Text.ToString().Trim());

            }
            else if (cmbSearch.SelectedIndex == 11)
            {
                string group4Value = "group4";
                grdInventoryView.PageIndex = e.NewPageIndex;
                LoadGroupDetail(group4Value, txtSearchVal.Text.ToString().Trim());

            }
            else if (cmbSearch.SelectedIndex == 12)
            {
                string group5Value = "group5";
                grdInventoryView.PageIndex = e.NewPageIndex;
                LoadGroupDetail(group5Value, txtSearchVal.Text.ToString().Trim());

            }
            // Search Option for Takeaway 
            else if (cmbSearch.SelectedIndex == 14)
            {
                #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

                if (chkActiveonly.Checked == true) // John added 02-Nov-2020 Active/InActive Include inside Query
                {
                    sActive = " and I.active <> 0";
                }
                else
                {
                    sActive = " and I.active = 0";
                }

                //string sCmdMBarcode = "Select * from {0}.inventory as A join {0}.inventorycategories as B on A.CategoryID = B.CategoryID Where Class = '10' and BarCode like CONCAT('%', @SearchVal, '%') " + sActive;

                string sCmdMBarcode = "select * from {0}.inventory as I  join  {0}.Webtakeawaychargeonly as TA ON I.Taid=TA.id join {0}.inventorycategories  as c ON I.Categoryid=c.categoryid  where TA.Takeawaycaption  like CONCAT('%', @SearchVal, '%') " + sActive;


                string command = string.Format(sCmdMBarcode, BranchAlias);
                MySqlParameter[] parameters =
                {
                 new MySqlParameter("@SearchVal",txtSearchVal.Text.ToString().Trim()),
                };
                DT = ObjMain.NewGetData_DT(command, parameters);
                grdInventoryView.PageIndex = e.NewPageIndex;
                grdInventoryView.DataSource = DT;
                grdInventoryView.DataBind();

            }
            else if (cmbSearch.SelectedIndex == 15)
            {
                #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

                if (chkActiveonly.Checked == true)
                {
                    sActive = " and I.active <> 0";
                }
                else
                {
                    sActive = " and I.active = 0";
                }
                string Inv_Qry4 = "select * from {0}.inventory as I join  {0}.inventorycategories  as c ON I.Categoryid=c.categoryid where  I.StockCode like CONCAT('%', @SearchVal, '%') " + sActive;

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

                string command = string.Format(Inv_Qry4, BranchAlias);
                grdInventoryView.PageIndex = e.NewPageIndex;
                DT = ObjMain.NewGetData_DT(command, parameters);
                grdInventoryView.DataSource = DT;
                grdInventoryView.DataBind();

            }


        }

        protected void OnSelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbBranches.SelectedIndex == 1)
            {

                BranchFullName = cmbBranches.SelectedItem.Text;    // This will Return Branch FullName 
                Cmb_BranchName = ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), BranchFullName);
                UPDATEBRANCH(Cmb_BranchName);
                Session["Active_Branch"] = Cmb_BranchName;

            }
            else
            {
                BranchFullName = cmbBranches.SelectedItem.Text;    // This will Return Branch FullName 
                Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);  // This will Return BranchName( Actual Database Name )
                Rcd_id = ObjMain.ExecuteScalar("select cd_id from portaldb.companydetails where cd_branchid=" + cmbBranches.SelectedItem.Value + " and cd_branchalias='" + Cmb_BranchName + "';");
                RPortalid = ObjMain.ExecuteScalar("select portaltypeid  from portaldb.invoicedetails where cd_id=" + Rcd_id + ";");
                DtLicense = ObjUserBL.GetLicenseDetails(RPortalid);
                Session["Active_Branch"] = Cmb_BranchName;

            }



            //Accessing TemplateField Column controls.
            string Barcode = (grdInventoryView.SelectedRow.FindControl("lblBarCode") as Label).Text;
            string InventoryId = (grdInventoryView.SelectedRow.FindControl("lblInventoryID") as Label).Text;
            

            string NewBarcode = Barcode.Substring(Barcode.Length - 1);

            string _barcode = string.Empty;

            if (NewBarcode.Equals("0"))
            {
                _barcode = Barcode + " ";
            }
            else
            {
                _barcode = Barcode.ToString().Trim();
            }

            LoadWebStockList(Cmb_BranchName, InventoryId);

        }

        protected void OnSorting(object sender, GridViewSortEventArgs e)
        {
            this.LoadInventoryview(e.SortExpression);

        }

        public void LoadInventoryview(string sortExpression = null)
        {
            if (cmbBranches.SelectedIndex == 1)
            {

                BranchFullName = cmbBranches.SelectedItem.Text;    // This will Return Branch FullName 
                Cmb_BranchName = ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), BranchFullName);
                UPDATEBRANCH(Cmb_BranchName);
                Session["Active_Branch"] = Cmb_BranchName;

            }
            else
            {
                BranchFullName = cmbBranches.SelectedItem.Text;    // This will Return Branch FullName 
                Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);  // This will Return BranchName( Actual Database Name )
                Rcd_id = ObjMain.ExecuteScalar("select cd_id from portaldb.companydetails where cd_branchid=" + cmbBranches.SelectedItem.Value + " and cd_branchalias='" + Cmb_BranchName + "';");
                RPortalid = ObjMain.ExecuteScalar("select portaltypeid  from portaldb.invoicedetails where cd_id=" + Rcd_id + ";");
                DtLicense = ObjUserBL.GetLicenseDetails(RPortalid);
                Session["Active_Branch"] = Cmb_BranchName;

            }

            /*  string InvenQuery = "select *,sum(pquantity-(CutQuantity+RetailQty))as OnHandICA from " + BranchAlias + ".inventory as I  " +
                                  " join " + BranchAlias + ".inventorycategories  as c ON I.Categoryid=c.categoryid  " +
                                  " join " + BranchAlias + ".inventorycostaverage ic on ic.inventoryid=i.inventoryid  " +
                                  " where i.active  <> 0  group by i.inventoryid  ORDER BY I.inventoryID asc LIMIT 50000;";
             */

            string InvenQuery = "select *,sum(pquantity-(CutQuantity+RetailQty))as OnHandICA from {0}.inventory as I  " +
                                " join {0}.inventorycategories  as c ON I.Categoryid=c.categoryid  " +
                                " join {0}.inventorycostaverage ic on ic.inventoryid=i.inventoryid  " +
                                " where i.active  <> 0  group by i.inventoryid  ORDER BY I.inventoryID asc LIMIT 50000;";

            string Command = string.Format(InvenQuery, Cmb_BranchName);
            DT = ObjMain.GetData_DT(Command);


            if (sortExpression != null)
            {
                DataView dv = DT.AsDataView();
                this.SortDirection = this.SortDirection == "ASC" ? "DESC" : "ASC";

                dv.Sort = sortExpression + " " + this.SortDirection;
                grdInventoryView.DataSource = dv;
            }
            else
            {
                grdInventoryView.DataSource = DT;
            }
            grdInventoryView.DataBind();


        }
        private string SortDirection
        {
            get { return ViewState["SortDirection"] != null ? ViewState["SortDirection"].ToString() : "ASC"; }
            set { ViewState["SortDirection"] = value; }
        }



    }
}