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

namespace SUNWEB
{
    public partial class Inventory : 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 U = 0;
        Int32 S = 0;
        string ConStr = ConfigurationManager.ConnectionStrings["ConMysql"].ConnectionString;
        string ConStr_Rds = ConfigurationManager.ConnectionStrings["ConRDS"].ConnectionString;
        string Curr_Date = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        string Curr_DateOnly = System.DateTime.Now.ToString("yyyy-MM-dd");

        DataSet ds = new DataSet();
        MYSQLDB ObjMain = new MYSQLDB();
        MYSQLCLOUD ObjCloudMain = new MYSQLCLOUD();
        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();
        DataTable DTCategorydl = new DataTable();
        DataTable DtCateoryList = new DataTable();
        DataTable DtCate_Printer = new DataTable();
        DataTable DTInvInfo = new DataTable();
        DataTable DTCheckBarcode = new DataTable();
        DataTable DTQry = new DataTable();
        DataTable DTSessionAdjust = new DataTable();
        DataTable DTCosting = new DataTable();
        DataTable DTTGroups = new DataTable();

        // string BranchAlias = "saffron1";
        string BranchAlias = string.Empty;

        string Grp1_Maxid = string.Empty;
        string Grp2_Maxid = string.Empty;
        string Grp3_Maxid = string.Empty;
        string Grp4_Maxid = string.Empty;
        string Grp5_Maxid = string.Empty;

        // Category Variable :  

        string RCategoryNo = string.Empty;
        string RCategoryName = string.Empty;
        string RCate_Descp = string.Empty;
        string RActive_Stauts = string.Empty;
        string RUpdate_Status = string.Empty;
        string RBranch_Update = string.Empty;
        string RFlag1_Tax = string.Empty;
        string RFlag2_Printer = string.Empty;
        string RFireIndex = string.Empty;
        string RCateYNo = string.Empty;


        //Inventory variables for editing purpose
        string GInventoryID = string.Empty;
        string GBarcode = string.Empty;
        string GInventoryName = string.Empty;
        string GDescription = string.Empty;
        string GCategoryID = string.Empty;
        string GClass = string.Empty;
        string GUnit = string.Empty;
        string GPrice = string.Empty;
        string GPrice2 = string.Empty;
        string GPrice3 = string.Empty;
        string GPrice4 = string.Empty;
        string GDateCreated = string.Empty;
        string GGroup1 = string.Empty;
        string GGroup2 = string.Empty;
        string GGroup3 = string.Empty;
        string GGroup4 = string.Empty;
        string GGroup5 = string.Empty;
        string GFlag1 = string.Empty;
        string GFlag2 = string.Empty;
        string GReorderLevel = string.Empty;
        string GMaximumLevel = string.Empty;
        string GSafetyLevel = string.Empty;

        //for InventoryAdjust Process
        string AdjInvCost = string.Empty;
        double vQuantity = 0;
        double vUnitCost = 0;
        double dPQty = 0;
        double dNPQty = 0;
        double dPAmount = 0;
        double dNPAmount = 0;
        double dCutQty = 0;
        double dUnitCost = 0;
        double dNUnitCost = 0;
        double dCutAmount = 0;
        //for check barcode function
        string sChkBarcode = string.Empty;

        DataTable AdjDt = new DataTable();
        DataTable FAdjDt = new DataTable();
        string sSno = string.Empty;
        int iSno = 0;
        string sCmd = string.Empty;
        string Jcmd = string.Empty;

        string Jcmd1 = string.Empty;
        string Jcmd2 = string.Empty;
        string Jcmd3 = string.Empty;
        string Jcmd4 = string.Empty;
        string Jcmd5 = string.Empty;

        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_Inventory = 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;
        string InAdjId = string.Empty;

        string JSno = string.Empty;
        string JInvenID = string.Empty;
        string JBarcode = string.Empty;
        string JQty = string.Empty;
        string JFlagValue = string.Empty;
        string JinventoryNane = string.Empty;
        string Jinven_Description = string.Empty;
        decimal jUnitCost = 0;
        decimal NAdjqty = 0;
        decimal PQOH = 0;
        decimal QOH = 0;

        string ChkAdjTal = string.Empty;

        string RBranchid = string.Empty;
        string Branchid = string.Empty;
        string sActive = string.Empty;

        // Added On 02-12-2021
        string ReadHQ = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {

            
            txtSearchVal.CssClass = "form-control";
            if (Session["UserName"] == null)
            {
                Response.Redirect("Login.aspx");
            }

            PID = "13";    // This is for Inventory  PageAccess
            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();

                        if ((DataTable)Session["QtyTable"] != null)  // Checks where Adjust  Datatable Have Data r Not 
                        {

                            lblAdjustPendingText.Text = "Stock Adjust Pendings.";
                            DTSessionAdjust = (DataTable)Session["QtyTable"];
                            GrdInvAdjView.DataSource = DTSessionAdjust;
                            GrdInvAdjView.DataBind();

                        }
                        else
                        {
                            GrdInvAdjView.DataSource = null;
                            GrdInvAdjView.DataBind();
                            GrdInvAdjView.EmptyDataText = "No Inventory Selected";
                        }

                    }
                }
            }
            else if (((Convert.ToBoolean(Session["IsSuperAdmin"])) == true) && (Session["PortalTypeId"].ToString() == ""))
            {
                if (!IsPostBack)
                {
                    LoadBranchesOnID();


                }

                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;
                LoadInventoryview(BranchAlias);
            }
            else if (((Convert.ToBoolean(Session["IsMultiBranch"])) == true) && (Session["PortalTypeId"].ToString() == ""))
            {
                if (!IsPostBack)
                {
                    LoadBranchesOnID();


                    ActiveCall();

                    if ((DataTable)Session["QtyTable"] != null)       // Checks where Adjust  Datatable Have Data r Not 
                    {
                        DTSessionAdjust = (DataTable)Session["QtyTable"];
                        GrdInvAdjView.DataSource = DTSessionAdjust;
                        GrdInvAdjView.DataBind();

                    }
                    else
                    {
                        GrdInvAdjView.DataSource = null;
                        GrdInvAdjView.DataBind();
                        GrdInvAdjView.EmptyDataText = "No Inventory Selected";
                    }
                }
            }
            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 = "&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_Inventory"].ToString() == "N") || (Session["Page_Acess"].ToString() == "N"))
                {
                    Response.Redirect("DeniedPage.aspx");
                }
                else
                {

                    if (!IsPostBack)
                    {
                        if (Session["Isdowld_Acess"].ToString() == "N")
                        {

                            Response.Write(@"<script language='javascript'>alert('No Access To download.')</script>");
                        }
                        else
                        {

                        }

                        if (Session["Write_Acess"].ToString() == "N")
                        {
                            btnAdjustStockSubmit.Enabled = false;
                            btnSave.Enabled = false;
                            BranchAlias = Session["Branch_HQ"].ToString();

                            if (!IsPostBack)
                            {
                                LoadInventoryview(BranchAlias);
                            }
                        }
                        else
                        {
                            btnAdjustStockSubmit.Enabled = true;
                            btnSave.Enabled = true;
                            BranchAlias = Session["Branch_HQ"].ToString();
                            LoadInventoryview(BranchAlias);
                           
                        }


                        if (cmbBranches.Visible == false)
                        {
                            BranchAlias = Session["Branch_HQ"].ToString();
                            LoadInventoryview(BranchAlias);
                            if ((DataTable)Session["QtyTable"] != null)    // Checks where Adjust  Datatable Have Data r Not 
                            {
                                DTSessionAdjust = (DataTable)Session["QtyTable"];
                                GrdInvAdjView.DataSource = DTSessionAdjust;
                                GrdInvAdjView.DataBind();

                            }

                        }




                    }

                }

            }
            else
            {

            }


        }


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

            for (int i = 0; i < DT.Rows.Count; i++)
            {
                DataRow dr = DT.Rows[i];
                RBranchid = dr["Branchid"].ToString();
                if (StrBObj.Length != 0)
                {

                    RBranchid = "," + RBranchid;
                    StrBObj.Append("  " + RBranchid + "    ");
                }
                else
                {
                    string _get_HQ = ObjSel.GetHQ_Status(Session["CM_ID"].ToString());
                    if (_get_HQ == "0")
                    {

                        //UPDATEBRANCH(Cmb_BranchName);
                        //Response.Redirect(Request.RawUrl);
                        Branchid = RBranchid;
                        StrBObj.Append("SELECT  Branchid ,BranchName,branchfullname,datapath FROM " + Session["Branch_HQ"].ToString() + ".branches where branchid in ( " + Branchid + " ");


                    }
                    else if (_get_HQ == "1")
                    {
                        Branchid = RBranchid;
                        StrBObj.Append("SELECT  Branchid ,BranchName,branchfullname,datapath FROM " + Session["Branch_HQ"].ToString() + ".branches where branchid in (1 , " + Branchid + " ");


                    }


                }


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

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

        }
        //public void LoadCategoriesDataList()
        //{

        //    DtCateoryList = ObjSel.GetCategoryList(BranchAlias);
        //    cmbCategory.DataSource = DtCateoryList;

        //    cmbCategory.DataTextField = "CategoryName";
        //    cmbCategory.DataValueField = "CategoryID";
        //    cmbCategory.DataBind();
        //    cmbCategory.Items.Insert(0, "Select");
        //}

        //protected void txtSearchVal_TextChanged(object sender, EventArgs e)
        //{
        //    // XSS Attack Prevention 
        //    //mp1.Show();
        //    ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ShowModalInventoryAdjustList();", true);

        //    if (cmbBranches.Visible == true)
        //    {
        //        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;
        //    }
        //    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
        //    }



        //    if (cmbSearch.SelectedIndex == 0)
        //    {

        //    }
        //    else if (cmbSearch.SelectedIndex == 1)
        //    {
        //        //string Inv_Qry1 = "select * from1 " + BranchAlias + ".inventory as I join  " + BranchAlias + ".inventorycategories  as c ON I.Categoryid=c.categoryid where I.Inventoryid=" + txtSearchVal.Text.ToString().Trim() + " ";

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



        //        string Inv_Qry1All = " Select *,Round(UnitCost,3) as UCost,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 " + sActive + "    group by I.inventoryid";

        //        string command = string.Format(Inv_Qry1All, BranchAlias);
        //        DT = ObjMain.GetData_DT(command);
        //        grdInventoryView.DataSource = DT;
        //        grdInventoryView.DataBind();



        //    }

        //    else if (cmbSearch.SelectedIndex == 2)
        //    {
        //        //string Inv_Qry1 = "select * from " + BranchAlias + ".inventory as I join  " + BranchAlias + ".inventorycategories  as c ON I.Categoryid=c.categoryid where I.Inventoryid=" + txtSearchVal.Text.ToString().Trim() + " ";


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


        //        string Inv_Qry1 = "Select *,Round(UnitCost,3) as UCost,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.Inventoryid=@Inventoryid  " + sActive + "  ";

        //        string command = string.Format(Inv_Qry1, BranchAlias);

        //        MySqlParameter[] parameters =
        //        {
        //             new MySqlParameter("@Inventoryid",txtSearchVal.Text.ToString().Trim()),

        //            };

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

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


        //        string Inv_Qry2 = "Select *,Round(UnitCost,3) as UCost,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.barcode like  CONCAT('%',@barcode,'%' )    " + sActive + " Group by I.barcode ";

        //        string command1 = string.Format(Inv_Qry2, BranchAlias);

        //        MySqlParameter[] parameters1 =
        //            {
        //             new MySqlParameter("@barcode",txtSearchVal.Text.ToString().Trim()),

        //            };

        //        DT = ObjMain.NewGetData_DT(command1, parameters1);
        //        grdInventoryView.DataSource = DT;
        //        grdInventoryView.DataBind();

        //    }

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



        //        //string Inv_Qry3 = "select * from " + BranchAlias + ".inventory as I join  " + BranchAlias + ".inventorycategories  as c ON I.Categoryid=c.categoryid where  I.InventoryName like '%" + txtSearchVal.Text.ToString().Trim() + "%' ";
        //        string Inv_Qry3 = "Select *,Round(UnitCost,3) as UCost,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.InventoryName like  CONCAT('%',@SearchVal,'%')   " + sActive + " group by I.inventoryid  ";

        //        string command = string.Format(Inv_Qry3, 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 == 5)
        //    {
        //        if (chkActiveonly.Checked == true)
        //        {
        //            sActive = " and I.active <> 0";
        //        }
        //        else
        //        {
        //            sActive = " 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 *,Round(UnitCost,3) as UCost,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,'%')   " + sActive + "   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();
        //    }


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

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

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

        //    }

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

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

        //    }


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



        //        //string Inv_Qry3 = "select * from " + BranchAlias + ".inventory as I join  " + BranchAlias + ".inventorycategories  as c ON I.Categoryid=c.categoryid where  I.InventoryName like '%" + txtSearchVal.Text.ToString().Trim() + "%' ";
        //        string Inv_Qry7 = "Select *,Round(UnitCost,3) as UCost,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.Description like CONCAT('%',@SearchVal,'%') " + sActive + " group by I.inventoryid  ";

        //        string command = string.Format(Inv_Qry7, BranchAlias);

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

        //            };


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


        //    }


        //}



        protected void btnSearch_Click(object sender, EventArgs e)
        {
            // XSS Attack Prevention 
            txtSearchVal.CssClass = "form-control";
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ShowModalInventoryAdjustList();", 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)
            {

            }
            else if (cmbSearch.SelectedIndex == 1)
            {
                //string Inv_Qry1 = "select * from1 " + BranchAlias + ".inventory as I join  " + BranchAlias + ".inventorycategories  as c ON I.Categoryid=c.categoryid where I.Inventoryid=" + txtSearchVal.Text.ToString().Trim() + " ";

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

                string Inv_Qry1All = " Select *,Round(UnitCost,3) as UCost,sum(pquantity-(CutQuantity+RetailQty))as OnHandICA ,'' as Qty 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 " + sActive + "    group by I.inventoryid";
                string command = string.Format(Inv_Qry1All, BranchAlias);
                DT = ObjMain.GetData_DT(command);
                grdInventoryView.DataSource = DT;
                grdInventoryView.DataBind();
            }

            else if (cmbSearch.SelectedIndex == 2)
            {
                //string Inv_Qry1 = "select * from " + BranchAlias + ".inventory as I join  " + BranchAlias + ".inventorycategories  as c ON I.Categoryid=c.categoryid where I.Inventoryid=" + txtSearchVal.Text.ToString().Trim() + " ";


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


                string Inv_Qry1 = "Select *,Round(UnitCost,3) as UCost,sum(pquantity-(CutQuantity+RetailQty))as OnHandICA , '' as Qty 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.Inventoryid=@Inventoryid   " + sActive + "  ";

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

            }
            else if (cmbSearch.SelectedIndex == 3)
            {
                //string Inv_Qry2 = "select * from " + BranchAlias + ".inventory as I join  " + BranchAlias + ".inventorycategories  as c ON I.Categoryid=c.categoryid where  I.barcode like '%" + txtSearchVal.Text.ToString().Trim() + "%' ";

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


                string Inv_Qry2 = "Select *,Round(UnitCost,3) as UCost,sum(pquantity-(CutQuantity+RetailQty))as OnHandICA , '' as Qty 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.barcode like CONCAT('%',@SearchVal,'%')   " + sActive + " Group by I.barcode ";

                string command = string.Format(Inv_Qry2, 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 == 4)
            {
                if (chkActiveonly.Checked == true)
                {
                    sActive = " and I.active <> 0";
                }
                else
                {
                    sActive = " and I.active = 0";
                }



                //string Inv_Qry3 = "select * from " + BranchAlias + ".inventory as I join  " + BranchAlias + ".inventorycategories  as c ON I.Categoryid=c.categoryid where  I.InventoryName like '%" + txtSearchVal.Text.ToString().Trim() + "%' ";
                string Inv_Qry3 = "Select *,Round(UnitCost,3) as UCost,sum(pquantity-(CutQuantity+RetailQty))as OnHandICA , '' as Qty  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.InventoryName like  CONCAT('%',@SearchVal,'%') " + sActive + " group by I.inventoryid  ";

                string command = string.Format(Inv_Qry3, 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 == 5)
            {
                if (chkActiveonly.Checked == true)
                {
                    sActive = " and I.active <> 0";
                }
                else
                {
                    sActive = " 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 *,Round(UnitCost,3) as UCost,sum(pquantity-(CutQuantity+RetailQty))as OnHandICA , '' as Qty  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 ,'%')   " + sActive + "   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();
            }


            if (cmbSearch.SelectedIndex == 6)
            {
                string group1Value = "group1";
                LoadGroupDetail(group1Value,txtSearchVal.Text.ToString().Trim());

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

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

            }

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

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

            }


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



                //string Inv_Qry3 = "select * from " + BranchAlias + ".inventory as I join  " + BranchAlias + ".inventorycategories  as c ON I.Categoryid=c.categoryid where  I.InventoryName like '%" + txtSearchVal.Text.ToString().Trim() + "%' ";
                string Inv_Qry7 = "Select *,Round(UnitCost,3) as UCost,sum(pquantity-(CutQuantity+RetailQty))as OnHandICA , '' as Qty  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.Description like CONCAT('%',@SearchVal,'%')  " + sActive + " group by I.inventoryid  ";
                string command = string.Format(Inv_Qry7, BranchAlias);
                MySqlParameter[] parameters =
                   {
                     new MySqlParameter("@SearchVal",txtSearchVal.Text.ToString().Trim()),
                    };
                DT = ObjMain.NewGetData_DT(command, parameters);
                grdInventoryView.DataSource = DT;
                grdInventoryView.DataBind();

            }


        }

        protected void cmbSearch_SelectedIndexChanged(object sender, EventArgs e)
        {
            // XSS Attack Prevention 
            //mp1.Show();
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ShowModalInventoryAdjustList();", true);

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

            }

            // Add the Code  Group Search
           if ((cmbSearch.SelectedIndex == 1) || (cmbSearch.SelectedIndex == 2) || (cmbSearch.SelectedIndex == 3) || (cmbSearch.SelectedIndex == 1))
            {
                //mp1.Show();

                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(BranchAlias);
                    txtSearchVal.Enabled = true;
                }
                else if (cmbSearch.SelectedIndex == 2)
                {
                    //txtSearchVal.Text = "";
                    LoadInventoryview(BranchAlias);
                }
                else if (cmbSearch.SelectedIndex == 3)
                {
                    //txtSearchVal.Text = "";
                    LoadInventoryview(BranchAlias);
                    txtSearchVal.Enabled = true;
                }
                else if (cmbSearch.SelectedIndex == 4)
                {
                    //txtSearchVal.Text = "";
                    LoadInventoryview(BranchAlias);
                }
                else if (cmbSearch.SelectedIndex == 5)
                {
                    //txtSearchVal.Text = "";
                    LoadInventoryview(BranchAlias);
                    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(BranchAlias);
                }

                if (cmbSearch.SelectedIndex == 7)
                {

                    txtSearchVal.Text = "";

                }

               
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ShowModalInventoryAdjustList();", true);
            }
            else
            {
            }

        }

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


        //    string GetGroupsData = " select Groupid,GroupName from     "+BranchAlias +"."+ Groupname+" ;";
        //    DTTGroups = ObjMain.GetData_DT(GetGroupsData);
        //    cmbSGroups.DataValueField = "GroupID";
        //    cmbSGroups.DataTextField = "GroupName";
        //    cmbSGroups.DataSource = DTTGroups;
        //    cmbSGroups.DataBind();
        //    cmbSGroups.Items.Insert(0, "Select");
        //    cmbSGroups.Items.Insert(1, "ALL");

        //}
        protected void cmbSGroups_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbSearch.SelectedIndex == 6)
            {
                string group1Value = "group1";
                // LoadGroupDetail(group1Value);     

            }
            else if (cmbSearch.SelectedIndex == 7)
            {
                string group2Value = "group2";
                //  LoadGroupDetail(group2Value);     

            }
            else if (cmbSearch.SelectedIndex == 8)
            {
                string group3Value = "group3";
                //  LoadGroupDetail(group3Value);

            }

            else if (cmbSearch.SelectedIndex == 9)
            {
                string group4Value = "group4";
                // LoadGroupDetail(group4Value);

            }
            else if (cmbSearch.SelectedIndex == 10)
            {
                string group5Value = "group5";
                //  LoadGroupDetail(group5Value);

            }




        }

        public void LoadGroupDetail(string groupname, string SearchText)
        {
            // XSS Attack Prevention 

            if (cmbBranches.Visible == true)
            {
                BranchFullName = cmbBranches.SelectedItem.Text;      // This will Return Branch FullName 
                if (BranchFullName == "HQ")
                {
                    BranchAlias = 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

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




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




            string Group_Detail_Query = "Select *,Round(UnitCost,3) as UCost,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(Group_Detail_Query, BranchAlias, groupname);

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

        }

        //protected void cmbCategory_SelectedIndexChanged(object sender, EventArgs e)  Date29
        //{

        //    if (cmbBranches.Visible == true)
        //    {
        //        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;
        //    }
        //    else
        //    {
        //        BranchAlias = Session["Branch_HQ"].ToString();
        //    }

        //    if (cmbCategory.SelectedIndex !=0 )
        //    {


        //        if (cmbActive.SelectedIndex == 0) 
        //        {
        //            sActive = " and I.active <> 0";
        //        }
        //        else
        //        {
        //            sActive = " 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 *,Round(UnitCost,3) as UCost,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   c.Categoryid=" + cmbCategory.SelectedItem.Value + "  " + sActive + "   group by I.inventoryid";
        //        DT = ObjMain.GetData_DT(Inv_Qry5);
        //        grdInventoryView.DataSource = DT;
        //        grdInventoryView.DataBind();
        //        txtSearchVal.Text = "";

        //    }


        //}





        protected void btnExcel_Click(object sender, EventArgs e)
        {

            // XSS Attack Prevention 
            if (cmbBranches.Visible == false)
            {

                BranchAlias = 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
            }


            if (cmbBranches.SelectedIndex != 0)
            {
                if (Session["Isdowld_Acess"].ToString() == "N")
                {
                    Page page = HttpContext.Current.Handler as Page;
                    string message = "No Access To download";
                    System.Web.UI.ScriptManager.RegisterStartupScript(page, page.GetType(), "err_msg", "alert('" + message + "');", true);
                }
                else
                {

                    if (cmbBranches.Visible == false)
                    {

                        if (chkActiveonly.Checked == true)
                        {
                            sActive = " I.active <> 0";
                        }
                        else
                        {
                            sActive = " I.active = 0";
                        }
                        string cmd1 = "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   " + sActive + "   group by i.inventoryid ";
                        string command = string.Format(cmd1, BranchAlias);
                        DataTable Dt1 = new DataTable();
                        Dt1 = ObjMain.GetData_DT(command);
                        //Create a dummy GridView
                        GridView GridView1 = new GridView();
                        GridView1.ShowFooter = true;
                        GridView1.AllowPaging = false;
                        GridView1.DataSource = Dt1;
                        GridView1.DataBind();
                        Response.Clear();
                        Response.Buffer = true;
                        Response.AddHeader("content-disposition",
                         "attachment;filename=GridViewExport.xls");
                        Response.Charset = "";
                        Response.ContentType = "application/vnd.ms-excel";
                        StringWriter sw = new StringWriter();
                        HtmlTextWriter hw = new HtmlTextWriter(sw);
                        for (int i = 0; i < GridView1.Rows.Count; i++)
                        {
                            //Apply text style to each Row
                            GridView1.Rows[i].Attributes.Add("class", "textmode");
                        }


                        GridView1.RenderControl(hw);

                        //style to format numbers to string
                        string style = @"<style> .textmode { mso-number-format:\@; } </style>";
                        Response.Write(style);
                        Response.Output.Write(sw.ToString());
                        Response.Flush();
                        Response.End();
                    }
                    else
                    {

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


                        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;

                        }

                        string cmd1 = "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   " + sActive + "   group by i.inventoryid ";
                        string command = string.Format(cmd1, BranchAlias);
                        DataTable Dt1 = new DataTable();
                        Dt1 = ObjMain.GetData_DT(command);
                        //Create a dummy GridView
                        GridView GridView1 = new GridView();
                        GridView1.AllowPaging = false;
                        GridView1.DataSource = Dt1;
                        GridView1.DataBind();
                        Response.Clear();
                        Response.Buffer = true;
                        Response.AddHeader("content-disposition",
                         "attachment;filename=GridViewExport.xls");
                        Response.Charset = "";
                        Response.ContentType = "application/vnd.ms-excel";
                        StringWriter sw = new StringWriter();
                        HtmlTextWriter hw = new HtmlTextWriter(sw);
                        for (int i = 0; i < GridView1.Rows.Count; i++)
                        {
                            //Apply text style to each Row
                            GridView1.Rows[i].Attributes.Add("class", "textmode");
                        }
                        GridView1.DataSource = Dt1;
                        GridView1.DataBind();

                        GridView1.RenderControl(hw);
                        //style to format numbers to string
                        string style = @"<style> .textmode { mso-number-format:\@; } </style>";
                        Response.Write(style);
                        Response.Output.Write(sw.ToString());
                        Response.Flush();
                        Response.End();

                    }


                }

            }
        }

        //protected void btnSearchbyVal_Click(object sender, EventArgs e)
        //{

        //    if (cmbBranches.Visible == true)
        //    {
        //        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;
        //    }
        //    else
        //    {
        //        BranchAlias = Session["Branch_HQ"].ToString();
        //    }



        //    if (cmbSearch.SelectedIndex == 0)
        //    {

        //    }
        //    else  if (cmbSearch.SelectedIndex == 1)
        //    {
        //        //string Inv_Qry1 = "select * from " + BranchAlias + ".inventory as I join  " + BranchAlias + ".inventorycategories  as c ON I.Categoryid=c.categoryid where I.Inventoryid=" + txtSearchVal.Text.ToString().Trim() + " ";

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



        //        string Inv_Qry1All = " Select *,Round(UnitCost,3) as UCost,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 "+ sActive+"    group by I.inventoryid";
        //        DT = ObjMain.GetData_DT(Inv_Qry1All);
        //        grdInventoryView.DataSource = DT;
        //        grdInventoryView.DataBind();



        //    }

        //    else if (cmbSearch.SelectedIndex == 2)
        //    {
        //        //string Inv_Qry1 = "select * from " + BranchAlias + ".inventory as I join  " + BranchAlias + ".inventorycategories  as c ON I.Categoryid=c.categoryid where I.Inventoryid=" + txtSearchVal.Text.ToString().Trim() + " ";


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


        //        string Inv_Qry1 = "Select *,Round(UnitCost,3) as UCost,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.Inventoryid=" + txtSearchVal.Text.ToString().Trim() + " "+sActive+"  ";
        //        DT = ObjMain.GetData_DT(Inv_Qry1);
        //        grdInventoryView.DataSource = DT;
        //        grdInventoryView.DataBind();


        //    }
        //    else if (cmbSearch.SelectedIndex == 3)
        //    {
        //        //string Inv_Qry2 = "select * from " + BranchAlias + ".inventory as I join  " + BranchAlias + ".inventorycategories  as c ON I.Categoryid=c.categoryid where  I.barcode like '%" + txtSearchVal.Text.ToString().Trim() + "%' ";

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


        //        string Inv_Qry2 = "Select *,Round(UnitCost,3) as UCost,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.barcode like '%" + txtSearchVal.Text.ToString().Trim() + "%'  "+sActive+" ";
        //        DT = ObjMain.GetData_DT(Inv_Qry2);
        //        grdInventoryView.DataSource = DT;
        //        grdInventoryView.DataBind();



        //    }

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



        //        //string Inv_Qry3 = "select * from " + BranchAlias + ".inventory as I join  " + BranchAlias + ".inventorycategories  as c ON I.Categoryid=c.categoryid where  I.InventoryName like '%" + txtSearchVal.Text.ToString().Trim() + "%' ";
        //        string Inv_Qry3 = "Select *,Round(UnitCost,3) as UCost,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.InventoryName like '%" + txtSearchVal.Text.ToString().Trim() + "%' " + sActive + " group by I.inventoryid  ";

        //        DT = ObjMain.GetData_DT(Inv_Qry3);
        //        grdInventoryView.DataSource = DT;
        //        grdInventoryView.DataBind();



        //    }

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



        //        //string Inv_Qry3 = "select * from " + BranchAlias + ".inventory as I join  " + BranchAlias + ".inventorycategories  as c ON I.Categoryid=c.categoryid where  I.InventoryName like '%" + txtSearchVal.Text.ToString().Trim() + "%' ";
        //        string Inv_Qry7 = "Select *,Round(UnitCost,3) as UCost,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.Description like '%" + txtSearchVal.Text.ToString().Trim() + "%' " + sActive + " group by I.inventoryid  ";

        //        DT = ObjMain.GetData_DT(Inv_Qry7);
        //        grdInventoryView.DataSource = DT;
        //        grdInventoryView.DataBind();

        //    }




        //    //if (cmbActive.SelectedIndex == 0)
        //    //{

        //    //    string InvenQuery = "select *,Round(UnitCost,3) as UCost,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  in (1,-1) " +
        //    //                     " group by i.inventoryid " +
        //    //                     " order by i.inventoryid;";
        //    //    DT = ObjCloudMain.GetData_DT(InvenQuery);

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

        //    //}
        //    //else if (cmbActive.SelectedIndex == 1)
        //    //{

        //    //    string InvenQuery = "select *,Round(UnitCost,3) as UCost,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  in (0) " +
        //    //                    " group by i.inventoryid " +
        //    //                    " order by i.inventoryid;";
        //    //    DT = ObjCloudMain.GetData_DT(InvenQuery);

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

        //}
        protected void cmbBranches_SelectedIndexChanged(object sender, EventArgs e)
        {
            // XSS Attack Prevention 
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "CloseModalInventoryAdjustList();", true);

            if (cmbBranches.SelectedIndex == 0)
            {
                Response.Write("Inventory.aspx");
            }
            else
            {
                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;
                }

                if (cmbBranches.SelectedIndex == 1)
                {

                    BranchFullName =cmbBranches.SelectedItem.Text;    // This will Return Branch FullName 
                    Cmb_BranchName = ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), BranchFullName);
                    BranchAlias = 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);
                    BranchAlias = Cmb_BranchName;
                    

                }

                if (DtLicense.Rows.Count > 0)
                {

                    L_Inventory = DtLicense.Rows[0]["INVENTORY"].ToString();
                    Session["L_Inventory"] = L_Inventory;
                }

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



                        btnAdjustStockSubmit.Enabled = true;
                        btnSave.Enabled = true;
                        BranchAlias = Cmb_BranchName;
                        LoadInventoryview(BranchAlias);

                    }
                    else
                    {
                        Response.Redirect("DeniedPage.aspx");
                    }


                }
                else
                {
                    if (Session["Write_Acess"].ToString() == "N")
                    {
                        btnAdjustStockSubmit.Enabled = false;
                        btnSave.Enabled = false;
                        BranchAlias = Cmb_BranchName;
                        LoadInventoryview(BranchAlias);
                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ShowModalInventoryAdjustList();", true);

                    }
                    else
                    {
                        btnAdjustStockSubmit.Enabled = true;
                        btnSave.Enabled = true;
                        BranchAlias = Cmb_BranchName;
                        LoadInventoryview(BranchAlias);

                        ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ShowModalInventoryAdjustList();", true);

                    }


                }
            }

            UPDATEBRANCH(BranchAlias);

        }


        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 OnSorting(object sender, GridViewSortEventArgs e)
        {
            this.LoadInventoryview(e.SortExpression);
        }

        protected void grdInventoryView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            // XSS Attack Prevention     
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ShowModalInventoryAdjustList();", true);
            if (cmbSearch.SelectedIndex == 0)
            {


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




                }

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

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




                }



            }

            else if (cmbSearch.SelectedIndex == 2)
            {

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

                }



            }

            else if (cmbSearch.SelectedIndex == 3)
            {

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

                }



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

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

                }



            }


            else if (cmbSearch.SelectedIndex == 5)
            {

                if (cmbBranches.Visible == false)
                {

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


                    //grdInventoryView.PageIndex = e.NewPageIndex;
                    ////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 *,Round(UnitCost,3) as UCost,sum(pquantity-(CutQuantity+RetailQty))as OnHandICA from " + Session["Branch_HQ"].ToString() + ".inventory as I " +
                    //                " join " + Session["Branch_HQ"].ToString() + ".inventorycategories  as c ON I.Categoryid=c.categoryid " +
                    //                " join " + Session["Branch_HQ"].ToString() + ".inventorycostaverage ic on ic.inventoryid=i.inventoryid where c.Categoryid=" + cmbCategory.SelectedItem.Value + " " + sActive + " group by I.inventoryid";
                    //DT = ObjMain.GetData_DT(Inv_Qry5);
                    //grdInventoryView.DataSource = DT;
                    //grdInventoryView.DataBind();
                    //txtSearchVal.Text = "";
                }
                else
                {
                    if (chkActiveonly.Checked == true)
                    {
                        sActive = " and I.active <> 0";
                    }
                    else
                    {
                        sActive = " and I.active = 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

                    grdInventoryView.PageIndex = e.NewPageIndex;

                    //string Inv_Qry5 = " Select *,Round(UnitCost,3) as UCost,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 c.Categoryid=" + cmbCategory.SelectedItem.Value + " " + sActive + " group by I.inventoryid";
                    //DT = ObjMain.GetData_DT(Inv_Qry5);
                    //grdInventoryView.DataSource = DT;
                    //grdInventoryView.DataBind();
                    //txtSearchVal.Text = "";


                }


            }


            if (cmbSearch.SelectedIndex == 6)
            {
                string group1Value = "group1";
                grdInventoryView.PageIndex = e.NewPageIndex;
                //LoadGroupDetail(group1Value,);


            }
            else if (cmbSearch.SelectedIndex == 7)
            {
                string group2Value = "group2";
                grdInventoryView.PageIndex = e.NewPageIndex;
                //LoadGroupsList(group2Value);
            }
            else if (cmbSearch.SelectedIndex == 8)
            {
                string group3Value = "group3";
                grdInventoryView.PageIndex = e.NewPageIndex;
                //LoadGroupsList(group3Value);
            }
            else if (cmbSearch.SelectedIndex == 9)
            {
                string group4Value = "group4";
                grdInventoryView.PageIndex = e.NewPageIndex;
                //LoadGroupsList(group4Value);
            }
            else if (cmbSearch.SelectedIndex == 10)
            {
                string group5Value = "group5";
                grdInventoryView.PageIndex = e.NewPageIndex;
                //LoadGroupsList(group5Value);
            }


            if (cmbSearch.SelectedIndex == 11)
            {

                #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_Qry3 = "select * from " + BranchAlias + ".inventory as I join  " + BranchAlias + ".inventorycategories  as c ON I.Categoryid=c.categoryid where  I.InventoryName like '%" + txtSearchVal.Text.ToString().Trim() + "%' ";
                string Inv_Qry7 = "Select *,Round(UnitCost,3) as UCost,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.Description like CONCAT('%',@SearchVal,'%')    " + sActive + " group by I.inventoryid  ";

                string command = string.Format(Inv_Qry7, BranchAlias);
                MySqlParameter[] parameters =
                   {
                     new MySqlParameter("@SearchVal", Microsoft.Security.Application.Encoder.HtmlEncode(txtSearchVal.Text.ToString().Trim())),

                    };

                DT = ObjMain.NewGetData_DT(command, parameters);


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

            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ShowModalInventoryAdjustList();", true);
        }

        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.GetBranchOnSuperAdmin(Session["Branch_HQ"].ToString(), Session["UserId"].ToString());
            DtNormalUser = ObjUserBL.GetBranchOnSuperAdminWithHQ8(Session["Branch_HQ"].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");
            }
        }
        
        //private string SortDirection
        //{
        //    get { return ViewState["SortDirection"] != null ? ViewState["SortDirection"].ToString() : "ASC"; }
        //    set { ViewState["SortDirection"] = value; }
        //}
        public void LoadInventoryview(string branch)
        {

            if (chkActiveonly.Checked == true)
            {
                sActive = "  I.active <> 0";
            }
            else
            {
                sActive = " I.active = 0";
            }
            string InvenQuery = " select *,Round(UnitCost,3) as UCost,sum(pquantity-(CutQuantity+RetailQty))as OnHandICA, ''  as Qty  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  " + sActive + " " +
                                " group by i.inventoryid " +
                                " order by i.inventoryid;";
            string command = string.Format(InvenQuery, branch);
            DT = ObjCloudMain.GetData_DT(command);
            grdInventoryView.DataSource = DT;
            grdInventoryView.DataBind();

             

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

            }
            #endregion

            txtSearchVal.Text = "";

            FAdjDt = (DataTable)Session["QtyTable"];        //session value assign to Final datatable for Submit
            if (AdjDt.Rows.Count==0)
            {
                AdjDt.Columns.Add(new System.Data.DataColumn("SNo", typeof(String)));
                AdjDt.Columns.Add(new System.Data.DataColumn("InventoryID", typeof(String)));
                AdjDt.Columns.Add(new System.Data.DataColumn("Barcode", typeof(String)));
                AdjDt.Columns.Add(new System.Data.DataColumn("Qty", typeof(String)));
                AdjDt.Columns.Add(new System.Data.DataColumn("AdjCost", typeof(String)));
                AdjDt.Columns.Add(new System.Data.DataColumn("CFlag", typeof(String)));
                AdjDt.Columns.Add(new System.Data.DataColumn("CAction", typeof(String)));
                AdjDt.Columns.Add(new System.Data.DataColumn("Flag", typeof(String)));
                AdjDt.Columns.Add(new System.Data.DataColumn("Action", typeof(String)));
            }

            DataRow dr;
            if (FAdjDt != null)
            {
                if (FAdjDt.Rows.Count > 0)
                {
                    foreach (DataRow row in FAdjDt.Rows)        // load previous page session values to current datatable
                    {
                        dr = AdjDt.NewRow();
                        dr[0] = row["SNo"].ToString();
                        dr[1] = row["InventoryID"].ToString();
                        dr[2] = row["Barcode"].ToString();
                        dr[3] = row["Qty"].ToString();
                        dr[4] = row["AdjCost"].ToString();
                        dr[5] = row["CFlag"].ToString();
                        dr[6] = row["CAction"].ToString();
                        dr[7] = row["Flag"].ToString();
                        dr[8] = row["Action"].ToString();
                        AdjDt.Rows.Add(dr);
                        iSno = Convert.ToInt32(dr[0]);
                    }
                }
            }
            
            foreach (GridViewRow row in grdInventoryView.Rows)    //append current page data to datatable
                {
                    Label InvID = (Label)row.FindControl("lblInventoryID");
                    Label Barcode = (Label)row.FindControl("lblBarCode");
                    TextBox Qty5 = row.FindControl("txtAdjust5") as TextBox;
                    TextBox AdjCost = (TextBox)row.FindControl("txtUnitCost");
                    CheckBox chk1 = (CheckBox)row.FindControl("chkFixedCost");
                    CheckBox chk = (CheckBox)row.FindControl("chkSelect");

                    int index = Qty5.Text.IndexOf(',');
                    string output = index > 0 ? Qty5.Text.Substring(0, index).Trim() : Qty5.Text;

                    int index1 = AdjCost.Text.IndexOf(',');
                    string output1 = index1 > 0 ? AdjCost.Text.Substring(0, index1).Trim() : AdjCost.Text;

                if ((output != string.Empty && output != "0") || chk1.Checked == true)
                    {
                        iSno = iSno + 1;
                        sSno = Convert.ToString(iSno);
                        dr = AdjDt.NewRow();
                        dr[0] = sSno;
                        dr[1] = InvID.Text;
                        dr[2] = Barcode.Text;
                        if (Qty5.Text == "")
                        {
                            dr[3] = 0;
                        }
                        else
                        {
                            dr[3] = output;
                        }
                        //dr[4] = AdjCost.Text;
                          dr[4] = output1;
                    if (chk1.Checked == true)
                        {
                            dr[3] = 0;
                            dr[5] = "1";
                            dr[6] = "FixedCost";
                        }
                        else
                        {
                            dr[5] = "0";
                            dr[6] = "UnitCost";
                        }
                        if (chk.Checked == true)
                        {
                            dr[7] = "1";
                            dr[8] = "Wastage";
                        }
                        else
                        {
                            dr[7] = "0";
                            dr[8] = "Adjust";
                        }

                        AdjDt.Rows.Add(dr);
                    }
                }
            Session["QtyTable"] = AdjDt;
            DataTable DT101 = new DataTable();
            DT101 = (DataTable)Session["QtyTable"];
            GrdInvAdjView.DataSource = DT101;
            GrdInvAdjView.DataBind();
            LoadInventoryview(BranchAlias);

            if (AdjDt.Rows.Count > 0)
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Items Added to ADJUST Section ');location.href='Inventory.aspx' ", true);
            }


        }


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

            }
            #endregion



            DataTable dt1 = (DataTable)Session["QtyTable"];
            // DataTable dt = new DataTable();
            if (dt1.Rows.Count > 0)
            {
                dt1.Rows[e.RowIndex].Delete();
                dt1.AcceptChanges();
                GrdInvAdjView.DataSource = dt1;
                GrdInvAdjView.DataBind();
                txtSearchVal.Text = "";
            }
            LoadInventoryview(BranchAlias);
        }

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

                #endregion



            }




            // HQ Validation For Loading Branch Name : Dropdown  Added Karthik  On 02-12-21 
            #region  HQ Validation Starts Here ...  
            cd_BranchAlias = ActiveCallvalue;
            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);
                UPDATEBRANCH(Cmb_BranchName);

            }
            #endregion  



            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_Inventory = DtLicense.Rows[0]["INVENTORY"].ToString();
                Session["L_Inventory"] = L_Inventory;


            }
            if ((Session["L_Inventory"] == null) || Session["L_Inventory"].ToString() == "N" || Session["Page_Acess"].ToString() == "N")
            {
                if (cmbBranches.SelectedItem.Text == "HQ")
                {
                    btnAdjustStockSubmit.Enabled = true;
                    btnSave.Enabled = true;
                    BranchAlias = Session["Branch_HQ"].ToString();
                    LoadInventoryview(BranchAlias);
                }
                else
                {
                    Response.Redirect("DeniedPage.aspx");
                }

            }
            else
            {

                if (Session["Write_Acess"].ToString() == "N")
                {

                    btnAdjustStockSubmit.Enabled = false;
                    btnSave.Enabled = false;
                    BranchAlias = Cmb_BranchName;
                    LoadInventoryview(BranchAlias);
                    UPDATEBRANCH(Cmb_BranchName);
                }
                else
                {
                    btnAdjustStockSubmit.Enabled = true;
                    btnSave.Enabled = true;
                    BranchAlias = Cmb_BranchName;

                   LoadInventoryview(BranchAlias);
                   UPDATEBRANCH(Cmb_BranchName);
                }




            }

        }







        public void btnAdjustStockSubmit_Click(object sender, System.EventArgs e)
        {
            // XSS Attack Prevention 
            if (cmbBranches.Visible == false)
            {
                BranchAlias = 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

            }

            if (GrdInvAdjView.Rows.Count > 0)
            {

                foreach (GridViewRow row in GrdInvAdjView.Rows)
                {
                    Label SNo = (Label)row.FindControl("lblSNo");
                    Label InvID = (Label)row.FindControl("lblInvID");
                    Label Barcode = (Label)row.FindControl("lblBarcode");
                    Label Qty = (Label)row.FindControl("lblQty");
                    Label AdjCost = (Label)row.FindControl("lblAdjCost");
                    Label Flagvalue1 = (Label)row.FindControl("lblCFlag");
                    Label Flagvalue = (Label)row.FindControl("lblFlag");

                    JSno = SNo.Text;
                    JInvenID = InvID.Text;
                    JBarcode = Barcode.Text;
                    JQty = Qty.Text;
                    JFlagValue = Flagvalue.Text;

                    // JinventoryNane = ObjMain.ExecuteScalar();

                    string QueryK = "select inventoryname from {0}.inventory where inventoryid=@inventoryid ";
                    string commandK = string.Format(QueryK, BranchAlias);
                    MySqlParameter[] parametersK =
                     {
                      new MySqlParameter("@inventoryid",JInvenID),
                     };

                    JinventoryNane = ObjMain.NewExecuteScalar(commandK, parametersK);


                    //Jinven_Description = ObjMain.ExecuteScalar("select description from " + BranchAlias + ".inventory where inventoryid=" + JInvenID + " ");  Existing code

                    string QueryS = "select description from {0}.inventory where inventoryid=@inventoryid ";
                    string commandS = string.Format(QueryS, BranchAlias);
                    MySqlParameter[] parametersS =
                     {
                      new MySqlParameter("@inventoryid",JInvenID),
                     };

                    Jinven_Description = ObjMain.NewExecuteScalar(commandS, parametersS);

                    if (Flagvalue.Text == "1")  // This will Handles wastage
                    {

                        Wastage();

                    }
                    else if (Flagvalue.Text == "0")  //  Inventory Adjust 
                    {

                        //Get Current Cost from InventoryCostAverage table
                        //DTQry = ObjSel.CheckUnitCost(BranchAlias, InvID.Text);
                        //if (DTQry.Rows.Count != 0)
                        //{
                        //    AdjInvCost = DTQry.Rows[0]["UnitCost"].ToString();
                        //}
                        //else
                        //{
                        //    AdjInvCost = "0";
                        //}

                        //nid added for Costing on 22-Sep-2020
                        string sQryCost = "SELECT InventoryID,PQuantity,PAmount,(CutQuantity+RetailQty) as CutQuantity,UnitCost,(CutAmount+RetailAmount) as CutAmount" +
                                         " From {0}.inventorycostaverage Where InventoryID=@InventoryID ";

                        string commandA = string.Format(sQryCost, BranchAlias);

                        MySqlParameter[] parameters =
                         {
                         new MySqlParameter("@InventoryID",JInvenID),
                        };
                        DTCosting = ObjMain.NewGetData_DT(commandA, parameters);
                        //string val = dt.Rows[0]["FieldName"].ToString();
                        vQuantity = Convert.ToDouble(Qty.Text);
                        vUnitCost = Convert.ToDouble(AdjCost.Text);
                        dPQty = Convert.ToDouble(DTCosting.Rows[0]["PQuantity"]);
                        dPAmount = Convert.ToDouble(DTCosting.Rows[0]["PAmount"]);
                        dCutQty = Convert.ToDouble(DTCosting.Rows[0]["CutQuantity"]);
                        dUnitCost = Convert.ToDouble(DTCosting.Rows[0]["UnitCost"]);
                        if (vQuantity > 0)
                        {
                            dNPQty = dPQty + vQuantity;
                            if (vQuantity != 0)
                            {
                                dPAmount = dPAmount + vQuantity * vUnitCost;
                            }
                            if (dNPQty - dCutQty != 0)
                            {
                                dUnitCost = Math.Abs((((dPQty - dCutQty) * dUnitCost) + (vQuantity * vUnitCost)) / ((dPQty - dCutQty) + vQuantity));

                            }
                            //Update InventoryCostAverage table 

                            // Prevents SQL Injections 
                            // Parameterized Approach 

                          string  MCmd = "Update {0}.inventorycostaverage Set PQuantity=@PQuantity ,PAmount=@PAmount,UnitCost=@UnitCost Where InventoryID=@InventoryID ";

                            string commandM = string.Format(MCmd, BranchAlias);
                            MySqlParameter[] parametersM =
                            {
                             new MySqlParameter("@PQuantity",dNPQty),
                             new MySqlParameter("@PAmount",dPAmount),
                             new MySqlParameter("@UnitCost",dUnitCost),
                             new MySqlParameter("@InventoryID",InvID.Text),

                            };

                            K = ObjCloudMain.ExecuteQuery(commandM, parametersM);
                        }
                        else
                        {
                            dNPQty = dPQty + vQuantity;
                            if (Flagvalue1.Text != "0")
                            {
                                dPAmount = dPQty * vUnitCost;
                                dCutAmount = dCutQty * vUnitCost;
                            }
                            else
                            {
                                if (vUnitCost != 0)
                                {
                                    dPAmount = dPAmount + vQuantity * vUnitCost;
                                }
                            }
                            if (Flagvalue1.Text == "0")
                            {
                                if (dNPQty - dCutQty != 0)
                                {
                                    dUnitCost = Math.Abs((((dPQty - dCutQty) * dUnitCost) + (vQuantity * vUnitCost)) / ((dPQty - dCutQty) + vQuantity));

                                }

                            }
                            else
                            {
                                dUnitCost = vUnitCost;
                            }
                            //Update InventoryCostAverage table 
                           string LCmd = "Update {0}.inventorycostaverage Set PQuantity=@PQuantity ,PAmount=@PAmount,UnitCost=@UnitCost Where InventoryID=@InventoryID ";
                            string commandL = string.Format(LCmd, BranchAlias);

                            MySqlParameter[] parametersL =
                             {
                             new MySqlParameter("@PQuantity",dNPQty),
                             new MySqlParameter("@PAmount",dPAmount),
                             new MySqlParameter("@UnitCost",dUnitCost),
                             new MySqlParameter("@InventoryID",InvID.Text),

                             };

                            K = ObjMain.ExecuteQuery(commandL, parametersL);
                        }
                    }

                    //Insert Adjust details into InventoryAdjust table
                  string  PCmd = "Insert INTO {0}.inventoryadjust(InventoryID, AdjustQuantity, UnitCost, DateAdjusted, EmployeeID)values(@InventoryID,@AdjustQuantity ,@UnitCost,@DateAdjusted,@EmployeeID) ";
                    string commandP = string.Format(PCmd, BranchAlias);

                    MySqlParameter[] parametersP =
                            {
                             new MySqlParameter("@InventoryID",InvID.Text),
                             new MySqlParameter("@AdjustQuantity",vQuantity),
                             new MySqlParameter("@UnitCost",vUnitCost),
                             new MySqlParameter("@DateAdjusted",Curr_DateOnly),
                             new MySqlParameter("@EmployeeID",1),
                             };

                    K = ObjMain.ExecuteQuery(commandP, parametersP);

                    ////Update InventoryCostAverage table 
                    //sCmd = "Update " + BranchAlias + ".inventorycostaverage Set PQuantity=PQuantity+" + Qty.Text + " Where InventoryID=" + InvID.Text + " ";
                    //K = ObjCloudMain.ExecuteNonQuery(sCmd);
                }

                string queryQ = "Select invadjID from {0}.invadjDetail where invadjID=@invadjID  ";
                string commandQ = string.Format(queryQ, BranchAlias);

                MySqlParameter[] parametersQ =
                    {
                     new MySqlParameter("@invadjID",InAdjId),

                    };

                ChkAdjTal = ObjMain.NewExecuteScalar(commandQ, parametersQ);

                if (ChkAdjTal != "")
                {
                    //string Wastaage="'Wastage\spoiled'";

                    // Prevents SQL Injections 
                    // Parameterized Approach 

                    string Wastaage = "Wastage";
                    // Insert Master data to invadjmaster
                   string  cmdR = "Insert into   {0}.invadjmaster(invadjID,invadjDate,invadjType,invadjsalesdatefrom,invadjsalesdateto,categoryname,EmployeeID,status,invadjstatus,Remarks)"
                    + "values(@invadjID,@invadjDate,@invadjType,@invadjsalesdatefrom ,@invadjsalesdateto,@categoryname,@EmployeeID,@status,@invadjstatus,@Remarks )";
                    string commandR = string.Format(cmdR, BranchAlias);
                    MySqlParameter[] parametersR =
                    {
                     new MySqlParameter("@invadjID",InAdjId),
                     new MySqlParameter("@invadjDate",Curr_DateOnly),
                     new MySqlParameter("@invadjType","Product"),
                     new MySqlParameter("@invadjsalesdatefrom",Curr_DateOnly),
                     new MySqlParameter("@invadjsalesdateto",Curr_DateOnly),
                     new MySqlParameter("@categoryname","None"),
                     new MySqlParameter("@EmployeeID","1"),
                     new MySqlParameter("@status","1"),
                     new MySqlParameter("@invadjstatus","Wastage"),
                     new MySqlParameter("@Remarks",Wastaage),
                     };
                    S = ObjMain.ExecuteQuery(commandR, parametersR);

                }

                Session.Remove("QtyTable");
                AdjDt.Clear();
                FAdjDt.Clear();
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Inventory Stock Adjusted Successfully ');location.href='Inventory.aspx' ", true);

            }
            else
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Inventory Items Not Added to Adjust ');location.href='Inventory.aspx' ", true);
            }

        }


        // Wastage  Functions  

        /// <summary>
        /// This function for Wastage 
        /// </summary>
        public void Wastage()
        {
            // XSS Attack Prevention 
            InAdjId = ObjSel.GetMax_InvAdjID(BranchAlias);

            // Insert Details 
            NAdjqty = Convert.ToDecimal(Convert.ToInt32(JQty) * -1);

            Jcmd = "Insert into {0}.invadjDetail(invadjID,inventoryID,barcode,inventoryName,Description,soldqty,adjqty,printstatus,UnitCost)"
            + "values (@invadjID,@inventoryID ,@barcode ,@inventoryName ,@Description,@soldqty,@adjqty ,@printstatus,@UnitCost)";

            string command6 = string.Format(Jcmd, BranchAlias);

            MySqlParameter[] parameters6 =
                  {
                     new MySqlParameter("@invadjID",InAdjId),
                     new MySqlParameter("@inventoryID",JInvenID),
                     new MySqlParameter("@barcode",JBarcode),
                     new MySqlParameter("@inventoryName",JinventoryNane),
                     new MySqlParameter("@Description",Jinven_Description),
                     new MySqlParameter("@soldqty",0),
                     new MySqlParameter("@adjqty",NAdjqty),
                     new MySqlParameter("@printstatus",0),
                     new MySqlParameter("@UnitCost",0.0000),


                    };
            K = ObjMain.ExecuteQuery(command6, parameters6);

            // Update InventoryCostAverage 


            string QueryB = "select pquantity from {0}.inventorycostaverage where inventoryid = @inventoryid ";
            string command7 = string.Format(QueryB, BranchAlias);
            MySqlParameter[] parameters7 =
             {
                     new MySqlParameter("@inventoryid", JInvenID),

                    };
            PQOH = Convert.ToDecimal(ObjMain.NewExecuteScalar(command7, parameters7));
            //  PQOH = Convert.ToDecimal(ObjMain.ExecuteScalar("  "));  Existing Code 
            QOH = PQOH + NAdjqty;
            Jcmd1 = "Update {0}.InventoryCostAverage set PQuantity =@PQuantity where inventoryID = @inventoryID ";
            // Prevents SQL Injection 

            string command8 = string.Format(Jcmd1, BranchAlias);
            MySqlParameter[] parameters8 =
                  {
                     new MySqlParameter("@PQuantity",QOH),
                     new MySqlParameter("@inventoryID",JInvenID),
                    };

            L = ObjMain.ExecuteQuery(command8, parameters8);

            // Inventory Adjust 

            // Get Unit Cost : Value  From InventoryCostaverage 
            //  jUnitCost = Convert.ToDecimal(ObjMain.ExecuteScalar("select  Unitcost from  " + BranchAlias + ".inventorycostaverage where Inventoryid=" + JInvenID + " ")); Exiting COde 

            string QueryC = "select  Unitcost from  {0}.inventorycostaverage where Inventoryid=@Inventoryid ";
            string Command9 = string.Format(QueryC, BranchAlias);
            MySqlParameter[] parameters9 =
                  {
                     new MySqlParameter("@Inventoryid", JInvenID),
                  };

            jUnitCost = Convert.ToDecimal(ObjMain.NewExecuteScalar(Command9, parameters9));
            Jcmd2 = "Insert into {0}.InventoryAdjust(inventoryid,adjustquantity,unitcost,notes,dateadjusted,employeeid)values(@inventoryid, @adjustquantity,@unitcost, @notes,@dateadjusted, @employeeid )";
            string command10 = string.Format(Jcmd2, BranchAlias);

            MySqlParameter[] parameters10 =
                 {
                     new MySqlParameter("@inventoryid",JInvenID),
                     new MySqlParameter("@adjustquantity",NAdjqty),
                     new MySqlParameter("@unitcost",jUnitCost),
                     new MySqlParameter("@notes",string.Empty),
                     new MySqlParameter("@dateadjusted",Microsoft.Security.Application.Encoder.HtmlEncode(Curr_DateOnly)),
                     new MySqlParameter("@employeeid","1"),
                  };
            U = ObjMain.ExecuteQuery(command10, parameters10);

        }


    }
}