using CLS_BL;
using CLS_DL;
using CLS_PL;
using CsvHelper;
using DocumentFormat.OpenXml.Math;
using iTextSharp.text;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
using MySql.Data;
using MySql.Data.MySqlClient;
using Newtonsoft;
using Newtonsoft.Json;
using Org.BouncyCastle.Asn1.Ocsp;
using RestSharp;
using SunWeb.Model;
using SUNWEB.App_Code.CLS_PL;
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Configuration;
using System.Data;
using System.Data.OleDb;
using System.Drawing;
using System.Drawing.Printing;
using System.Drawing.Text;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Web.Script.Serialization;
using System.Web.Services;
using System.Web.UI;
using System.Web.UI.DataVisualization.Charting;
using System.Web.UI.WebControls;
using static SUNWEB.InteractiveDashboard;

namespace SUNWEB
{
    public partial class InventoryMaster : System.Web.UI.Page
    {
        Random rndGenerator = new Random();
        BL_ErrorLog ObjError = new BL_ErrorLog();
        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;
        Int32 Z = 0;
        Int32 R = 0;
        Int32 P = 0;
        Int32 Q = 0;
        Int32 T = 0;
        string TS = "";
        Int32 Ln = 0;
        Int32 InsertMultiBarcode;
        Int32 InsertInventoryPackage;
        Int32 DeleteExistingSlave;
        Int32 DeleteExistingPackageItem;
        Int32 DeletePackageItem;
        Int32 DeleteSlave;
        Int32 ImportMSBarcode;
        Int32 DeleteMSBarcode;
        Int32 iUpdatePriceCaption;
        Int32 iInsertWebOrderPromo; //JOHN added on 16-Aug-2021
        Int32 IDeleteWebOrderPromo; //JOhn added on 16-Aug-2021
        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 DTTGroups = new DataTable();
        DataTable DTPrinterList = new DataTable();
        DataTable DTImageResult = new DataTable();
        DataTable DtTimeRead = new DataTable();
        DataTable DtRead = new DataTable();

        DataTable DtPriceFlag = new DataTable();
        DataTable DtinventoryCnt = new DataTable();

        DataTable FPckDt = new DataTable();

        // Access variables
        string PortalTypeId = string.Empty;
        string ActiveCallvalue = string.Empty;
        string Datapath = string.Empty;
        string cd_BranchAlias = string.Empty;
        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 ChkValue = string.Empty;
        // string BranchAlias = "saffron1";
        string BranchAlias = string.Empty;
        string PSett;
        string CatValue;
        string Grp1Value;
        string Grp2Value;
        string Grp3Value;
        string Grp4Value;
        string Grp5Value;

        string GroupID1 = string.Empty;
        string GroupID2 = string.Empty;
        string GroupID3 = string.Empty;
        string GroupID4 = string.Empty;
        string GroupID5 = 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;

        private string SearchTxt_G1;
        private string SearchTxt_G2;
        private string SearchTxt_G3;
        private string SearchTxt_G4;
        private string SearchTxt_G5;
        // 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;
        string CateVl;
        string CateValue;

        //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 GActive = string.Empty;
        string sSpicy = string.Empty;   // John added on 07-Aug-2020
        string sChef = string.Empty;    // John added on 07-Aug-2020
        string sBeef = string.Empty;    // John added on 07-Aug-2020
        string sChicken = string.Empty; // John added on 07-Aug-2020
        string sPork = string.Empty;    // John added on 07-Aug-2020
        string sTakeAway = string.Empty; //john added on 26-Nov-2020
        string sAvailable = string.Empty;
        string sShowItem = string.Empty;
        string sNodiscount = string.Empty;
        string sProductRelationMain = string.Empty;         //john added on 18-Sept-2024
        string sProductRelationNotInculde = string.Empty;   //john added on 18-Sept-2024
        string sGWebPriceCaptionID = string.Empty;  //JOHN ADDED ON 13-JAN-2021
        string RWebPriceCaptionID = string.Empty; //JOHN ADDED ON 13-JAN-2021

        string Notes = string.Empty;
        string GReorderLevel = string.Empty;
        string GMaximumLevel = string.Empty;
        string GSafetyLevel = string.Empty;
        string ImageVal = string.Empty;
        //for InventoryAdjust Process
        string AdjInvCost = string.Empty;

        //for check barcode function
        string sChkBarcode = string.Empty;

        DataTable AdjDt = new DataTable();
        DataTable fFAdjDt = new DataTable();
        StringBuilder sb = new StringBuilder();
        string sSno = string.Empty;
        int iSno = 0;
        string sCmd = string.Empty;

        // 

        string ServiceC_TaxName;
        decimal Service_Taxval;
        string Service_AddOn;
        string Service_TaxOn;
        // Gst 
        string Gst_TaxName;
        decimal Gst_TaxVal;
        string Gst_AddOn;
        string Gst_TaxOn;
        // Tax3
        string Tax3_TaxName;
        decimal Tax3_TaxVal;
        string Tax3_AddOn;
        string Tax3_TaxOn;
        // Tax4 
        string Tax4_TaxName;
        decimal Tax4_TaxVal;
        string Tax4_AddOn;
        string Tax4_TaxOn;
        // Tax5
        string Tax5_TaxName;
        decimal Tax5_TaxVal;
        string Tax5_AddOn;
        string Tax5_TaxOn;
        // Tax6
        string Tax6_TaxName;
        decimal Tax6_TaxVal;
        string Tax6_AddOn;
        string Tax6_TaxOn;
        string TaxId = string.Empty;
        string HQ = string.Empty;
        string Cm_id = string.Empty;
        string ISHQ = string.Empty;
        string RUnitids = string.Empty;
        string ChkInvenId = string.Empty;
        decimal OldPQty = 0;
        decimal OldPAmount = 0;
        decimal NewPAmount = 0;
        decimal NewPQty = 0;
        decimal NewUnitCost = 0;
        decimal OldUnitCost = 0;
        decimal VQty = 0;
        decimal VUnitCost = 0;
        decimal VAvgCost = 0;
        decimal JAmount = 0;
        decimal CutQty = 0;
        string RBranchid = string.Empty;
        string Branchid = string.Empty;

        string sDeleteMBarcode = string.Empty;
        string IISAppName = string.Empty;
        string SPath = string.Empty;
        string ChkImagePath = string.Empty;
        string NotAvailable = string.Empty;
        string sActive = string.Empty;
        string RPrintno1, RPrintno2, RPrintno3, RPrintno4, RPrintno5, RPrintno6, RPrintno7, RPrintno8,
               RPrintno9, RPrintno10, RPrintno11, RPrintno12, RPrintno13, RPrintno14, RPrintno15,
               RPrintno16, RPrintno17, RPrintno18, RPrintno19;
        string Printno1, Printno2, Printno3, Printno4, Printno5, Printno6, Printno7, Printno8, Printno9,
               Printno10, Printno11, Printno12, Printno13, Printno14, Printno15, Printno16, Printno17, Printno18, Printno19;
        string PrinterName1, PrinterName2, PrinterName3, PrinterName4, PrinterName5, PrinterName6, PrinterName7, PrinterName8,
               PrinterName9, PrinterName10, PrinterName11, PrinterName12, PrinterName13, PrinterName14, PrinterName15,
               PrinterName16, PrinterName17, PrinterName18, PrinterName19;
        protected string ActiveTab { get; private set; }//for Nav Bar
        string FileID = string.Empty;
        string sPromo = string.Empty;

        // Added On 02-12-2021
        string ReadHQ = string.Empty;
        string RTakeAwayValue = string.Empty;
        string NoDiscount = string.Empty;
        // Inventory Costaverage : Obj
        PLINVENTORYCOSTAVERAGE ICObj = new PLINVENTORYCOSTAVERAGE();


        protected void Page_Load(object sender, EventArgs e)
        {

            AlertA.Visible = false;

            txtSearchVal.CssClass = "form-control";
            Fileploadid.CssClass = "form-control";
            if (Session["UserName"] == null)
            {
                Response.Redirect("Login.aspx");
            }
            PID = "13";          // This is for Inventory Master's  PageAccess
            if (((Convert.ToBoolean(Session["IsSuperAdmin"])) == true) && (Session["PortalTypeId"].ToString() == "") && ((Convert.ToBoolean(Session["IsMultiBranch"])) == true))
            {
                if (!IsPostBack)
                {
                    LoadBranchesOnID();   // Modified On 07-03-20 : KARTHI
                    //LoadBranchName4SuperAdmin();
                    string QueryCal = "select ActiveValue from portaldb.usermaster  where Userid=" + Session["UserId"].ToString() + " ";
                    ActiveCallvalue = ObjMain.ExecuteScalar(QueryCal);
                    if (ActiveCallvalue != " " || ActiveCallvalue != "Select Branch")
                    {
                        //btnUpdateInv.Attributes.Add("onclick", "return false;");
                        //btnSubmit.Attributes.Add("onclick", "return false;");
                        //ClearCacheItems();
                        //ClearCache();

                        ActiveCall();
                      




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

                #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 (!IsPostBack)
                {

                    txtEffectiveDt.Text = Curr_DateOnly;
                    LoadGrp1(BranchAlias);
                    LoadGrp2(BranchAlias);
                    LoadGrp3(BranchAlias);
                    LoadGrp4(BranchAlias);
                    LoadGrp5(BranchAlias);
                    LoadCategoryList(BranchAlias);
                    LoadTaxLables();


                    btnUpdateInv.Visible = false;
                    btnDelete.Visible = false;
                    txtReadInventroyId.Enabled = false;
                    txtReadInventroyId.CssClass = "form-control";
                    //John added on 31-Oct-2020 PriceCaption
                    //lblPrice1.InnerText = "Price 1 ( " + ObjSel.GetPriceCaption(BranchAlias, 1) + " )";
                    //txtCaptionPrice1.Text = ObjSel.GetPriceCaption(BranchAlias, 1);
                    //lblPrice2.InnerText = "Price 2 ( " + ObjSel.GetPriceCaption(BranchAlias, 2) + " )";
                    //txtCaptionPrice2.Text = ObjSel.GetPriceCaption(BranchAlias, 2);
                    //lblPrice3.InnerText = "Price 3 ( " + ObjSel.GetPriceCaption(BranchAlias, 3) + " )";
                    //txtCaptionPrice3.Text = ObjSel.GetPriceCaption(BranchAlias, 3);
                    //lblPrice4.InnerText = "Price 4 ( " + ObjSel.GetPriceCaption(BranchAlias, 4) + " )";
                    //txtCaptionPrice4.Text = ObjSel.GetPriceCaption(BranchAlias, 4);
                    lblPrice1.InnerText = "Price 1 ( " + ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "1") + " )";
                    txtCaptionPrice1.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "1");
                    lblPrice2.InnerText = "Price 2 ( " + ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "2") + " )";
                    txtCaptionPrice2.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "2");
                    lblPrice3.InnerText = "Price 3 ( " + ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "3") + " )";
                    txtCaptionPrice3.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "3");
                    lblPrice4.InnerText = "Price 4 ( " + ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "4") + " )";
                    txtCaptionPrice4.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "4");
                }
            }
            else if (((Convert.ToBoolean(Session["IsMultiBranch"])) == true) && (Session["PortalTypeId"].ToString() == ""))
            {
                if (!IsPostBack)
                {
                    LoadBranchesOnID();
                    ActiveCall();
                }
            }
            else if (((Session["PortalTypeId"].ToString() != "") || (Convert.ToBoolean(Session["IsSuperAdmin"])) == false) && ((Convert.ToBoolean(Session["IsMultiBranch"])) == false))
            {
                cmbBranches.Enabled = false;
                cmbBranches.Visible = false;
                Cm_id = ObjSel.GETcmid(Session["Cd_Id"].ToString());  // Get cm_id
                HQ = ObjSel.Get_HQ(Cm_id);     // Get the HQ Value
                Curr_BranchFullName = ObjSel.GetBranchFullName(HQ, Session["Branch_HQ"].ToString());
                lblBranchAliasName.ForeColor = System.Drawing.Color.DodgerBlue;
                lblBranchAliasName.Text = "&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 (Session["Write_Acess"].ToString() == "N")
                {
                    Response.Redirect("DeniedPage.aspx");
                }
                else
                {
                    if (!IsPostBack)
                    {
                        if (Session["Isdowld_Acess"].ToString() == "N")
                        {
                            // btnExcel.Enabled = false;
                            Response.Write(@"<script language='javascript'>alert('No Access To download.')</script>");
                        }
                        else if (Session["Write_Acess"].ToString() == "N")
                        {
                            Response.Redirect("DeniedPage.aspx");
                        }
                        else
                        {
                            if (cmbBranches.Visible == false)
                            {
                                BranchAlias = Session["Branch_HQ"].ToString();
                                // Loading Parts : 
                                if (!IsPostBack)
                                {

                                    txtEffectiveDt.Text = Curr_DateOnly;
                                    LoadGrp1(BranchAlias);
                                    LoadGrp2(BranchAlias);
                                    LoadGrp3(BranchAlias);
                                    LoadGrp4(BranchAlias);
                                    LoadGrp5(BranchAlias);
                                    LoadCategoryList(BranchAlias);
                                    LoadUnits(BranchAlias);
                                    LoadInventoryview();
                                  
                                    LoadPriceCaptionHeader(BranchAlias);
                                    LoadTaxLables();

                                    btnUpdateInv.Visible = false;
                                    btnDelete.Visible = false;
                                    txtReadInventroyId.Enabled = false;
                                    txtReadInventroyId.CssClass = "form-control";
                                    //John added on 31-Oct-2020 PriceCaption                                    
                                    //txtCaptionPrice1.Text = ObjSel.GetPriceCaption(BranchAlias, 1);
                                    //txtCaptionPrice2.Text = ObjSel.GetPriceCaption(BranchAlias, 2);
                                    //txtCaptionPrice3.Text = ObjSel.GetPriceCaption(BranchAlias, 3);
                                    //txtCaptionPrice4.Text = ObjSel.GetPriceCaption(BranchAlias, 4);

                                    //txtCaptionPrice1.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderID(BranchAlias), "1");
                                    //txtCaptionPrice2.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderID(BranchAlias), "2");
                                    //txtCaptionPrice3.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderID(BranchAlias), "3");
                                    //txtCaptionPrice4.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderID(BranchAlias), "4");
                                    lblPrice1.InnerText = "Price 1 ( " + ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "1") + " )";
                                    txtCaptionPrice1.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "1");
                                    lblPrice2.InnerText = "Price 2 ( " + ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "2") + " )";
                                    txtCaptionPrice2.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "2");
                                    lblPrice3.InnerText = "Price 3 ( " + ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "3") + " )";
                                    txtCaptionPrice3.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "3");
                                    lblPrice4.InnerText = "Price 4 ( " + ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "4") + " )";
                                    txtCaptionPrice4.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "4");
                                }
                            }
                        }
                    }
                }
            }
        }

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

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

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

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


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


                    }


                }


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

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

        }

        public void LoadBranchName()
        {
            DtNormalUser = ObjUserBL.GetBranchOnLoginValues8(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), Session["CM_ID"].ToString());
            if (DtNormalUser.Rows.Count > 0)
            {
                cmbBranches.DataSource = DtNormalUser;
                cmbBranches.DataTextField = "branchfullname";
                cmbBranches.DataValueField = "Branchid";
                cmbBranches.DataBind();
                cmbBranches.Items.Insert(0, "Select Branch");
            }
        }

        public void LoadBranchName4SuperAdmin()
        {

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

        }

        public void LoadGrp1(string db)
        {
            cmbGroup1.DataSource = ObjSel.Inv_Grp1List(db);
            cmbGroup1.DataValueField = "Groupid";
            cmbGroup1.DataTextField = "GroupName1";
            cmbGroup1.DataBind();
            cmbGroup1.Items.Insert(0, "Select");

        }

        public void LoadGrp2(string db)
        {
            cmbGroup2.DataSource = ObjSel.Inv_Grp2List(db);
            cmbGroup2.DataValueField = "Groupid";
            cmbGroup2.DataTextField = "GroupName2";
            cmbGroup2.DataBind();
            cmbGroup2.Items.Insert(0, "Select");

        }

        public void LoadGrp3(string db)
        {
            cmbGroup3.DataSource = ObjSel.Inv_Grp3List(db);
            cmbGroup3.DataValueField = "Groupid";
            cmbGroup3.DataTextField = "GroupName3";
            cmbGroup3.DataBind();
            cmbGroup3.Items.Insert(0, "Select");

        }

        public void LoadGrp4(string db)
        {
            cmbGroup4.DataSource = ObjSel.Inv_Grp4List(db);
            cmbGroup4.DataValueField = "Groupid";
            cmbGroup4.DataTextField = "GroupName4";
            cmbGroup4.DataBind();
            cmbGroup4.Items.Insert(0, "Select");
        }

        public void LoadGrp5(string db)
        {
            cmbGroup5.DataSource = ObjSel.Inv_Grp5List(db);
            cmbGroup5.DataValueField = "Groupid";
            cmbGroup5.DataTextField = "GroupName5";
            cmbGroup5.DataBind();
            cmbGroup5.Items.Insert(0, "Select");
        }

        public void LoadCategoryList(string db)
        {
            cmbCategoryName.DataSource = ObjSel.Inv_CategoryList(db);
            cmbCategoryName.DataTextField = "Description";
            cmbCategoryName.DataValueField = "CategoryID";
            cmbCategoryName.DataBind();
            cmbCategoryName.Items.Insert(0, "Select Category");

        }

        public void LoadUnits(string db)
        {
            cmbUnits.DataSource = ObjSel.Inv_Units(db);
            cmbUnits.DataTextField = "Unit";
            cmbUnits.DataValueField = "UnitID";
            cmbUnits.DataBind();
            // cmbUnits.Items.Insert(0, "Select Unit");

        }

        public void LoadPriceCaptionHeader(string db)  //JOHN ADDED ON 13-JAN-2021
        {
            cmbPriceTypeCaption.DataSource = ObjSel.LoadPriceTypeHeader(db);
            cmbPriceTypeCaption.DataTextField = "PriceCaptionName";
            cmbPriceTypeCaption.DataBind();
            cmbPriceTypeCaption.Items.Insert(0, "Select Price Caption Header");
        }

        public void LoadTakeawayCharge(string db)
        {
            cmbTakeAway.DataSource = ObjSel.LoadTakeAwayCharge(db);
            cmbTakeAway.DataTextField = "TakeAwayCaption";
            cmbTakeAway.DataValueField = "ID";
            cmbTakeAway.DataBind();
            //cmbTakeAway.Items.Insert(0, "Select Price Caption Header");
        }

        //public void LoadGroupsList(string Groupname)
        //{
        //    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 txtInventoryName_TextChanged(object sender, EventArgs e)
        {

            txtDescription.Text = txtInventoryName.Text;
        }

        protected void txtBarcode_TextChanged(object sender,EventArgs e)
        {
            this.txtInventoryName.Focus();
        }

        public void ClearCache()
        {

            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Cache.SetExpires(DateTime.Now);
            Response.Cache.SetNoServerCaching();
            Response.Cache.SetNoStore();

        }

        public static void ClearCacheItems()
        {
            foreach (System.Collections.DictionaryEntry entry in HttpContext.Current.Cache)
            {
                HttpContext.Current.Cache.Remove((string)entry.Key);
            }

            /*
            List<string> keys = new List<string>();
            IDictionaryEnumerator enumerator = Cache.GetEnumerator();

            while (enumerator.MoveNext())
                keys.Add(enumerator.Key.ToString());

            for (int i = 0; i < keys.Count; i++)
                Cache.Remove(keys[i]);
            */
        }

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

        //    txtSearchVal.CssClass = "form-control";

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

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

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



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

        //        // Prevents SQL Injections 
        //        // Parameterized approach 

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

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

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

        //        DT = ObjMain.NewGetData_DT(command2, parameters);

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

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


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

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

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

        //    }

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


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

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

        //        DT = ObjMain.NewGetData_DT(command4, parameters);

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


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

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

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

        //        DT = ObjMain.NewGetData_DT(command5, parameters);

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

        //    }

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

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

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


        //    }


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

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


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

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

        //    }

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

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


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

        //        DT = ObjMain.NewGetData_DT(command8, parameters);

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

        //    }



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

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

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

        //    }

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

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

        //    }


        //}

        protected void btnSaveTaxMain_Click(object sender, EventArgs e)
        {
            TaxValue2();
            ResetCheckboxIT();
        }

        public void TaxValue2()
        {
            string[] Valuu = new string[8];

            if (chk2InventoryCate.Checked == true)
            {
                Valuu[0] = "1";
            }
            else
            {
                Valuu[0] = "0";
            }
            if (chk2Always.Checked == true)
            {
                Valuu[1] = "1";
            }
            else
            {
                Valuu[1] = "0";
            }

            if (chk2TaxRate6.Checked == true)
            {
                Valuu[2] = "1";

            }
            else
            {
                Valuu[2] = "0";
            }

            if (chk2TaxRate5.Checked == true)
            {
                Valuu[3] = "1";
            }
            else
            {
                Valuu[3] = "0";
            }
            if (chk2TaxRate4.Checked == true)
            {
                Valuu[4] = "1";
            }
            else
            {
                Valuu[4] = "0";
            }

            if (chk2TaxRate3.Checked == true)
            {
                Valuu[5] = "1";
            }
            else
            {
                Valuu[5] = "0";
            }
            if (chk2scvc.Checked == true)
            {
                Valuu[6] = "1";
            }
            else
            {
                Valuu[6] = "0";
            }
            if (chk2GST.Checked == true)
            {
                Valuu[7] = "1";

            }
            else
            {
                Valuu[7] = "0";
            }


            StringBuilder Build = new StringBuilder();
            foreach (string valuess in Valuu)
            {
                Build.Append(valuess);
            }
            // mp1.Show();
            hidenInventoryTax.Value = Convert.ToString(Build);  // Inventory TaxSetting Value

            Session["ITaxSettings"] = hidenInventoryTax.Value;
            lblmsgTaxMain.Text = Session["ITaxSettings"].ToString();
        }

        public void ResetCheckboxIT()
        {
            chk2InventoryCate.Checked = false;
            chk2Always.Checked = false;
            chk2TaxRate6.Checked = false;
            chk2TaxRate5.Checked = false;
            chk2TaxRate4.Checked = false;
            chk2TaxRate3.Checked = false;
            chk2scvc.Checked = false;
            chk2GST.Checked = false;

        }

        protected void btnSavePrinterMain_Click(object sender, EventArgs e)
        {
            Flag2Value2();
            PSett = Session["IPrinterSetting"].ToString();

            lblmsgPrinterMain.Text = Session["IPrinterSetting"].ToString();
            ResetCheckboxIP();

        }

        public void ResetCheckboxIP()
        {
            chk2Invoice2.Checked = false;
            chk2RP19.Checked = false;
            chk2RP18.Checked = false;
            chk2RP17.Checked = false;
            chk2RP16.Checked = false;
            chk2RP15.Checked = false;

            chk2RP14.Checked = false;
            chk2RP13.Checked = false;
            chk2RP12.Checked = false;
            chk2RP11.Checked = false;
            chk2RP10.Checked = false;
            chk2RP9.Checked = false;
            chk2RP8.Checked = false;
            chk2RP7.Checked = false;
            chk2RP6.Checked = false;
            chk2RP5.Checked = false;
            chk2RP4.Checked = false;
            chk2RP3.Checked = false;
            chk2RP2.Checked = false;
            chk2RP1.Checked = false;


        }

        public void Flag2Value2()
        {
            string[] Printernew = new string[20];

            //if (chk2Invoice2.Checked == true)
            //{
            //    Printernew[0] = "1";

            //}
            //else
            //{
            //    Printernew[0] = "0";
            //}

            if (chk2RP19.Checked == true || chk2RP18.Checked == true || chk2RP17.Checked == true || chk2RP16.Checked == true || chk2RP15.Checked == true || chk2RP14.Checked == true || chk2RP13.Checked == true || chk2RP12.Checked == true || chk2RP11.Checked == true || chk2RP10.Checked == true || chk2RP9.Checked == true || chk2RP8.Checked == true || chk2RP7.Checked == true || chk2RP6.Checked == true || chk2RP5.Checked == true || chk2RP4.Checked == true || chk2RP3.Checked == true || chk2RP2.Checked == true || chk2RP1.Checked == true)
            {
                Printernew[0] = "1";

            }

            if (chk2RP19.Checked == false && chk2RP18.Checked == false && chk2RP17.Checked == false && chk2RP16.Checked == false && chk2RP15.Checked == false && chk2RP14.Checked == false && chk2RP13.Checked == false && chk2RP12.Checked == false && chk2RP11.Checked == false && chk2RP10.Checked == false && chk2RP9.Checked == false && chk2RP8.Checked == false && chk2RP7.Checked == false && chk2RP6.Checked == false && chk2RP5.Checked == false && chk2RP4.Checked == false && chk2RP3.Checked == false && chk2RP2.Checked == false && chk2RP1.Checked == false)
            {
                Printernew[0] = "0";
            }


            if (chk2RP19.Checked == true)
            {
                Printernew[1] = "1";
            }
            else
            {
                Printernew[1] = "0";
            }

            if (chk2RP18.Checked == true)
            {
                Printernew[2] = "1";

            }
            else
            {
                Printernew[2] = "0";
            }

            if (chk2RP17.Checked == true)
            {
                Printernew[3] = "1";
            }
            else
            {
                Printernew[3] = "0";
            }
            if (chk2RP16.Checked == true)
            {
                Printernew[4] = "1";
            }
            else
            {
                Printernew[4] = "0";
            }

            if (chk2RP15.Checked == true)
            {
                Printernew[5] = "1";
            }
            else
            {
                Printernew[5] = "0";
            }
            if (chk2RP14.Checked == true)
            {
                Printernew[6] = "1";
            }
            else
            {
                Printernew[6] = "0";
            }
            if (chk2RP13.Checked == true)
            {
                Printernew[7] = "1";

            }
            else
            {
                Printernew[7] = "0";
            }
            if (chk2RP12.Checked == true)
            {
                Printernew[8] = "1";

            }
            else
            {
                Printernew[8] = "0";
            }


            if (chk2RP11.Checked == true)
            {
                Printernew[9] = "1";

            }
            else
            {
                Printernew[9] = "0";
            }

            if (chk2RP10.Checked == true)
            {
                Printernew[10] = "1";

            }
            else
            {
                Printernew[10] = "0";
            }
            if (chk2RP9.Checked == true)
            {
                Printernew[11] = "1";

            }
            else
            {
                Printernew[11] = "0";
            }
            if (chk2RP8.Checked == true)
            {
                Printernew[12] = "1";

            }
            else
            {
                Printernew[12] = "0";
            }

            if (chk2RP7.Checked == true)
            {
                Printernew[13] = "1";

            }
            else
            {
                Printernew[13] = "0";
            }
            if (chk2RP6.Checked == true)
            {
                Printernew[14] = "1";

            }
            else
            {
                Printernew[14] = "0";
            }
            if (chk2RP5.Checked == true)
            {
                Printernew[15] = "1";

            }
            else
            {
                Printernew[15] = "0";
            }

            if (chk2RP4.Checked == true)
            {
                Printernew[16] = "1";

            }
            else
            {
                Printernew[16] = "0";
            }


            if (chk2RP3.Checked == true)
            {
                Printernew[17] = "1";

            }
            else
            {
                Printernew[17] = "0";
            }


            if (chk2RP2.Checked == true)
            {
                Printernew[18] = "1";

            }
            else
            {
                Printernew[18] = "0";
            }

            if (chk2RP1.Checked == true)
            {
                Printernew[19] = "1";

            }
            else
            {
                Printernew[19] = "0";
            }

            StringBuilder BuildVals = new StringBuilder();
            foreach (string vals in Printernew)
            {
                BuildVals.Append(vals);
            }

            HideInvenPrinter.Value = Convert.ToString(BuildVals);
            Session["IPrinterSetting"] = HideInvenPrinter.Value;
            lblmsgPrinterMain.Text = Session["IPrinterSetting"].ToString();
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {

            if (cmbCategoryName.SelectedIndex != 0)
            {

                //if (cmbUnits.SelectedIndex != 0)
                //{
                SaveInventoryInfo();
                LoadInventoryview();
                
                cmbCategoryName.SelectedIndex = 0;
                txtBarcode.Text = "";
                txtInventoryName.Text = "";
                txtPrice1.Text = "";
                txtPrice2.Text = "";
                txtPrice3.Text = "";
                txtDescription.Text = "";

                ClearInvForm();
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Inventory Created Successfully ') ", true);
                //}
                //else
                //{

                //    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' You must select the Unit ') ", true);
                //}





            }
            else
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' You must select the CategoryName ') ", true);
            }

        }

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


        protected void ClearInvForm()
        {
            txtReadInventroyId.Text = "";
            txtBarcode.Text = "";
            cmbCategoryName.SelectedIndex = 0;
            cmbClass.SelectedIndex = 0;
            txtInventoryName.Text = "";
            txtDescription.Text = "";
            //cmbUnits.SelectedIndex = 0;
            txtPrice1.Text = "";
            txtPrice2.Text = "";
            txtPrice3.Text = "";
            txtPrice4.Text = "";
            txtReorder.Text = "";
            txtSafty.Text = "";
            txtMaximum.Text = "";
            txtStockCode.Text = "";
            cmbGroup1.SelectedIndex = 0;
            cmbGroup2.SelectedIndex = 0;
            cmbGroup3.SelectedIndex = 0;
            cmbGroup4.SelectedIndex = 0;
            cmbGroup5.SelectedIndex = 0;

            txtNotes.Text = "";
            //LblInvIDCaption.Visible = false;
            //lblInventoryID.Visible = false;
            //btnSubmit.Visible = true;
            //btnUpdateInv.Visible = false;
            // Reset other Controls  Added on 25-05-21

            chkActiveStatus.Checked = false;
            ChkNotAvailable.Checked = false;
            //cmbUnits.SelectedIndex = 0;
            cmbPriceTypeCaption.SelectedIndex = 0;
            cmbCategoryName.SelectedIndex = 0;
            cmbGroup1.SelectedIndex = 0;
            cmbGroup2.SelectedIndex = 0;
            cmbGroup3.SelectedIndex = 0;
            cmbGroup4.SelectedIndex = 0;
            cmbGroup5.SelectedIndex = 0;


            chk2Invoice2.Checked = false;
            chk2RP19.Checked = false;
            chk2RP18.Checked = false;
            chk2RP17.Checked = false;
            chk2RP16.Checked = false;
            chk2RP15.Checked = false;
            chk2RP14.Checked = false;
            chk2RP13.Checked = false;
            chk2RP12.Checked = false;
            chk2RP11.Checked = false;
            chk2RP10.Checked = false;
            chk2RP9.Checked = false;
            chk2RP8.Checked = false;
            chk2RP7.Checked = false;
            chk2RP6.Checked = false;
            chk2RP5.Checked = false;
            chk2RP4.Checked = false;
            chk2RP3.Checked = false;
            chk2RP2.Checked = false;
            chk2RP1.Checked = false;
            ChkShowItem.Checked = false;
            chkTA.Checked = false;
            ChkNoDiscount.Checked = false;
            chkPromo.Checked = false;
            TxtMBarcode.Text = string.Empty;
            txtMName.Text = string.Empty;
            txtMDesc.Text = string.Empty;
            chkTaxRate6.Checked = false;
            chkTaxRate5.Checked = false;
            chkTax4.Checked = false;
            chkTax3.Checked = false;
            chkTax2.Checked = false;
            chkTax1.Checked = false;

            chkMainProductRelation.Checked = false;         //john added on 18-Sept-2024
            chkNotIncludeProductRelation.Checked = false;   //john added on 18-Sept-2024



        }
        /// <summary>
        /// This Function Saves Inventory Information 
        /// </summary>
        public void SaveInventoryInfo()
        {
            string sSpicy = string.Empty;
            string sChef = string.Empty;
            string sBeef = string.Empty;
            string sChicken = string.Empty;
            string sPork = string.Empty;

            MySqlConnection Cnn = new MySqlConnection(ConStr);
            Cnn.Open();

            // Common Code for Get Branchdatabase 

            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


            }

            DTCheckBarcode = ObjSel.CheckBarcode(BranchAlias, txtBarcode.Text);
            if (DTCheckBarcode.Rows.Count != 0)
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Item already existing in the system ')", true);
                ClearInvForm();
                return;
            }


            MakeTaxSetting();  // Tax Setting 
            Flag2Value2();   // Printer Setting 


            ObjPL.InventoryId = ObjSel.GetMax_RunningNo(BranchAlias);
            ObjPL.Units = cmbUnits.SelectedItem.Text;

            if (txtPrice1.Text == "")
            {
                ObjPL.Price1 = 0;
            }
            else
            {
                ObjPL.Price1 = Convert.ToDecimal(txtPrice1.Text);
            }
            if (txtPrice2.Text == "")
            {
                ObjPL.Price2 = 0;
            }
            else
            {
                ObjPL.Price2 = Convert.ToDecimal(txtPrice2.Text);
            }

            if (txtPrice3.Text == "")
            {
                ObjPL.Price3 = 0;
            }
            else
            {
                ObjPL.Price3 = Convert.ToDecimal(txtPrice3.Text);
            }

            if (txtPrice4.Text == "")
            {
                ObjPL.Price4 = 0;
            }
            else
            {
                ObjPL.Price4 = Convert.ToDecimal(txtPrice4.Text);
            }

            if (txtReorder.Text == "")
            {
                ObjPL.ReoderLevel = 0;
            }
            else
            {
                ObjPL.ReoderLevel = Convert.ToInt64(txtReorder.Text);
            }

            if (txtSafty.Text == "")
            {
                ObjPL.SaftyLevel = 0;
            }
            else
            {
                ObjPL.SaftyLevel = Convert.ToInt64(txtSafty.Text);
            }

            if (txtMaximum.Text == "")
            {
                ObjPL.MaixmumLevel = 0;
            }
            else
            {
                ObjPL.MaixmumLevel = Convert.ToInt64(txtMaximum.Text);
            }
            if (cmbGroup1.SelectedIndex == 0)
            {
                cmbGroup1.SelectedItem.Text = "";
            }
            if (cmbGroup2.SelectedIndex == 0)
            {
                cmbGroup2.SelectedItem.Text = "";
            }
            if (cmbGroup3.SelectedIndex == 0)
            {
                cmbGroup3.SelectedItem.Text = "";
            }
            if (cmbGroup4.SelectedIndex == 0)
            {
                cmbGroup4.SelectedItem.Text = "";
            }
            if (cmbGroup5.SelectedIndex == 0)
            {
                cmbGroup5.SelectedItem.Text = "";
            }

            //John added on 04-Aug-2020
            if (chkSpicy.Checked == true)
            {
                sSpicy = "1";
            }
            else
            {
                sSpicy = "0";
            }

            if (chkChef.Checked == true)
            {
                sChef = "1";
            }
            else
            {
                sChef = "0";
            }

            if (chkBeef.Checked == true)
            {
                sBeef = "1";
            }
            else
            {
                sBeef = "0";
            }

            if (chkChicken.Checked == true)
            {
                sChicken = "1";
            }
            else
            {
                sChicken = "0";
            }

            if (chkPork.Checked == true)
            {
                sPork = "1";
            }
            else
            {
                sPork = "0";
            }

            if (chkTA.Checked == true)
            {
                sTakeAway = "1";
            }
            else
            {
                sTakeAway = "0";
            }

            if (ChkNotAvailable.Checked == true)
            {
                sAvailable = "1";
            }
            else
            {
                sAvailable = "0";
            }

            if (ChkShowItem.Checked == true)
            {
                sShowItem = "1";
            }
            else
            {
                sShowItem = "0";
            }



            if (ChkShowItem.Checked == true)
            {
                // Promo checks
                if (chkPromo.Checked == true)
                {
                    sPromo = "1";
                }
                else
                {
                    sPromo = "0";
                }
            }
            else
            {
                sPromo = "0";
            }




            if (ChkNoDiscount.Checked == true)
            {
                sNodiscount = "1";
            }
            else
            {
                sNodiscount = "0";
            }

            //Product Relation //john added on 18-Sept-2024
            if(chkMainProductRelation.Checked == true)
            {
                sProductRelationMain = "1";
            }
            else
            {
                sProductRelationMain = "0";
            }

            if(chkNotIncludeProductRelation.Checked == true)
            {
                sProductRelationNotInculde = "1";
            }
            else
            {
                sProductRelationNotInculde = "0";
            }


            // Calling  S3 Image Fileupload Function 
            // SaveImagedetailstoS3(BranchAlias, ObjPL.InventoryId);  This Function Is removed . 
            //==========================

            // John added WebIcon1,WebIcon2,WebIcon3,WebIcon4 on 07-Aug-2020 
            //   string Query = "insert into " + BranchAlias + ".inventory(InventoryID,BarCode,InventoryName,Description,CategoryID,Class,Unit,Price," +
            //"  Price2,Price3,Price4,DateCreated,Group1,Group2,Group3,Group4,Group5,NoPriceShift,Active,Updated," +
            //"  Notes,BranchUpdated,StockCode,Flag1,Flag2,ReorderLevel,MaxiumLevel,SafetyLevel,WebIcon1,WebIcon2,WebIcon3,WebIcon4,WebIcon5)" + 
            //"  values (" + ObjPL.InventoryId + "  ,'" + txtBarcode.Text + "', '" + txtInventoryName.Text + "','" + txtDescription.Text + "'," + cmbCategoryName.SelectedValue + ", " +
            //"  " + cmbClass.SelectedItem.Value + " , '" + ObjPL.Units + "'," + ObjPL.Price1 + "," + ObjPL.Price2 + "," + ObjPL.Price3 + "," + ObjPL.Price4 + ",'" + Curr_DateOnly + "','" + cmbGroup1.SelectedItem.Text + "','" + cmbGroup2.SelectedItem.Text + "'," +
            //"  '" + cmbGroup3.SelectedItem.Text + "','" + cmbGroup4.SelectedItem.Text + "','" + cmbGroup5.SelectedItem.Text + "',0,-1,0,' ',0, '" + txtStockCode.Text + "', '" + hidNewTax.Value + "','" + HideInvenPrinter.Value + "'," + ObjPL.ReoderLevel + " ," + ObjPL.SaftyLevel + "," + ObjPL.MaixmumLevel + "," +
            //   " '" + sSpicy + "','" + sChef + "','" + sBeef + "','" + sChicken + "','" + sPork + "');";

            string sWebpriceCaptionID = ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text); // JOHN ADDED ON 13-JAN-2021
            if (hdnfileid.Value != "")   // Modified On 15-07-21 ( S3-Bucket) 
            {
                string Query = "insert into {0}.inventory(InventoryID,BarCode,InventoryName,Description,CategoryID,Class,Unit,Price, " +
            "  Price2,Price3,Price4,DateCreated,Group1,Group2,Group3,Group4,Group5,NoPriceShift,Active,Updated, " +
            "  Notes,BranchUpdated,StockCode,Flag1,Flag2,ReorderLevel,MaxiumLevel,SafetyLevel,webpricecaptionid,imagepath,TakeawayFlag,OutofStock,showitem,Promo,fileid,TAId,productrelationmain,productrelationnotinclude) " +
            "  values (@InventoryID ,@BarCode, @InventoryName,@Description,@CategoryID, " +
            "  @Class ,@Unit,@Price,@Price2,@Price3,@Price4,@DateCreated,@Group1,@Group2, " +
            "  @Group3,@Group4,@Group5,@NoPriceShift,@Active,@Updated,@Notes,@BranchUpdated,@StockCode,@Flag1,@Flag2,@ReorderLevel, " +
            "  @MaxiumLevel,@SafetyLevel,@webpricecaptionid,@imagepath,@TakeawayFlag,@OutofStock,@showitem,@Promo,@fileid,@TAId,@productrelationmain,@productrelationnotinclude );";

                MySqlParameter[] parameters =
                     {
                     new MySqlParameter("@InventoryID",ObjPL.InventoryId),
                     new MySqlParameter("@BarCode",txtBarcode.Text.ToString().Trim()),
                     new MySqlParameter("@InventoryName",txtInventoryName.Text.ToString().Trim()),
                     new MySqlParameter("@Description",txtDescription.Text.ToString().Trim()),
                     new MySqlParameter("@CategoryID",cmbCategoryName.SelectedValue),
                     new MySqlParameter("@Class",cmbClass.SelectedItem.Value),
                     new MySqlParameter("@Unit",ObjPL.Units),
                     new MySqlParameter("@Price",ObjPL.Price1),
                     new MySqlParameter("@Price2",ObjPL.Price2),
                     new MySqlParameter("@Price3",ObjPL.Price3),
                     new MySqlParameter("@Price4",ObjPL.Price4),
                     new MySqlParameter("@DateCreated",Curr_DateOnly),
                     new MySqlParameter("@Group1",cmbGroup1.SelectedItem.Text),
                     new MySqlParameter("@Group2",cmbGroup2.SelectedItem.Text),
                     new MySqlParameter("@Group3",cmbGroup3.SelectedItem.Text),
                     new MySqlParameter("@Group4",cmbGroup4.SelectedItem.Text),
                     new MySqlParameter("@Group5",cmbGroup5.SelectedItem.Text),
                     new MySqlParameter("@NoPriceShift",sNodiscount),
                     new MySqlParameter("@Active",-1),
                     new MySqlParameter("@Updated",0),
                     new MySqlParameter("@Notes",txtNotes.Text),
                     new MySqlParameter("@BranchUpdated",0),
                     new MySqlParameter("@StockCode",txtRStockCode.Text),
                     new MySqlParameter("@Flag1",hidNewTax.Value),
                     new MySqlParameter("@Flag2",HideInvenPrinter.Value),
                     new MySqlParameter("@ReorderLevel",ObjPL.ReoderLevel),
                     new MySqlParameter("@MaxiumLevel",ObjPL.MaixmumLevel),
                     new MySqlParameter("@SafetyLevel",ObjPL.SaftyLevel),
                     new MySqlParameter("@webpricecaptionid",sWebpriceCaptionID),
                     new MySqlParameter("@imagepath",hdnurl.Value),
                     new MySqlParameter("@TakeawayFlag",sTakeAway),
                     new MySqlParameter("@OutofStock",sAvailable),
                     new MySqlParameter("@showitem",sShowItem),
                     new MySqlParameter("@Promo",sPromo),
                     new MySqlParameter("@fileid",FileID),
                     new MySqlParameter("@TAId",cmbTakeAway.SelectedValue),
                     new MySqlParameter("@productrelationmain",sProductRelationMain),
                     new MySqlParameter("@productrelationnotinclude",sProductRelationNotInculde),
                };
                string commmandInventory = string.Format(Query, BranchAlias);
                K = ObjMain.ExecuteQuery(commmandInventory, parameters);

            }
            else
            {
                string Query = "insert into {0}.inventory(InventoryID,BarCode,InventoryName,Description,CategoryID,Class,Unit,Price," +
               "  Price2,Price3,Price4,DateCreated,Group1,Group2,Group3,Group4,Group5,NoPriceShift,Active,Updated," +
               "  Notes,BranchUpdated,StockCode,Flag1,Flag2,ReorderLevel,SafetyLevel,MaxiumLevel,webpricecaptionid,TakeawayFlag,OutofStock,showitem,Promo,TAId,productrelationmain,productrelationnotinclude)" +
               "  values " +
               "  (@InventoryID,@BarCode, @InventoryName,@Description,@CategoryID , " +
               "  @Class,@Unit,@Price,@Price2,@Price3,@Price4,@DateCreated,@Group1,@Group2," +
               "  @Group3,@Group4,@Group5,@NoPriceShift,@Active,@Updated,@Notes,@BranchUpdated,@StockCode, " +
               "  @Flag1,@Flag2,@ReorderLevel ,@SafetyLevel,@MaxiumLevel,@webpricecaptionid,@TakeawayFlag,@OutofStock,@showitem,@Promo,@TAId,@productrelationmain,@productrelationnotinclude);";



                MySqlParameter[] parameters2 =
                  {
                     new MySqlParameter("@InventoryID",ObjPL.InventoryId),
                     new MySqlParameter("@BarCode",txtBarcode.Text.ToString().Trim()),
                     new MySqlParameter("@InventoryName",txtInventoryName.Text.ToString().Trim()),
                     new MySqlParameter("@Description",txtDescription.Text.ToString().Trim()),
                     new MySqlParameter("@CategoryID",cmbCategoryName.SelectedValue),
                     new MySqlParameter("@Class",cmbClass.SelectedItem.Value),
                     new MySqlParameter("@Unit",ObjPL.Units),
                     new MySqlParameter("@Price",ObjPL.Price1),
                     new MySqlParameter("@Price2",ObjPL.Price2),
                     new MySqlParameter("@Price3",ObjPL.Price3),
                     new MySqlParameter("@Price4",ObjPL.Price4),
                     new MySqlParameter("@DateCreated",Curr_DateOnly),
                     new MySqlParameter("@Group1",cmbGroup1.SelectedItem.Text),
                     new MySqlParameter("@Group2",cmbGroup2.SelectedItem.Text),
                     new MySqlParameter("@Group3",cmbGroup3.SelectedItem.Text),
                     new MySqlParameter("@Group4",cmbGroup4.SelectedItem.Text),
                     new MySqlParameter("@Group5",cmbGroup5.SelectedItem.Text),
                     new MySqlParameter("@NoPriceShift",sNodiscount),
                     new MySqlParameter("@Active",-1),
                     new MySqlParameter("@Updated",0),
                     new MySqlParameter("@Notes",txtNotes.Text),
                     new MySqlParameter("@BranchUpdated",0),
                     new MySqlParameter("@StockCode",txtRStockCode.Text),
                     new MySqlParameter("@Flag1",hidNewTax.Value),
                     new MySqlParameter("@Flag2",HideInvenPrinter.Value),
                     new MySqlParameter("@ReorderLevel",ObjPL.ReoderLevel),
                     new MySqlParameter("@MaxiumLevel",ObjPL.MaixmumLevel),
                     new MySqlParameter("@SafetyLevel",ObjPL.SaftyLevel),
                     new MySqlParameter("@webpricecaptionid",sWebpriceCaptionID),
                     new MySqlParameter("@TakeawayFlag",sTakeAway),
                     new MySqlParameter("@OutofStock",sAvailable),
                     new MySqlParameter("@showitem",sShowItem),
                     new MySqlParameter("@Promo",sPromo),
                     new MySqlParameter("@TAId",cmbTakeAway.SelectedValue),
                      new MySqlParameter("@productrelationmain",sProductRelationMain),
                     new MySqlParameter("@productrelationnotinclude",sProductRelationNotInculde),

                };

                string commmandInventory = string.Format(Query, BranchAlias);

                K = ObjMain.ExecuteQuery(commmandInventory, parameters2);


            }



            // Insert  CostAvg Table 
            string Query1 = " INSERT INTO {0}.inventorycostaverage(`InventoryID`, `PQuantity`, `PAmount`, `CutQuantity`, `CutAmount`, `UnitCost`, `RetailQty`, `RetailAmount`) " +
                            " VALUES (@InventoryID,@PQuantity,@PAmount,@CutQuantity,@CutAmount,@UnitCost,@RetailQty,@RetailAmount); ";



            ICObj.InventoryID = int.Parse(ObjPL.InventoryId);
            ICObj.PQuantity = decimal.Parse("0.0000");
            ICObj.PAmount = decimal.Parse("0.0000");
            ICObj.CutQuantity = decimal.Parse("0.0000");
            ICObj.CutAmount = decimal.Parse("0.0000");
            ICObj.UnitCost = decimal.Parse("0.0000");
            ICObj.RetailQty = decimal.Parse("0.0000");
            ICObj.RetailAmount = decimal.Parse("0.0000");

            MySqlParameter[] parameters3 =
                  {
                     new MySqlParameter("@InventoryID",ICObj.InventoryID),
                     new MySqlParameter("@PQuantity",ICObj.PQuantity),
                     new MySqlParameter("@PAmount",ICObj.PAmount),
                     new MySqlParameter("@CutQuantity",ICObj.CutQuantity),
                     new MySqlParameter("@CutAmount",ICObj.CutAmount),
                     new MySqlParameter("@UnitCost",ICObj.UnitCost),
                     new MySqlParameter("@RetailQty",ICObj.RetailQty),
                     new MySqlParameter("@RetailAmount",ICObj.RetailAmount),
                  };



            string command = string.Format(Query1, BranchAlias);
            L = ObjMain.ExecuteQuery(command, parameters3);


            string QueryUPT = "update {0}.runningnumber set RunningNo={1}   where ModuleName='Inventory';";
            string commandU = string.Format(QueryUPT, BranchAlias, ObjPL.InventoryId);
            U = ObjCloudMain.ExecuteNonQuery(commandU);
            // Create the TimescheduleFlag For new Inventory Creation 
            // Create the PriceFlag For new Inventory Creation 
            CreateTimeschedule(BranchAlias, ObjPL.InventoryId);
            CreateTimescheduleFlag(BranchAlias, ObjPL.InventoryId, txtBarcode.Text);
            CreatePriceFlag(BranchAlias, ObjPL.InventoryId, txtBarcode.Text);

            //if (sPromo == "1") //John added on 16-Aug-2021 Validate if item is WebOrder Promo
            //{
            //    SavePromoItem(BranchAlias, ObjPL.InventoryId, txtBarcode.Text); //John added on 16-Aug-2021  Insert Promo Item in WebOrderPromo Table
            //}
        }

        /// <summary>
        ///  This Function Inserts A Record when create the New Inventory Item 
        /// </summary>
        /// <param name="sdb"></param>
        /// <param name="Inventoryid"></param>
        /// <param name="Barcode"></param>
               public void CreateTimescheduleFlag(string sdb, string Inventoryid, string Barcode)
        {
            #region   Insert Portion
            string Ins_ScheduleFlag = " insert into {0}.timescheduleFlag (Inventoryid,Barcode,IsCommonUpdate,IsNotAvailable)" +
                                      " values " +
                                      " (@Inventoryid,@Barcode,@IsCommonUpdate,@IsNotAvailable);";
            string Ins_command = string.Format(Ins_ScheduleFlag, sdb);
            MySqlParameter[] parameters =
                {
                             new MySqlParameter("@Inventoryid",Inventoryid),
                             new MySqlParameter("@Barcode",Barcode),
                             new MySqlParameter("@IsCommonUpdate","0"),
                             new MySqlParameter("@IsNotAvailable","0"),
                        };
            Q = ObjMain.ExecuteQuery(Ins_command, parameters);




            #endregion


        }
        
        /// <summary>
        ///  This Function Insert a Record into PriceFlag When Create New Inventory Item
        /// </summary>
        /// <param name="sdb"></param>
        /// <param name="Inventoryid"></param>
        /// <param name="Barcode"></param>
        public void CreatePriceFlag(string sdb, string Inventoryid, string Barcode)
        {
            #region   Insert Portion
            string Ins_PriceFlag = " insert into {0}.PriceFlag (Inventoryid,Barcode,Price_Flag,Price2_Flag,Price3_Flag,Price4_Flag)" +
                                   " values " +
                                   " (@Inventoryid,@Barcode,@Price_Flag,@Price2_Flag,@Price3_Flag,@Price4_Flag);";
            string Ins_command = string.Format(Ins_PriceFlag, sdb);
            MySqlParameter[] parametersM =
                {
                             new MySqlParameter("@Inventoryid",Inventoryid),
                             new MySqlParameter("@Barcode",Barcode),
                             new MySqlParameter("@Price_Flag","0"),
                             new MySqlParameter("@Price2_Flag","0"),
                             new MySqlParameter("@Price3_Flag","0"),
                             new MySqlParameter("@Price4_Flag","0"),
                        };
            L = ObjMain.ExecuteQuery(Ins_command, parametersM);

            #endregion



        }

        protected void grdInventoryView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {


            if (cmbBranches.Visible == false)
            {
                grdInventoryView.PageIndex = e.NewPageIndex;
                LoadInventoryview(Session["Branch_HQ"].ToString());
            }
            else
            {

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

                }
                #endregion


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

            }


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

                }
                #endregion


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

                DT = ObjMain.GetData_DT(NewQuery);

                grdInventoryView.PageIndex = e.NewPageIndex;
                grdInventoryView.DataSource = DT;
                grdInventoryView.DataBind();
            }
            else if (cmbSearch.SelectedIndex == 1)
            {
                #region  Validation Between HQ Branch and Normal Branch 
                BranchFullName = cmbBranches.SelectedItem.Text;      // This will Return Branch FullName 
                if (BranchFullName == "HQ")
                {
                    BranchAlias = Session["Branch_HQ"].ToString();
                }
                else
                {
                    BranchFullName = cmbBranches.SelectedItem.Text;     // This will Return Branch FullName 
                    Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);  // This will Return BranchName( Actual Database Name )
                    BranchAlias = Cmb_BranchName;

                }
                #endregion


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

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

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

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

                grdInventoryView.DataBind();

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

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

                }
                #endregion

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


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

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

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

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

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

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

                }
                #endregion

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


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

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

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

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

                }
                #endregion

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

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

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

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

                }
                #endregion

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

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

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


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

                }
                #endregion

                string sActivex = string.Empty;

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


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

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

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

                }
                #endregion

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

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


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

            }

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

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

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

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

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

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

                }
                #endregion

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

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

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


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

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

                }
                #endregion

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

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

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

            }

        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {

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

            }
            #endregion

            #region Delete inventory  Table    
            string Del_Inventory = " Delete from {0}.inventory where Inventoryid=@Inventoryid;";
            string Del_command = string.Format(Del_Inventory, BranchAlias);
            MySqlParameter[] Del_Inventory_parameters =
                       {
                             new MySqlParameter("@Inventoryid",txtReadInventroyId.Text),

                        };
            Q = ObjMain.ExecuteQuery(Del_command, Del_Inventory_parameters);




            #endregion

            #region Delete inventoryCostaverage  Table    
            string Del_Inventorycostaverage = " Delete from {0}.inventorycostaverage where Inventoryid=@Inventoryid;";
            string Del_Inventorycostaverage_command = string.Format(Del_Inventorycostaverage, BranchAlias);
            MySqlParameter[] Del_Inventorycostaverage_parameters =
                       {
                             new MySqlParameter("@Inventoryid",txtReadInventroyId.Text),

                        };
            R = ObjMain.ExecuteQuery(Del_Inventorycostaverage_command, Del_Inventorycostaverage_parameters);




            #endregion

            #region Delete timeschedule  Table    
            string Del_Timeschedule = " Delete from {0}.timeschedule where Inventoryid=@Inventoryid;";
            string Del_Timeschedule_command = string.Format(Del_Timeschedule, BranchAlias);
            MySqlParameter[] Del_Timeschedule_parameters =
                       {
                             new MySqlParameter("@Inventoryid",txtReadInventroyId.Text),

                        };
            K = ObjMain.ExecuteQuery(Del_Timeschedule_command, Del_Timeschedule_parameters);




            #endregion

            #region Delete PriceFlag  Table    
            string Del_Priceflag = " Delete from {0}.priceflag where Inventoryid=@Inventoryid;";
            string Del_Priceflag_command = string.Format(Del_Priceflag, BranchAlias);
            MySqlParameter[] Del_Priceflag_parameters =
                       {
                             new MySqlParameter("@Inventoryid",txtReadInventroyId.Text),

                        };
            R = ObjMain.ExecuteQuery(Del_Priceflag_command, Del_Priceflag_parameters);

            #endregion

            #region Delete filedetails  Table    
            string Del_Filedetails = " Delete from {0}.filedetails where Inventoryid=@Inventoryid;";
            string Del_Filedetails_command = string.Format(Del_Filedetails, BranchAlias);
            MySqlParameter[] Del_Filedetails_parameters =
                       {
                             new MySqlParameter("@Inventoryid",txtReadInventroyId.Text),

                        };
            L = ObjMain.ExecuteQuery(Del_Filedetails_command, Del_Filedetails_parameters);

            #endregion

            if (Q > 0 && R > 0)
            {
                CreateLog_Delete_Inventory(txtReadInventroyId.Text);
            }

            UPDATEBRANCH(BranchAlias);

            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Inventory Deleted Successfully!.');location.href='InventoryMaster.aspx'", true);
        }

        #region  Inventory Delete Log 
        public void CreateLog_Delete_Inventory(string Inventoryid)
        {
            string Category_Insert = "Insert into {0}.InventoryDeleteLog(Inventoryid,Deleteby,Deleteddate,userid)values(@Inventoryid,@Deleteby,@Deleteddate,@userid); ";
            string Ins_CategoryLog_Command = string.Format(Category_Insert, BranchAlias);
            MySqlParameter[] Ins_Category_parameters =
                      {
                        new MySqlParameter("@Inventoryid",Convert.ToInt32(Inventoryid)),
                        new MySqlParameter("@Deleteby",Session["UserName"].ToString()),
                        new MySqlParameter("@Deleteddate",Curr_Date),
                        new MySqlParameter("@userid", Convert.ToInt32(Session["UserId"].ToString())),

                      };
            K = ObjMain.ExecuteQuery(Ins_CategoryLog_Command, Ins_Category_parameters);
        }

        #endregion
        protected void btnSearchBarcode_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
            }

            lblImageError.Text = "";
            DTInvInfo = ObjSel.GetInvInfo(BranchAlias, txtBarcode.Text.ToString().Trim());
            if (DTInvInfo.Rows.Count == 0)
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Item not found, please enter valid Barcode ')", true);
                ClearInvForm();
                return;
            }
            else
            {
                txtEffectiveDt.Text = Curr_DateOnly;
                ShowInventory();
                btnSubmit.Visible = false;
                btnUpdateInv.Visible = true;
                txtBarcode.Focus();

            }
        }

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

        public void ShowInventory()
        {
            // xss Prevention enabled 
            Page.ClientScript.RegisterStartupScript(this.GetType(), "hash", "location.hash = '#Inventoryx';", true);

            ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "MyFun1", "disableDiv();", true);
            ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "MyFun8", "ShowTopUpdateButton();", true);




            #region UnitPrice Hide and Show 

            string is_view_unitcost = "select inivalue from " + BranchAlias + ".weborderinginisetting where id = 82;";
            string Read_Value_unitcost = ObjMain.ExecuteScalar(is_view_unitcost);
            string _branch = Session["BranchDB"] != null ? Session["BranchDB"].ToString() : "";
            ScriptManager.RegisterStartupScript(
                             this,
                             this.GetType(),
                             "Javascript",
                             $"Loadunitpricelable('{_branch}');",
                             true
                         );

            #endregion




            #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

            

            // Assign s3 realted Parameter values 
            lblclientname.Text = Session["CM_ID"].ToString();
            lblstorename.Text = BranchAlias;

            GInventoryID = DTInvInfo.Rows[0]["InventoryID"].ToString();
            GInventoryName = DTInvInfo.Rows[0]["InventoryName"].ToString();
            GDescription = DTInvInfo.Rows[0]["Description"].ToString();
            GCategoryID = DTInvInfo.Rows[0]["CategoryID"].ToString();
            GClass = DTInvInfo.Rows[0]["Class"].ToString();
            GUnit = DTInvInfo.Rows[0]["Unit"].ToString();
            GPrice = DTInvInfo.Rows[0]["Price"].ToString();
            GPrice2 = DTInvInfo.Rows[0]["Price2"].ToString();
            GPrice3 = DTInvInfo.Rows[0]["Price3"].ToString();
            GPrice4 = DTInvInfo.Rows[0]["Price4"].ToString();
            GGroup1 = DTInvInfo.Rows[0]["Group1"].ToString();

            txtRStockCode.Text = DTInvInfo.Rows[0]["stockcode"].ToString();

            string Groupid1query = "select Groupid from {0}.group1  where GroupName='{1}' ;";
            string command1 = string.Format(Groupid1query, BranchAlias, GGroup1.ToString().Trim());
            GroupID1 = ObjMain.ExecuteScalar(command1);

            GGroup2 = DTInvInfo.Rows[0]["Group2"].ToString();

            string GroupID2_Query = "select Groupid from {0}.group2  where GroupName='{1}';";
            string command2 = string.Format(GroupID2_Query, BranchAlias, GGroup2.ToString().Trim());
            GroupID2 = ObjMain.ExecuteScalar(command2);
            GGroup3 = DTInvInfo.Rows[0]["Group3"].ToString();

            string GroupID3_Query = "select Groupid from {0}.group3  where GroupName='{1}';";
            string command3 = string.Format(GroupID3_Query, BranchAlias, GGroup3.ToString().Trim());

            GroupID3 = ObjMain.ExecuteScalar(command3);
            GGroup4 = DTInvInfo.Rows[0]["Group4"].ToString();

            string GroupID4_Query = "select Groupid from {0}.group4  where GroupName='{1}';";
            string commad4 = string.Format(GroupID4_Query, BranchAlias, GGroup4.ToString().Trim());
            GroupID4 = ObjMain.ExecuteScalar(commad4);
            GGroup5 = DTInvInfo.Rows[0]["Group5"].ToString();

            string GroupID5_Query = "select Groupid from {0}.group5  where GroupName='{1}';";
            string command5 = string.Format(GroupID5_Query, BranchAlias, GGroup5.ToString().Trim());
            GroupID5 = ObjMain.ExecuteScalar(command5);


            GFlag1 = DTInvInfo.Rows[0]["Flag1"].ToString();
            GFlag2 = DTInvInfo.Rows[0]["Flag2"].ToString();
            GReorderLevel = DTInvInfo.Rows[0]["ReorderLevel"].ToString();
            GMaximumLevel = DTInvInfo.Rows[0]["MaxiumLevel"].ToString();
            GSafetyLevel = DTInvInfo.Rows[0]["SafetyLevel"].ToString();
            GActive = DTInvInfo.Rows[0]["Active"].ToString();
            //sSpicy = DTInvInfo.Rows[0]["WebIcon1"].ToString();
            //sChef = DTInvInfo.Rows[0]["WebIcon2"].ToString();
            //sBeef = DTInvInfo.Rows[0]["WebIcon3"].ToString();
            //sChicken = DTInvInfo.Rows[0]["WebIcon4"].ToString();
            //sPork = DTInvInfo.Rows[0]["WebIcon5"].ToString();
            sTakeAway = DTInvInfo.Rows[0]["Takeawayflag"].ToString();

            sAvailable = DTInvInfo.Rows[0]["OutofStock"].ToString();
            sShowItem = DTInvInfo.Rows[0]["showitem"].ToString();
            sPromo = DTInvInfo.Rows[0]["Promo"].ToString();
            sGWebPriceCaptionID = DTInvInfo.Rows[0]["webpricecaptionid"].ToString();
            Notes = DTInvInfo.Rows[0]["Notes"].ToString();
            RTakeAwayValue = DTInvInfo.Rows[0]["TAId"].ToString();
            NoDiscount = DTInvInfo.Rows[0]["NoPriceShift"].ToString();
            txtNotes.Text = Notes;

            txtWebstockcount.Text = DTInvInfo.Rows[0]["WebstockCount"].ToString(); 

            //john added on 18-Sept-2024
            sProductRelationMain = DTInvInfo.Rows[0]["productrelationmain"].ToString();
            sProductRelationNotInculde = DTInvInfo.Rows[0]["productrelationnotinclude"].ToString();


            string Qry_Image = "select substring( I.ImagePath,1) AS ImagePath from {0}.inventory as i  where inventoryid={1}";
            string commandx = string.Format(Qry_Image, BranchAlias, GInventoryID);
            DTImageResult = ObjCloudMain.GetData_DT(commandx);

            DTImageResult.Rows[0]["ImagePath"] = DTImageResult.Rows[0]["ImagePath"] + "?nocache=" + rndGenerator.Next(10000);
            dtimg.DataSource = DTImageResult;
            dtimg.DataBind();

            // Get the UnitPrice detail ..


            string Qry_unitcost = "select unitcost from {0}.Inventorycostaverage where inventoryid={1} ;";
            string command_unitcost = string.Format(Qry_unitcost, BranchAlias, GInventoryID);
            string R_Unitcost = ObjMain.ExecuteScalar(command_unitcost);



            string newText = R_Unitcost;
            newText = newText.Replace("'", "\\'"); // escape for JavaScript safety;

            ScriptManager.RegisterStartupScript(
                this,
                this.GetType(),
                "SetLabelText",
                $"document.getElementById('unitprice_value').innerText = '{newText}';",
                true
            );



            if (sSpicy == "1")
            {
                chkSpicy.Checked = true;
            }
            else
            {
                chkSpicy.Checked = false;
            }

            if (sChef == "1")
            {
                chkChef.Checked = true;
            }
            else
            {
                chkChef.Checked = false;
            }

            if (sBeef == "1")
            {
                chkBeef.Checked = true;
            }
            else
            {
                chkBeef.Checked = false;
            }

            if (sChicken == "1")
            {
                chkChicken.Checked = true;
            }
            else
            {
                chkChicken.Checked = false;
            }

            if (sPork == "1")
            {
                chkPork.Checked = true;
            }
            else
            {
                chkPork.Checked = false;
            }

            if (sTakeAway == "1")
            {
                chkTA.Checked = true;
            }
            else
            {
                chkTA.Checked = false;
            }

            

            if (NoDiscount == "1")
            {
                ChkNoDiscount.Checked = true;
            }
            else
            {
                ChkNoDiscount.Checked = false;
            }

            //Assigning values to form fields



            txtReadInventroyId.Text = GInventoryID;
            txtReadInventroyId.Enabled = false;
            txtReadInventroyId.CssClass = "form-control";

            txtInventoryName.Text = GInventoryName;
            txtMName.Text = txtInventoryName.Text;  //Misc
            
            txtDescription.Text = GDescription;
            txtMDesc.Text = txtDescription.Text;    //Misc
            
            cmbCategoryName.SelectedIndex = cmbCategoryName.Items.IndexOf(cmbCategoryName.Items.FindByValue(GCategoryID));
            cmbClass.SelectedIndex = cmbClass.Items.IndexOf(cmbClass.Items.FindByValue(GClass));

            //GET PRICE CAPTION TYPE
            string pricecaptionQry = "Select PriceCaptionName from {0}.WebPriceCaption where ID = {1} ; ";
            string command_Pricecaption = string.Format(pricecaptionQry, BranchAlias, sGWebPriceCaptionID);
            RWebPriceCaptionID = ObjCloudMain.ExecuteScalar(command_Pricecaption);//JOHN ADDED ON 13-JAN-2021
            cmbPriceTypeCaption.SelectedIndex = cmbPriceTypeCaption.Items.IndexOf(cmbPriceTypeCaption.Items.FindByValue(RWebPriceCaptionID));
            // Get Unitid 

            string unitidQry = "select unitid from {0}.inventoryunits where Unit='{1}';";
            string command_Unitid = string.Format(unitidQry, BranchAlias, GUnit);
            RUnitids = ObjCloudMain.ExecuteScalar(command_Unitid);


            cmbUnits.SelectedIndex = cmbUnits.Items.IndexOf(cmbUnits.Items.FindByValue(RUnitids));
            txtPrice1.Text = GPrice;
            txtPrice2.Text = GPrice2;
            txtPrice3.Text = GPrice3;
            txtPrice4.Text = GPrice4;
            cmbGroup1.SelectedIndex = cmbGroup1.Items.IndexOf(cmbGroup1.Items.FindByValue(GroupID1));
            cmbGroup2.SelectedIndex = cmbGroup2.Items.IndexOf(cmbGroup2.Items.FindByValue(GroupID2));
            cmbGroup3.SelectedIndex = cmbGroup3.Items.IndexOf(cmbGroup3.Items.FindByValue(GroupID3));
            cmbGroup4.SelectedIndex = cmbGroup4.Items.IndexOf(cmbGroup4.Items.FindByValue(GroupID4));
            cmbGroup5.SelectedIndex = cmbGroup5.Items.IndexOf(cmbGroup5.Items.FindByValue(GroupID5));
            // TakeAway combobox
            cmbTakeAway.SelectedIndex = cmbTakeAway.Items.IndexOf(cmbTakeAway.Items.FindByValue(RTakeAwayValue));

            // Get the Flag1 Values - Tax Setting 
            char[] Flag_Val = GFlag1.ToCharArray();

            string c0 = Flag_Val[0].ToString();  //  1: Inventory Flag ; 0:Category Flag
            string c1 = Flag_Val[1].ToString();  //  Always : 0
            string c2 = Flag_Val[2].ToString();  //  Tax Rate 6
            string c3 = Flag_Val[3].ToString();  //  Tax Rate 5
            string c4 = Flag_Val[4].ToString();  //  Tax Rate 4
            string c5 = Flag_Val[5].ToString();  //  Tax Rate 3 
            string c6 = Flag_Val[6].ToString();  //  Scv.C
            string c7 = Flag_Val[7].ToString();  //  GST 


            // 1: Inventory Flag ; 0:Category Flag  in New Checkbox for it 

            if (c0.Equals("1"))
            {
                chk2InventoryCate.Checked = true;
            }
            else
            {
                chk2InventoryCate.Checked = false;
            }



            // Assgin values to Checkbox : 


            if (c1.Equals("1"))
            {
                chk2Always.Checked = true;
            }
            else
            {
                chk2Always.Checked = false;
            }

            if (c2.Equals("1"))
            {
                chk2TaxRate6.Checked = true;
            }
            else
            {
                chk2TaxRate6.Checked = false;
            }

            if (c3.Equals("1"))
            {
                chk2TaxRate5.Checked = true;
            }
            else
            {
                chk2TaxRate5.Checked = false;
            }

            if (c4.Equals("1"))
            {
                chk2TaxRate4.Checked = true;
            }
            else
            {
                chk2TaxRate4.Checked = false;
            }

            if (c5.Equals("1"))
            {
                chk2TaxRate3.Checked = true;
            }
            else
            {
                chk2TaxRate3.Checked = false;
            }


            if (c6.Equals("1"))
            {
                chk2GST.Checked = true;
            }
            else
            {
                chk2GST.Checked = false;
            }

            if (c7.Equals("1"))
            {
                chk2scvc.Checked = true;
            }
            else
            {
                chk2scvc.Checked = false;
            }


            //if (GActive.Equals("1")) //john hide on 18-Dec-2020
            //{
            //    chkActiveStatus.Checked = true;
            //}
            //else if (GActive.Equals("-1"))
            //{
            //    chkActiveStatus.Checked = true;
            //}
            //else if (GActive.Equals("0"))
            //{
            //    chkActiveStatus.Checked = false;
            //}

            if ((GActive == "True") || (GActive.Equals("1")) || (GActive.Equals("-1")))      //John added on 18-Dec-2020
            {
                chkActiveStatus.Checked = true;
            }
            else if ((GActive == "False") || (GActive.Equals("0")))
            {
                chkActiveStatus.Checked = false;
            }

            // Not Available

            if (sAvailable.Equals("1"))
            {
                ChkNotAvailable.Checked = true;

            }
            else if (sAvailable.Equals("0"))
            {
                ChkNotAvailable.Checked = false;
            }
            // ShowItem 


            if (sShowItem.Equals("1"))
            {
                ChkShowItem.Checked = true;

            }
            else if (sShowItem.Equals("0"))
            {
                ChkShowItem.Checked = false;
            }

            // Promo 
            if (sPromo.Equals("1"))
            {
                chkPromo.Checked = true;
            }
            else
            {
                chkPromo.Checked = false;
            }

            //product relation main
            if (sProductRelationMain.Equals("1"))
            {
                chkMainProductRelation.Checked = true;
            }
            else
            {
                chkMainProductRelation.Checked = false;
            }

            //product relation not include
            if (sProductRelationNotInculde.Equals("1"))
            {
                chkNotIncludeProductRelation.Checked = true;
            }
            else
            {
                chkNotIncludeProductRelation.Checked = false;
            }

            // Assign Combobox value form New TAX: 
            if (c0.Equals("1"))
            {
                ChkKeyValueTax.Checked = true;
            }
            else
            {
                ChkKeyValueTax.Checked = false;
            }



            if (c2.Equals("1"))
            {
                chkTaxRate6.Checked = true;

            }
            else
            {
                chkTaxRate6.Checked = false;
            }

            if (c3.Equals("1"))
            {
                chkTaxRate5.Checked = true;
            }
            else
            {
                chkTaxRate5.Checked = false;
            }

            if (c4.Equals("1"))
            {
                chkTax4.Checked = true;
            }
            else
            {
                chkTax4.Checked = false;
            }

            if (c5.Equals("1"))
            {
                chkTax3.Checked = true;
            }
            else
            {
                chkTax3.Checked = false;
            }

            if (c6.Equals("1"))
            {
                chkTax2.Checked = true;
            }
            else
            {
                chkTax2.Checked = false;
            }

            if (c7.Equals("1"))
            {
                chkTax1.Checked = true;
            }
            else
            {
                chkTax1.Checked = false;
            }

            //  Get the Flag2 Values : Printer Settings

            char[] Flag2_Val = GFlag2.ToCharArray();

            string P0 = Flag2_Val[0].ToString();           //1: Inventory Flag ; 0:Category Flag  
            string P1 = Flag2_Val[1].ToString();          // Print on Remote Printer 19                               
            string P2 = Flag2_Val[2].ToString();          // Print on Remote Printer 18  
            string P3 = Flag2_Val[3].ToString();         //  Print on Remote Printer 17  
            string P4 = Flag2_Val[4].ToString();         //  Print on Remote Printer 16  
            string P5 = Flag2_Val[5].ToString();        //   Print on Remote Printer 15  
            string P6 = Flag2_Val[6].ToString();        //   Print on Remote Printer 14   
            string P7 = Flag2_Val[7].ToString();        //   Print on Remote Printer 13  
            string P8 = Flag2_Val[8].ToString();        //   Print on Remote Printer 12 
            string P9 = Flag2_Val[9].ToString();        //   Print on Remote Printer 11 
            string P10 = Flag2_Val[10].ToString();    //   Print on Remote Printer 10
            string P11 = Flag2_Val[11].ToString();    //   Print on Remote Printer 9
            string P12 = Flag2_Val[12].ToString();    //   Print on Remote Printer 8
            string P13 = Flag2_Val[13].ToString();    //   Print on Remote Printer 7
            string P14 = Flag2_Val[14].ToString();    //   Print on Remote Printer 6
            string P15 = Flag2_Val[15].ToString();    //   Print on Remote Printer 5
            string P16 = Flag2_Val[16].ToString();    //   Print on Remote Printer 4
            string P17 = Flag2_Val[17].ToString();    //   Print on Remote Printer 3
            string P18 = Flag2_Val[18].ToString();    //   Print on Remote Printer 2 
            string P19 = Flag2_Val[19].ToString();    //   Print on Remote Printer 1

            // Assign Values to Checkbox : 
            if (P0.Equals("1"))
            {
                chk2Invoice2.Checked = true;
            }
            else
            {
                chk2Invoice2.Checked = false;
            }

            if (P1.Equals("1"))
            {
                chk2RP19.Checked = true;
            }
            else
            {
                if (chkVP19.Checked == true)
                {

                    chk2RP19.Checked = false;
                    chk2RP19.Visible = true;
                    lblLPrinter19.Visible = true;
                }
                else
                {
                    chk2RP19.Checked = false;
                    chk2RP19.Visible = false;
                    lblLPrinter19.Visible = false;

                }



            }
            if (P2.Equals("1"))
            {
                chk2RP18.Checked = true;

            }
            else
            {

                if (chkVP18.Checked == true)
                {

                    chk2RP18.Checked = false;
                    chk2RP18.Visible = true;
                    lblLPrinter18.Visible = true;
                }
                else
                {
                    chk2RP18.Checked = false;
                    chk2RP18.Visible = false;
                    lblLPrinter18.Visible = false;
                }





            }

            if (P3.Equals("1"))
            {
                chk2RP17.Checked = true;

            }
            else
            {

                if (chkVP17.Checked == true)
                {

                    chk2RP17.Checked = false;
                    chk2RP17.Visible = true;
                    lblLPrinter17.Visible = true;
                }
                else
                {
                    chk2RP17.Checked = false;
                    chk2RP17.Visible = false;
                    lblLPrinter17.Visible = false;
                }





            }

            if (P4.Equals("1"))
            {
                chk2RP16.Checked = true;

            }
            else
            {

                if (chkVP16.Checked == true)
                {

                    chk2RP16.Checked = false;
                    chk2RP16.Visible = true;
                    lblLPrinter16.Visible = true;
                }
                else
                {
                    chk2RP16.Checked = false;
                    chk2RP16.Visible = false;
                    lblLPrinter16.Visible = false;
                }




            }

            if (P5.Equals("1"))
            {
                chk2RP15.Checked = true;

            }
            else
            {

                if (chkVP15.Checked == true)
                {

                    chk2RP15.Checked = false;
                    chk2RP15.Visible = true;
                    lblLPrinter15.Visible = true;
                }
                else
                {
                    chk2RP15.Checked = false;
                    chk2RP15.Visible = false;
                    lblLPrinter15.Visible = false;
                }

            }


            if (P6.Equals("1"))
            {
                chk2RP14.Checked = true;

            }
            else
            {
                if (chkVP14.Checked == true)
                {

                    chk2RP14.Checked = false;
                    chk2RP14.Visible = true;
                    lblLPrinter14.Visible = true;
                }
                else
                {
                    chk2RP14.Checked = false;
                    chk2RP14.Visible = false;
                    lblLPrinter14.Visible = false;
                }



            }


            if (P7.Equals("1"))
            {
                chk2RP13.Checked = true;

            }
            else
            {

                if (chkVP13.Checked == true)
                {

                    chk2RP13.Checked = false;
                    chk2RP13.Visible = true;
                    lblLPrinter13.Visible = true;
                }
                else
                {
                    chk2RP13.Checked = false;
                    chk2RP13.Visible = false;
                    lblLPrinter13.Visible = false;
                }




            }

            if (P8.Equals("1"))
            {
                chk2RP12.Checked = true;

            }
            else
            {


                if (chkVP12.Checked == true)
                {

                    chk2RP12.Checked = false;
                    chk2RP12.Visible = true;
                    lblLPrinter12.Visible = true;
                }
                else
                {
                    chk2RP12.Checked = false;
                    chk2RP12.Visible = false;
                    lblLPrinter12.Visible = false;
                }



            }



            if (P9.Equals("1"))
            {
                chk2RP11.Checked = true;

            }
            else
            {

                if (chkVP11.Checked == true)
                {

                    chk2RP11.Checked = false;
                    chk2RP11.Visible = true;
                    lblLPrinter11.Visible = true;
                }
                else
                {
                    chk2RP11.Checked = false;
                    chk2RP11.Visible = false;
                    lblLPrinter11.Visible = false;
                }



            }

            if (P10.Equals("1"))
            {
                chk2RP10.Checked = true;

            }
            else
            {

                if (chkVP10.Checked == true)
                {

                    chk2RP10.Checked = false;
                    chk2RP10.Visible = true;
                    lblLPrinter10.Visible = true;
                }
                else
                {
                    chk2RP10.Checked = false;
                    chk2RP10.Visible = false;
                    lblLPrinter10.Visible = false;
                }


            }

            if (P11.Equals("1"))
            {
                chk2RP9.Checked = true;

            }
            else
            {

                if (chkVP9.Checked == true)
                {

                    chk2RP9.Checked = false;
                    chk2RP9.Visible = true;
                    lblLPrinter9.Visible = true;
                }
                else
                {
                    chk2RP9.Checked = false;
                    chk2RP9.Visible = false;
                    lblLPrinter9.Visible = false;
                }



            }
            if (P12.Equals("1"))
            {
                chk2RP8.Checked = true;

            }
            else
            {

                if (chkVP8.Checked == true)
                {

                    chk2RP8.Checked = false;
                    chk2RP8.Visible = true;
                    lblLPrinter8.Visible = true;
                }
                else
                {
                    chk2RP8.Checked = false;
                    chk2RP8.Visible = false;
                    lblLPrinter8.Visible = false;
                }




            }
            if (P13.Equals("1"))
            {
                chk2RP7.Checked = true;
            }
            else
            {

                if (chkVP7.Checked == true)
                {

                    chk2RP7.Checked = false;
                    chk2RP7.Visible = true;
                    lblLPrinter7.Visible = true;
                }
                else
                {
                    chk2RP7.Checked = false;
                    chk2RP7.Visible = false;
                    lblLPrinter7.Visible = false;
                }


            }
            if (P14.Equals("1"))
            {
                chk2RP6.Checked = true;
            }
            else
            {

                if (chkVP6.Checked == true)
                {

                    chk2RP6.Checked = false;
                    chk2RP6.Visible = true;
                    lblLPrinter6.Visible = true;
                }
                else
                {
                    chk2RP6.Checked = false;
                    chk2RP6.Visible = false;
                    lblLPrinter6.Visible = false;
                }



            }

            if (P15.Equals("1"))
            {
                chk2RP5.Checked = true;
            }
            else
            {

                if (chkVP5.Checked == true)
                {
                    chk2RP5.Checked = false;
                    chk2RP5.Visible = true;
                    lblLPrinter5.Visible = true;
                }
                else
                {
                    chk2RP5.Checked = false;
                    chk2RP5.Visible = false;
                    lblLPrinter5.Visible = false;
                }



            }

            if (P16.Equals("1"))
            {
                chk2RP4.Checked = true;
            }
            else
            {


                if (chkVP4.Checked == true)
                {
                    chk2RP4.Checked = false;
                    chk2RP4.Visible = true;
                    lblLPrinter4.Visible = true;
                }
                else
                {
                    chk2RP4.Checked = false;
                    chk2RP4.Visible = false;
                    lblLPrinter4.Visible = false;
                }



            }

            if (P17.Equals("1"))
            {
                chk2RP3.Checked = true;
            }
            else
            {

                if (chkVP3.Checked == true)
                {
                    chk2RP3.Checked = false;
                    chk2RP3.Visible = true;
                    lblLPrinter3.Visible = true;
                }
                else
                {
                    chk2RP3.Checked = false;
                    chk2RP3.Visible = false;
                    lblLPrinter3.Visible = false;
                }



            }

            if (P18.Equals("1"))
            {
                chk2RP2.Checked = true;
            }
            else
            {


                if (chkVP2.Checked == true)
                {
                    chk2RP2.Checked = false;
                    chk2RP2.Visible = true;
                    lblLPrinter2.Visible = true;
                }
                else
                {
                    chk2RP2.Checked = false;
                    chk2RP2.Visible = false;
                    lblLPrinter2.Visible = false;
                }


            }
            if (P19.Equals("1"))
            {
                chk2RP1.Checked = true;

            }
            else
            {

                if (chkVP1.Checked == true)
                {
                    chk2RP1.Checked = false;
                    chk2RP1.Visible = true;
                    lblLPrinter1.Visible = true;
                }
                else
                {
                    chk2RP1.Checked = false;
                    chk2RP1.Visible = false;
                    lblLPrinter1.Visible = false;
                }



            }







            // Load Price Flage of Price1,Price2,Price3,Price4


            #region   Load the  Price1 Flag 

            string Price1query = "select Price_Flag from  {0}.PriceFlag where inventoryid=@inventoryid;";
            string Price1command = string.Format(Price1query, BranchAlias);
            MySqlParameter[] Price1parameters =
                  {
                     new MySqlParameter("@inventoryid",GInventoryID),

                  };
            string Price1ChkBoxVal = ObjMain.NewExecuteScalar(Price1command, Price1parameters);


            if (Price1ChkBoxVal.Equals("0"))
            {
                chkPrice1.Checked = false;
            }
            else if (Price1ChkBoxVal.Equals("1"))
            {
                chkPrice1.Checked = true;
            }
            #endregion

            #region   Load the  Price2 Flag 

            string Price2query = "select Price2_Flag from  {0}.PriceFlag where inventoryid=@inventoryid;";
            string Price2command = string.Format(Price2query, BranchAlias);
            MySqlParameter[] Price2parameters =
                  {
                     new MySqlParameter("@inventoryid",GInventoryID),

                  };
            string Price2ChkBoxVal = ObjMain.NewExecuteScalar(Price2command, Price2parameters);


            if (Price2ChkBoxVal.Equals("0"))
            {
                chkPrice2.Checked = false;
            }
            else if (Price2ChkBoxVal.Equals("1"))
            {
                chkPrice2.Checked = true;
            }
            #endregion

            #region   Load the  Price3 Flag 

            string Price3query = "select Price3_Flag from  {0}.PriceFlag where inventoryid=@inventoryid;";
            string Price3command = string.Format(Price3query, BranchAlias);
            MySqlParameter[] Price3parameters =
                  {
                     new MySqlParameter("@inventoryid",GInventoryID),

                  };
            string Price3ChkBoxVal = ObjMain.NewExecuteScalar(Price3command, Price3parameters);


            if (Price3ChkBoxVal.Equals("0"))
            {
                chkPrice3.Checked = false;
            }
            else if (Price3ChkBoxVal.Equals("1"))
            {
                chkPrice3.Checked = true;
            }
            #endregion

            #region   Load the  Price4 Flag 

            string Price4query = "select Price4_Flag from  {0}.PriceFlag where inventoryid=@inventoryid;";
            string Price4command = string.Format(Price4query, BranchAlias);
            MySqlParameter[] Price4parameters =
                  {
                     new MySqlParameter("@inventoryid",GInventoryID),

                  };
            string Price4ChkBoxVal = ObjMain.NewExecuteScalar(Price4command, Price4parameters);


            if (Price4ChkBoxVal.Equals("0"))
            {
                chkPrice4.Checked = false;
            }
            else if (Price4ChkBoxVal.Equals("1"))
            {
                chkPrice4.Checked = true;
            }
            #endregion




            txtReorder.Text = GReorderLevel;
            txtMaximum.Text = GMaximumLevel;
            txtSafty.Text = GSafetyLevel;
            string imageValQry = "select ImagePath from  {0}.inventory where Inventoryid={1} ;";
            string command_ImageVal = string.Format(imageValQry, Cmb_BranchName, txtReadInventroyId.Text.ToString().Trim());
            ImageVal = ObjMain.ExecuteScalar(command_ImageVal);

            IsExistImagePath.Value = ImageVal;







            if (ImageVal != "")
            {
                lblImageError.Text = " Image Already Updated -This Field for ' WebOrdering' ";
            }
            else
            {


            }





        }

        public void ShowInventoryNew()
        {
            // xss Prevention enabled 
            // Page.ClientScript.RegisterStartupScript(this.GetType(), "hash", "location.hash = '#Inventoryx';", true);

            ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "MyFun1", "disableDiv();", true);
            #region  Validation Between HQ Branch and Normal Branch 
            // This will Return Branch FullName 
            if (BranchFullName == "HQ")
            {
                BranchAlias = Session["Branch_HQ"].ToString();
            }
            else
            {

                BranchAlias = ActiveCallvalue;

            }
            #endregion

            // Assign s3 realted Parameter values 
            lblclientname.Text = Session["CM_ID"].ToString();
            lblstorename.Text = BranchAlias;

            GInventoryID = DTInvInfo.Rows[0]["InventoryID"].ToString();
            GInventoryName = DTInvInfo.Rows[0]["InventoryName"].ToString();
            GDescription = DTInvInfo.Rows[0]["Description"].ToString();
            GCategoryID = DTInvInfo.Rows[0]["CategoryID"].ToString();
            GClass = DTInvInfo.Rows[0]["Class"].ToString();
            GUnit = DTInvInfo.Rows[0]["Unit"].ToString();
            GPrice = DTInvInfo.Rows[0]["Price"].ToString();
            GPrice2 = DTInvInfo.Rows[0]["Price2"].ToString();
            GPrice3 = DTInvInfo.Rows[0]["Price3"].ToString();
            GPrice4 = DTInvInfo.Rows[0]["Price4"].ToString();

            GGroup1 = DTInvInfo.Rows[0]["Group1"].ToString();
            string Groupid1query = "select Groupid from {0}.group1  where GroupName='{1}' ;";
            string command1 = string.Format(Groupid1query, BranchAlias, GGroup1.ToString().Trim());
            GroupID1 = ObjMain.ExecuteScalar(command1);

            GGroup2 = DTInvInfo.Rows[0]["Group2"].ToString();

            string GroupID2_Query = "select Groupid from {0}.group2  where GroupName='{1}';";
            string command2 = string.Format(GroupID2_Query, BranchAlias, GGroup2.ToString().Trim());
            GroupID2 = ObjMain.ExecuteScalar(command2);
            GGroup3 = DTInvInfo.Rows[0]["Group3"].ToString();

            string GroupID3_Query = "select Groupid from {0}.group3  where GroupName='{1}';";
            string command3 = string.Format(GroupID3_Query, BranchAlias, GGroup3.ToString().Trim());

            GroupID3 = ObjMain.ExecuteScalar(command3);
            GGroup4 = DTInvInfo.Rows[0]["Group4"].ToString();

            string GroupID4_Query = "select Groupid from {0}.group4  where GroupName='{1}';";
            string commad4 = string.Format(GroupID4_Query, BranchAlias, GGroup4.ToString().Trim());
            GroupID4 = ObjMain.ExecuteScalar(commad4);
            GGroup5 = DTInvInfo.Rows[0]["Group5"].ToString();

            string GroupID5_Query = "select Groupid from {0}.group5  where GroupName='{1}';";
            string command5 = string.Format(GroupID5_Query, BranchAlias, GGroup5.ToString().Trim());
            GroupID5 = ObjMain.ExecuteScalar(command5);


            GFlag1 = DTInvInfo.Rows[0]["Flag1"].ToString();
            GFlag2 = DTInvInfo.Rows[0]["Flag2"].ToString();
            GReorderLevel = DTInvInfo.Rows[0]["ReorderLevel"].ToString();
            GMaximumLevel = DTInvInfo.Rows[0]["MaxiumLevel"].ToString();
            GSafetyLevel = DTInvInfo.Rows[0]["SafetyLevel"].ToString();
            GActive = DTInvInfo.Rows[0]["Active"].ToString();
            //sSpicy = DTInvInfo.Rows[0]["WebIcon1"].ToString();
            //sChef = DTInvInfo.Rows[0]["WebIcon2"].ToString();
            //sBeef = DTInvInfo.Rows[0]["WebIcon3"].ToString();
            //sChicken = DTInvInfo.Rows[0]["WebIcon4"].ToString();
            //sPork = DTInvInfo.Rows[0]["WebIcon5"].ToString();
            sTakeAway = DTInvInfo.Rows[0]["Takeawayflag"].ToString();

            sAvailable = DTInvInfo.Rows[0]["OutofStock"].ToString();
            sShowItem = DTInvInfo.Rows[0]["showitem"].ToString();
            sPromo = DTInvInfo.Rows[0]["Promo"].ToString();
            sGWebPriceCaptionID = DTInvInfo.Rows[0]["webpricecaptionid"].ToString();
            Notes = DTInvInfo.Rows[0]["Notes"].ToString();
            txtNotes.Text = Notes;

            sProductRelationMain = DTInvInfo.Rows[0]["productrelationmain"].ToString();
            sProductRelationNotInculde = DTInvInfo.Rows[0]["productrelationnotinclude"].ToString();


            string Qry_Image = "select substring( I.ImagePath,1) AS ImagePath from {0}.inventory as i  where inventoryid={1}";
            string commandx = string.Format(Qry_Image, BranchAlias, GInventoryID);
            DTImageResult = ObjCloudMain.GetData_DT(commandx);

            


            DTImageResult.Rows[0]["ImagePath"] = DTImageResult.Rows[0]["ImagePath"] + "123";
            dtimg.DataSource = DTImageResult;
            dtimg.DataBind();
            



            if (sSpicy == "1")
            {
                chkSpicy.Checked = true;
            }
            else
            {
                chkSpicy.Checked = false;
            }

            if (sChef == "1")
            {
                chkChef.Checked = true;
            }
            else
            {
                chkChef.Checked = false;
            }

            if (sBeef == "1")
            {
                chkBeef.Checked = true;
            }
            else
            {
                chkBeef.Checked = false;
            }

            if (sChicken == "1")
            {
                chkChicken.Checked = true;
            }
            else
            {
                chkChicken.Checked = false;
            }

            if (sPork == "1")
            {
                chkPork.Checked = true;
            }
            else
            {
                chkPork.Checked = false;
            }

            if (sTakeAway == "1")
            {
                chkTA.Checked = true;
            }
            else
            {
                chkTA.Checked = false;
            }

            //Assigning values to form fields



            txtReadInventroyId.Text = GInventoryID;
            txtReadInventroyId.Enabled = false;
            txtReadInventroyId.CssClass = "form-control";

            txtInventoryName.Text = GInventoryName;
            txtMName.Text = txtInventoryName.Text;  //Misc
            
            txtDescription.Text = GDescription;
            txtMDesc.Text = txtDescription.Text; //Misc
            
            cmbCategoryName.SelectedIndex = cmbCategoryName.Items.IndexOf(cmbCategoryName.Items.FindByValue(GCategoryID));
            cmbClass.SelectedIndex = cmbClass.Items.IndexOf(cmbClass.Items.FindByValue(GClass));

            //GET PRICE CAPTION TYPE
            string pricecaptionQry = "Select PriceCaptionName from {0}.WebPriceCaption where ID = {1} ; ";
            string command_Pricecaption = string.Format(pricecaptionQry, BranchAlias, sGWebPriceCaptionID);
            RWebPriceCaptionID = ObjCloudMain.ExecuteScalar(command_Pricecaption);//JOHN ADDED ON 13-JAN-2021
            cmbPriceTypeCaption.SelectedIndex = cmbPriceTypeCaption.Items.IndexOf(cmbPriceTypeCaption.Items.FindByValue(RWebPriceCaptionID));
            // Get Unitid 

            string unitidQry = "select unitid from {0}.inventoryunits where Unit='{1}';";
            string command_Unitid = string.Format(unitidQry, BranchAlias, GUnit);
            RUnitids = ObjCloudMain.ExecuteScalar(command_Unitid);


            cmbUnits.SelectedIndex = cmbUnits.Items.IndexOf(cmbUnits.Items.FindByValue(RUnitids));
            txtPrice1.Text = GPrice;
            txtPrice2.Text = GPrice2;
            txtPrice3.Text = GPrice3;
            txtPrice4.Text = GPrice4;
            cmbGroup1.SelectedIndex = cmbGroup1.Items.IndexOf(cmbGroup1.Items.FindByValue(GroupID1));
            cmbGroup2.SelectedIndex = cmbGroup2.Items.IndexOf(cmbGroup2.Items.FindByValue(GroupID2));
            cmbGroup3.SelectedIndex = cmbGroup3.Items.IndexOf(cmbGroup3.Items.FindByValue(GroupID3));
            cmbGroup4.SelectedIndex = cmbGroup4.Items.IndexOf(cmbGroup4.Items.FindByValue(GroupID4));
            cmbGroup5.SelectedIndex = cmbGroup5.Items.IndexOf(cmbGroup5.Items.FindByValue(GroupID5));

            // Get the Flag1 Values - Tax Setting 
            char[] Flag_Val = GFlag1.ToCharArray();

            string c0 = Flag_Val[0].ToString();  //  1: Inventory Flag ; 0:Category Flag
            string c1 = Flag_Val[1].ToString();  //  Always : 0
            string c2 = Flag_Val[2].ToString();  //  Tax Rate 6
            string c3 = Flag_Val[3].ToString();  //  Tax Rate 5
            string c4 = Flag_Val[4].ToString();  //  Tax Rate 4
            string c5 = Flag_Val[5].ToString();  //  Tax Rate 3 
            string c6 = Flag_Val[6].ToString();  //  Scv.C
            string c7 = Flag_Val[7].ToString();  //  GST 


            // 1: Inventory Flag ; 0:Category Flag  in New Checkbox for it 

            if (c0.Equals("1"))
            {
                ChkKeyValueTax.Checked = true;
            }
            else
            {
                ChkKeyValueTax.Checked = false;
            }



            // Assgin values to Checkbox : 
            if (c0.Equals("1"))
            {
                chk2InventoryCate.Checked = true;
            }
            else
            {
                chk2InventoryCate.Checked = false;
            }


            if (c1.Equals("1"))
            {
                chk2Always.Checked = true;
            }
            else
            {
                chk2Always.Checked = false;
            }

            if (c2.Equals("1"))
            {
                chk2TaxRate6.Checked = true;
            }
            else
            {
                chk2TaxRate6.Checked = false;
            }

            if (c3.Equals("1"))
            {
                chk2TaxRate5.Checked = true;
            }
            else
            {
                chk2TaxRate5.Checked = false;
            }

            if (c4.Equals("1"))
            {
                chk2TaxRate4.Checked = true;
            }
            else
            {
                chk2TaxRate4.Checked = false;
            }

            if (c5.Equals("1"))
            {
                chk2TaxRate3.Checked = true;
            }
            else
            {
                chk2TaxRate3.Checked = false;
            }


            if (c6.Equals("1"))
            {
                chk2GST.Checked = true;
            }
            else
            {
                chk2GST.Checked = false;
            }

            if (c7.Equals("1"))
            {
                chk2scvc.Checked = true;
            }
            else
            {
                chk2scvc.Checked = false;
            }


            //if (GActive.Equals("1")) //john hide on 18-Dec-2020
            //{
            //    chkActiveStatus.Checked = true;
            //}
            //else if (GActive.Equals("-1"))
            //{
            //    chkActiveStatus.Checked = true;
            //}
            //else if (GActive.Equals("0"))
            //{
            //    chkActiveStatus.Checked = false;
            //}

            if ((GActive == "True") || (GActive.Equals("1")) || (GActive.Equals("-1")))      //John added on 18-Dec-2020
            {
                chkActiveStatus.Checked = true;
            }
            else if ((GActive == "False") || (GActive.Equals("0")))
            {
                chkActiveStatus.Checked = false;
            }

            // Not Available

            if (sAvailable.Equals("1"))
            {
                ChkNotAvailable.Checked = true;

            }
            else if (sAvailable.Equals("0"))
            {
                ChkNotAvailable.Checked = false;
            }
            // ShowItem 


            if (sShowItem.Equals("1"))
            {
                ChkShowItem.Checked = true;

            }
            else if (sShowItem.Equals("0"))
            {
                ChkShowItem.Checked = false;
            }

            //product relation main
            if (sProductRelationMain.Equals("1"))
            {
                chkMainProductRelation.Checked = true;

            }
            else if (sProductRelationMain.Equals("0"))
            {
                chkMainProductRelation.Checked = false;
            }

            //product relation not include
            if (sProductRelationNotInculde.Equals("1"))
            {
                chkNotIncludeProductRelation.Checked = true;

            }
            else if (sProductRelationNotInculde.Equals("0"))
            {
                chkNotIncludeProductRelation.Checked = false;
            }

            // Promo 
            if (sPromo.Equals("1"))
            {
                chkPromo.Checked = true;
            }
            else
            {
                chkPromo.Checked = false;
            }
            // Assign Combobox value form New TAX: 

            if (c2.Equals("1"))
            {
                chkTaxRate6.Checked = true;

            }
            else
            {
                chkTaxRate6.Checked = false;
            }

            if (c3.Equals("1"))
            {
                chkTaxRate5.Checked = true;
            }
            else
            {
                chkTaxRate5.Checked = false;
            }

            if (c4.Equals("1"))
            {
                chkTax4.Checked = true;
            }
            else
            {
                chkTax4.Checked = false;
            }

            if (c5.Equals("1"))
            {
                chkTax3.Checked = true;
            }
            else
            {
                chkTax3.Checked = false;
            }

            if (c6.Equals("1"))
            {
                chkTax2.Checked = true;
            }
            else
            {
                chkTax2.Checked = false;
            }

            if (c7.Equals("1"))
            {
                chkTax1.Checked = true;
            }
            else
            {
                chkTax1.Checked = false;
            }

            //  Get the Flag2 Values : Printer Settings

            char[] Flag2_Val = GFlag2.ToCharArray();

            string P0 = Flag2_Val[0].ToString();           //1: Inventory Flag ; 0:Category Flag  
            string P1 = Flag2_Val[1].ToString();          // Print on Remote Printer 19                               
            string P2 = Flag2_Val[2].ToString();          // Print on Remote Printer 18  
            string P3 = Flag2_Val[3].ToString();         //  Print on Remote Printer 17  
            string P4 = Flag2_Val[4].ToString();         //  Print on Remote Printer 16  
            string P5 = Flag2_Val[5].ToString();        //   Print on Remote Printer 15  
            string P6 = Flag2_Val[6].ToString();        //   Print on Remote Printer 14   
            string P7 = Flag2_Val[7].ToString();        //   Print on Remote Printer 13  
            string P8 = Flag2_Val[8].ToString();        //   Print on Remote Printer 12 
            string P9 = Flag2_Val[9].ToString();        //   Print on Remote Printer 11 
            string P10 = Flag2_Val[10].ToString();    //   Print on Remote Printer 10
            string P11 = Flag2_Val[11].ToString();    //   Print on Remote Printer 9
            string P12 = Flag2_Val[12].ToString();    //   Print on Remote Printer 8
            string P13 = Flag2_Val[13].ToString();    //   Print on Remote Printer 7
            string P14 = Flag2_Val[14].ToString();    //   Print on Remote Printer 6
            string P15 = Flag2_Val[15].ToString();    //   Print on Remote Printer 5
            string P16 = Flag2_Val[16].ToString();    //   Print on Remote Printer 4
            string P17 = Flag2_Val[17].ToString();    //   Print on Remote Printer 3
            string P18 = Flag2_Val[18].ToString();    //   Print on Remote Printer 2 
            string P19 = Flag2_Val[19].ToString();    //   Print on Remote Printer 1

            // Assign Values to Checkbox : 
            if (P0.Equals("1"))
            {
                chk2Invoice2.Checked = true;
            }
            else
            {
                chk2Invoice2.Checked = false;
            }

            if (P1.Equals("1"))
            {
                chk2RP19.Checked = true;
            }
            else
            {
                if (chkVP19.Checked == true)
                {

                    chk2RP19.Checked = false;
                    chk2RP19.Visible = true;
                    lblLPrinter19.Visible = true;
                }
                else
                {
                    chk2RP19.Checked = false;
                    chk2RP19.Visible = false;
                    lblLPrinter19.Visible = false;

                }



            }
            if (P2.Equals("1"))
            {
                chk2RP18.Checked = true;

            }
            else
            {

                if (chkVP18.Checked == true)
                {

                    chk2RP18.Checked = false;
                    chk2RP18.Visible = true;
                    lblLPrinter18.Visible = true;
                }
                else
                {
                    chk2RP18.Checked = false;
                    chk2RP18.Visible = false;
                    lblLPrinter18.Visible = false;
                }





            }

            if (P3.Equals("1"))
            {
                chk2RP17.Checked = true;

            }
            else
            {

                if (chkVP17.Checked == true)
                {

                    chk2RP17.Checked = false;
                    chk2RP17.Visible = true;
                    lblLPrinter17.Visible = true;
                }
                else
                {
                    chk2RP17.Checked = false;
                    chk2RP17.Visible = false;
                    lblLPrinter17.Visible = false;
                }





            }

            if (P4.Equals("1"))
            {
                chk2RP16.Checked = true;

            }
            else
            {

                if (chkVP16.Checked == true)
                {

                    chk2RP16.Checked = false;
                    chk2RP16.Visible = true;
                    lblLPrinter16.Visible = true;
                }
                else
                {
                    chk2RP16.Checked = false;
                    chk2RP16.Visible = false;
                    lblLPrinter16.Visible = false;
                }




            }

            if (P5.Equals("1"))
            {
                chk2RP15.Checked = true;

            }
            else
            {

                if (chkVP15.Checked == true)
                {

                    chk2RP15.Checked = false;
                    chk2RP15.Visible = true;
                    lblLPrinter15.Visible = true;
                }
                else
                {
                    chk2RP15.Checked = false;
                    chk2RP15.Visible = false;
                    lblLPrinter15.Visible = false;
                }

            }


            if (P6.Equals("1"))
            {
                chk2RP14.Checked = true;

            }
            else
            {
                if (chkVP14.Checked == true)
                {

                    chk2RP14.Checked = false;
                    chk2RP14.Visible = true;
                    lblLPrinter14.Visible = true;
                }
                else
                {
                    chk2RP14.Checked = false;
                    chk2RP14.Visible = false;
                    lblLPrinter14.Visible = false;
                }



            }


            if (P7.Equals("1"))
            {
                chk2RP13.Checked = true;

            }
            else
            {

                if (chkVP13.Checked == true)
                {

                    chk2RP13.Checked = false;
                    chk2RP13.Visible = true;
                    lblLPrinter13.Visible = true;
                }
                else
                {
                    chk2RP13.Checked = false;
                    chk2RP13.Visible = false;
                    lblLPrinter13.Visible = false;
                }




            }

            if (P8.Equals("1"))
            {
                chk2RP12.Checked = true;

            }
            else
            {


                if (chkVP12.Checked == true)
                {

                    chk2RP12.Checked = false;
                    chk2RP12.Visible = true;
                    lblLPrinter12.Visible = true;
                }
                else
                {
                    chk2RP12.Checked = false;
                    chk2RP12.Visible = false;
                    lblLPrinter12.Visible = false;
                }



            }



            if (P9.Equals("1"))
            {
                chk2RP11.Checked = true;

            }
            else
            {

                if (chkVP11.Checked == true)
                {

                    chk2RP11.Checked = false;
                    chk2RP11.Visible = true;
                    lblLPrinter11.Visible = true;
                }
                else
                {
                    chk2RP11.Checked = false;
                    chk2RP11.Visible = false;
                    lblLPrinter11.Visible = false;
                }



            }

            if (P10.Equals("1"))
            {
                chk2RP10.Checked = true;

            }
            else
            {

                if (chkVP10.Checked == true)
                {

                    chk2RP10.Checked = false;
                    chk2RP10.Visible = true;
                    lblLPrinter10.Visible = true;
                }
                else
                {
                    chk2RP10.Checked = false;
                    chk2RP10.Visible = false;
                    lblLPrinter10.Visible = false;
                }


            }

            if (P11.Equals("1"))
            {
                chk2RP9.Checked = true;

            }
            else
            {

                if (chkVP9.Checked == true)
                {

                    chk2RP9.Checked = false;
                    chk2RP9.Visible = true;
                    lblLPrinter9.Visible = true;
                }
                else
                {
                    chk2RP9.Checked = false;
                    chk2RP9.Visible = false;
                    lblLPrinter9.Visible = false;
                }



            }
            if (P12.Equals("1"))
            {
                chk2RP8.Checked = true;

            }
            else
            {

                if (chkVP8.Checked == true)
                {

                    chk2RP8.Checked = false;
                    chk2RP8.Visible = true;
                    lblLPrinter8.Visible = true;
                }
                else
                {
                    chk2RP8.Checked = false;
                    chk2RP8.Visible = false;
                    lblLPrinter8.Visible = false;
                }




            }
            if (P13.Equals("1"))
            {
                chk2RP7.Checked = true;
            }
            else
            {

                if (chkVP7.Checked == true)
                {

                    chk2RP7.Checked = false;
                    chk2RP7.Visible = true;
                    lblLPrinter7.Visible = true;
                }
                else
                {
                    chk2RP7.Checked = false;
                    chk2RP7.Visible = false;
                    lblLPrinter7.Visible = false;
                }


            }
            if (P14.Equals("1"))
            {
                chk2RP6.Checked = true;
            }
            else
            {

                if (chkVP6.Checked == true)
                {

                    chk2RP6.Checked = false;
                    chk2RP6.Visible = true;
                    lblLPrinter6.Visible = true;
                }
                else
                {
                    chk2RP6.Checked = false;
                    chk2RP6.Visible = false;
                    lblLPrinter6.Visible = false;
                }



            }

            if (P15.Equals("1"))
            {
                chk2RP5.Checked = true;
            }
            else
            {

                if (chkVP5.Checked == true)
                {
                    chk2RP5.Checked = false;
                    chk2RP5.Visible = true;
                    lblLPrinter5.Visible = true;
                }
                else
                {
                    chk2RP5.Checked = false;
                    chk2RP5.Visible = false;
                    lblLPrinter5.Visible = false;
                }



            }

            if (P16.Equals("1"))
            {
                chk2RP4.Checked = true;
            }
            else
            {


                if (chkVP4.Checked == true)
                {
                    chk2RP4.Checked = false;
                    chk2RP4.Visible = true;
                    lblLPrinter4.Visible = true;
                }
                else
                {
                    chk2RP4.Checked = false;
                    chk2RP4.Visible = false;
                    lblLPrinter4.Visible = false;
                }



            }

            if (P17.Equals("1"))
            {
                chk2RP3.Checked = true;
            }
            else
            {

                if (chkVP3.Checked == true)
                {
                    chk2RP3.Checked = false;
                    chk2RP3.Visible = true;
                    lblLPrinter3.Visible = true;
                }
                else
                {
                    chk2RP3.Checked = false;
                    chk2RP3.Visible = false;
                    lblLPrinter3.Visible = false;
                }



            }

            if (P18.Equals("1"))
            {
                chk2RP2.Checked = true;
            }
            else
            {


                if (chkVP2.Checked == true)
                {
                    chk2RP2.Checked = false;
                    chk2RP2.Visible = true;
                    lblLPrinter2.Visible = true;
                }
                else
                {
                    chk2RP2.Checked = false;
                    chk2RP2.Visible = false;
                    lblLPrinter2.Visible = false;
                }


            }
            if (P19.Equals("1"))
            {
                chk2RP1.Checked = true;

            }
            else
            {

                if (chkVP1.Checked == true)
                {
                    chk2RP1.Checked = false;
                    chk2RP1.Visible = true;
                    lblLPrinter1.Visible = true;
                }
                else
                {
                    chk2RP1.Checked = false;
                    chk2RP1.Visible = false;
                    lblLPrinter1.Visible = false;
                }



            }


            txtReorder.Text = GReorderLevel;
            txtMaximum.Text = GMaximumLevel;
            txtSafty.Text = GSafetyLevel;
            string imageValQry = "select ImagePath from  {0}.inventory where Inventoryid={1} ;";
            string command_ImageVal = string.Format(imageValQry, Cmb_BranchName, txtReadInventroyId.Text.ToString().Trim());
            ImageVal = ObjMain.ExecuteScalar(command_ImageVal);

            IsExistImagePath.Value = ImageVal;

            // Clear the Existing session 
            Session["LastValue"] = null;




            if (ImageVal != "")
            {
                lblImageError.Text = " Image Already Updated -This Field for ' WebOrdering' ";
            }
            else
            {


            }



            // Clear the LastBarcode
            Session["LastBarcode"] = null;

        }

        private void RegisterJavsacriptWindowScrollTo(int x, int y)
        {
            ClientScriptManager scriptManager = Page.ClientScript;
            if (!scriptManager.IsClientScriptBlockRegistered(this.GetType(), "WindowScrollTo"))
            {
                StringBuilder scriptBlock = new StringBuilder();
                scriptBlock.AppendLine("Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoaded);");
                scriptBlock.AppendLine("function pageLoaded(sender, args)");
                scriptBlock.AppendLine("{");
                scriptBlock.AppendFormat("  window.scrollTo({0}, {1});\n", x, y);
                scriptBlock.AppendLine("}");
                scriptManager.RegisterStartupScript(this.GetType(), "WindowScrollTo", scriptBlock.ToString(), true);
            }
        }

        protected void cmbBranches_SelectedIndexChanged(object sender, EventArgs e)
        {

            ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "MyFun2", "clearimg();", true);

            if (cmbBranches.SelectedIndex == 1)
            {

                BranchFullName = cmbBranches.SelectedItem.Text;    // This will Return Branch FullName 
                Cmb_BranchName = ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), BranchFullName);
                UPDATEBRANCH(Cmb_BranchName);
                Session["BranchFullName"] = BranchFullName;
                lblSelectedBranchCaption1.Text = BranchFullName;
                lblSelctedBranchCaption2.Text = BranchFullName;
                Session["BranchDB"] = Cmb_BranchName;
                //  this.Page.ClientScript.RegisterStartupScript(this.GetType(), "Javascript", "javascript:GetActiveSession5();", true);
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "MyFun1", "GetActiveSession5();", true);


                





            }
            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



                Rcd_id = ObjMain.ExecuteScalar("select cd_id from portaldb.companydetails where cd_branchid=" + cmbBranches.SelectedItem.Value + " and cd_branchalias='" + BranchAlias + "';");
                RPortalid = ObjMain.ExecuteScalar("select portaltypeid  from portaldb.invoicedetails where cd_id=" + Rcd_id + ";");
                DtLicense = ObjUserBL.GetLicenseDetails(RPortalid);
                Session["BranchFullName"] = BranchFullName;
                lblSelectedBranchCaption1.Text = BranchFullName;
                lblSelctedBranchCaption2.Text = BranchFullName;

                Session["BranchDB"] = BranchAlias;
                // this.Page.ClientScript.RegisterStartupScript(this.GetType(), "Javascript", "javascript:GetActiveSession5();", true);
                ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "MyFun1", "GetActiveSession5();", true);
                

           

            }





            if (cmbBranches.SelectedIndex == 0)
            {
                Response.Write("Inventory.aspx");
            }
            else
            {
                DT = ObjUserBL.GetPageRightsDetailsPIDNew(Session["UserId"].ToString(), PID, cmbBranches.SelectedItem.Value);

                if (DT.Rows.Count > 0)
                {
                    Page_Acess = DT.Rows[0]["Acess_status"].ToString();
                    Read_Acess = DT.Rows[0]["Read_Access"].ToString();
                    Write_Acess = DT.Rows[0]["Write_Access"].ToString();
                    Isdowld_Acess = DT.Rows[0]["IDwld_Access"].ToString();
                    Session["Page_Acess"] = Page_Acess;
                    Session["Read_Acess"] = Read_Acess;
                    Session["Write_Acess"] = Write_Acess;
                    Session["Isdowld_Acess"] = Isdowld_Acess;
                }





                if (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
                        string chk_Condition = ObjMain.ExecuteScalar("select IsWebOrderApp from portaldb.companydetails where  cd_branchAlias='" + BranchAlias + "';");
                        if (chk_Condition.Equals("Y"))
                        {
                            string _inventoryrows = string.Empty;
                            string _priceflagrows = string.Empty;
                            string Inven_sCmd = "Select count(*) as InventoryRows from {0}.Inventory; ";
                            string Invent_command = string.Format(Inven_sCmd, BranchAlias);
                            _inventoryrows = ObjMain.ExecuteScalar(Invent_command);



                            string priceflag_sCmd = "Select count(*) as PriceflagRows from {0}.priceflag; ";
                            string priceflag_command = string.Format(priceflag_sCmd, BranchAlias);
                            _priceflagrows = ObjMain.ExecuteScalar(priceflag_command);

                            if (_inventoryrows != _priceflagrows)
                            {
                                INS_PriceFlage(BranchAlias);
                                INS_WebStock(BranchAlias);
                            }
                        }
                        else
                        { 
                        }

                            // LoadInventoryview();

                        txtEffectiveDt.Text = Curr_DateOnly;
                        LoadGrp1(BranchAlias);
                        LoadGrp2(BranchAlias);
                        LoadGrp3(BranchAlias);
                        LoadGrp4(BranchAlias);
                        LoadGrp5(BranchAlias);
                        LoadCategoryList(BranchAlias);
                        LoadTaxLables();
                        LoadTakeawayCharge(BranchAlias);
                        // Assign s3 realted Parameter values 
                        //clientname.Value = Session["CM_ID"].ToString();
                        lblclientname.Text = Session["CM_ID"].ToString();
                        lblstorename.Text = BranchAlias;

                        btnSubmit.Visible = true;
                        btnSubmit.Enabled = true;

                        //  btnUpdateInv.Enabled = true;
                        //  btnUpdateInv.Visible = true;
                        txtReadInventroyId.Enabled = false;
                        txtReadInventroyId.CssClass = "form-control";
                        UPDATEBRANCH(BranchAlias);
                        Session["BranchFullName"] = BranchFullName;
                        lblSelectedBranchCaption1.Text = BranchFullName;
                        lblSelctedBranchCaption2.Text = BranchFullName;
                        this.Page.ClientScript.RegisterStartupScript(this.GetType(), "Javascript", "javascript:GetActiveSession5();", true);


                      string  key2 = "Initialbranch";
                      string value2 = Server.HtmlEncode(BranchAlias);
                      string      script = $"localStorage.setItem('{key2}', '{value2}');";
                      ScriptManager.RegisterStartupScript(this, this.GetType(), "SetLocalStorage", script, true);

                      #region UnitPrice Hide and Show 




                        string is_view_unitcost = "select inivalue from " + BranchAlias + ".weborderinginisetting where id =82;";
                        string Read_Value_unitcost = ObjMain.ExecuteScalar(is_view_unitcost);
                        string _branch = Session["BranchDB"] != null ? Session["BranchDB"].ToString() : "";
                        ScriptManager.RegisterStartupScript(
                                         this,
                                         this.GetType(),
                                         "Javascript",
                                         $"Loadunitpricelable('{_branch}');",
                                         true
                                     );

                        #endregion



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

                }

                else
                {
                    if (Session["Write_Acess"].ToString() == "N")
                    {
                        //btnShow.Enabled = false;
                        btnSubmit.Enabled = false;
                        btnSubmit.CssClass = "btn btn-primary";
                        //btnShow.CssClass = "btn btn-success active";
                    }
                    else if (Session["Write_Acess"].ToString() == "Y")
                    {
                        //btnShow.Enabled = true;
                        btnSubmit.Enabled = true;
                        btnSubmit.CssClass = "btn btn-primary";
                    }

                    // btnExcel.Enabled = 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
                    lblSelectedBranchCaption1.Text = BranchFullName;
                    lblSelctedBranchCaption2.Text = BranchFullName;

                    string chk_Condition = ObjMain.ExecuteScalar("select IsWebOrderApp from portaldb.companydetails where  cd_branchAlias='" + BranchAlias + "';");
                    if (chk_Condition.Equals("Y"))
                    {


                        string _inventoryrows = string.Empty;
                        string _priceflagrows = string.Empty;
                        string Inven_sCmd = "Select count(*) as InventoryRows from {0}.Inventory; ";
                        string Invent_command = string.Format(Inven_sCmd, BranchAlias);
                        _inventoryrows = ObjMain.ExecuteScalar(Invent_command);
                        
                        

                        string priceflag_sCmd = "Select count(*) as PriceflagRows from {0}.priceflag; ";
                        string priceflag_command = string.Format(priceflag_sCmd, BranchAlias);
                        _priceflagrows = ObjMain.ExecuteScalar(priceflag_command);

                        if (_inventoryrows != _priceflagrows)
                        {
                            INS_PriceFlage(BranchAlias);
                            INS_WebStock(BranchAlias);
                        }
                    }
                    else
                    {
                    }



                    // LoadInventoryview();

                    txtEffectiveDt.Text = Curr_DateOnly;
                    LoadGrp1(BranchAlias);
                    LoadGrp2(BranchAlias);
                    LoadGrp3(BranchAlias);
                    LoadGrp4(BranchAlias);
                    LoadGrp5(BranchAlias);
                    LoadCategoryList(BranchAlias);
                    LoadTaxLables();
                    LoadTakeawayCharge(BranchAlias);
                    btnUpdateInv.Visible = false;
                    btnDelete.Visible = false;
                    txtReadInventroyId.Enabled = false;
                    txtReadInventroyId.CssClass = "form-control";
                    BranchFullName = cmbBranches.SelectedItem.Text;
                    UPDATEBRANCH(BranchAlias);



                    string is_view_unitcost = "select inivalue from " + BranchAlias + ".weborderinginisetting where id = 82;";
                    string Read_Value_unitcost = ObjMain.ExecuteScalar(is_view_unitcost);
                    string _branch = Session["BranchDB"] != null ? Session["BranchDB"].ToString() : "";
                    ScriptManager.RegisterStartupScript(
                                         this,
                                         this.GetType(),
                                         "Javascript",
                                         $"Loadunitpricelable('{_branch}');",
                                         true
                                     );


                }
            }



            //  Check the HQ  Condition      

            /*
             string _get_HQ = ObjSel.GetHQ_Status(Session["CM_ID"].ToString());
             if (_get_HQ == "0")
             {

                 UPDATEBRANCH(Cmb_BranchName);
                 Response.Redirect(Request.RawUrl);
             }
             else if (_get_HQ == "1")
             {

             }
            */

            ClearInvForm();
        }

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

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

            txtSearchVal.CssClass = "form-control";
            Page.ClientScript.RegisterStartupScript(this.GetType(), "hash", "location.hash = '#Inventoryx';", true);

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

            cmbSearch.SelectedIndex = 0;
            txtSearchVal.Text = "";
            grdInventoryView.DataSource = null;
            grdInventoryView.DataBind();
            dtimg.DataSource = null;
            dtimg.DataBind();

            ClearInvForm();
           
           

            


          //  Response.Redirect(HttpContext.Current.Request.Url.ToString(), true);

        }

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

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

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

            }

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

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

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


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

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


        }
        //public override void VerifyRenderingInServerForm(Control control)
        //{
        //    /* Confirms that an HtmlForm control is rendered for the specified ASP.NET
        //       server control at run time. */
        //}

        [System.Web.Services.WebMethod]
        public static string GetSessionValue5(string key)
        {
            return HttpContext.Current.Session[key].ToString();
        }

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

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

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

            }


            string Val3 = "Yes";
            if (FileUpload1.HasFile)
            {
                string FileName = Path.GetFileName(FileUpload1.PostedFile.FileName);
                string Extension = Path.GetExtension(FileUpload1.PostedFile.FileName);
                string FolderPath = ConfigurationManager.AppSettings["FolderPath"];
                string FilePath = Server.MapPath(FolderPath + FileName);
                FileUpload1.SaveAs(FilePath);
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "return CloseImportExportModal();", true);

                Import_To_Grid(FilePath, Extension, Val3);
                this.Page.ClientScript.RegisterStartupScript(this.GetType(), "Javascript", "javascript:GetActiveSession5();", true);


            }
            else
            {
                
                Log.Info(Curr_Date+": " + " Porvide the Excel File to upload."  + "Database-> "+ Session["Active_Branch"].ToString());
                this.Page.ClientScript.RegisterStartupScript(this.GetType(), "Javascript", "javascript:GetActiveSession5();", true);
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Provide Excel File To Upload ') ", true);
            }


        }
        /// <summary>
        /// This Remove image  Previous Approach 
        /// No longer used 
        /// NOT -ACTIVE Function 
        /// </summary>
       /*
        public void RemoveImage()
        {
            BranchFullName = Microsoft.Security.Application.Encoder.HtmlEncode(cmbBranches.SelectedItem.Text);    // This will Return Branch FullName 
            Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);  // This will Return BranchName( Actual Database Name )
            BranchAlias = Cmb_BranchName;

            string ChkQry_Image = "select substring( I.ImagePath,3) AS ImagePath from " + BranchAlias + ".inventory as i  where inventoryid=" + txtReadInventroyId.Text + "";
            string checkImgpath = ObjCloudMain.ExecuteScalar(ChkQry_Image);

            if ((txtReadInventroyId.Text != "") && (checkImgpath != ""))
            {
                string UPT_ImagePath = "Update " + BranchAlias + ".inventory set imagePath='' where inventoryid=" + txtReadInventroyId.Text + ";";
                Z = ObjCloudMain.ExecuteNonQuery(UPT_ImagePath);


                //DTInvInfo = ObjSel.GetInvInfo(BranchAlias, txtBarcode.Text.ToString().Trim());
                //ShowInventory();

                dtimg.DataSource = null;
                dtimg.DataBind();
                lblImageError.Text = string.Empty;
                if (Z > 0)
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('Image Removed! '); ", true);
                }
                else
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('Image Not Removed! ') ", true);
                }

            }
            else
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('No Image to  Remove! '); ", true);
            }
        
        }
       */

        public void LoadImageOnly()
        {


            string imageValQry = "select ImagePath from  {0}.inventory where Inventoryid={1} ;";
            string command_ImageVal = string.Format(imageValQry, Cmb_BranchName, txtReadInventroyId.Text.ToString().Trim());
            ImageVal = ObjMain.ExecuteScalar(command_ImageVal);

            IsExistImagePath.Value = ImageVal;


        }

        public void DeleteImageFromS3(string filename, string bucketname, string storename, string clientname)
        {

            #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

            // Filename - Read from the filedetails table 
            // bucketname - Read from the filedetails table 
            // storeName - Get the Current Branch from the session 
            // clientName - Read cm_d from  filedetails table ( Companymaster Table )

            var client = new RestClient("https://www.suntoyo.online/api/FileService/Delete?fileName=" + filename + "&bucketName=" + bucketname + "&storeName=" + storename + "&clientname=" + clientname + "");
            /*
              # Enable Server Api Path 
              # Disable the Local Api Path              
             */

            // var client = new RestClient("http://18.139.75.241:4545/api/FileService/Delete?fileName=" + filename + "&bucketName=" + bucketname + "&storeName=" + stsorename + "&clientname=" + clientname + "");


            client.Timeout = -1;
            var request = new RestRequest(Method.POST);
            request.AddHeader("Content-Type", "application/x-www-form-urlencoded");
            request.AddParameter("clientname", clientname);
            request.AddParameter("fileName", filename);
            request.AddParameter("bucketName", bucketname);
            request.AddParameter("storeName", storename);
            IRestResponse response = client.Execute(request);
            Console.WriteLine(response.Content);

        }

        public void UpdateImagePathWhileDelete(string inventoryid)
        {
            #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
            int KL = 0;
            string UPTImagePath = "Update " + BranchAlias + ".inventory set imagepath='' where inventoryid=" + inventoryid + " ;";
            KL = ObjMain.ExecuteNonQuery(UPTImagePath);

            if (KL > 0)
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('Image Removed! '); ", true);
            }
            else
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('Image Not Removed! ') ", true);
            }

        }

        protected void btnRemove_Click(object sender, EventArgs e)
        {

            // Prevention SQL Injection : 07-10-21
            // Parameterized Approach 
            // Prevention XSS 
            #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
            // RemoveImage();  Existing Approach 
            // Pass the S3Bucket Parameters to delete 

            //1.FileName 
            //2.BucketName
            //3.StoreName
            //4.ClientName 

            string command = "select substring( I.ImagePath,1) AS ImagePath from {0}.inventory as i  where inventoryid={1}; ";
            string ChkQry_Image = string.Format(command, BranchAlias, txtReadInventroyId.Text);
            string checkImgpath = ObjCloudMain.ExecuteScalar(ChkQry_Image);

            if ((txtReadInventroyId.Text != "") && (checkImgpath != ""))
            {

                DataTable DtS3_Deletable = new DataTable();
                string command_Del = "select * from  {0}.filedetails where inventoryid={1};";
                string Qry_Del = string.Format(command_Del, BranchAlias, txtReadInventroyId.Text);
                string R_filename = string.Empty;
                string R_bucketname = string.Empty;
                string R_storename = string.Empty;
                string R_clientname = string.Empty;

                DtS3_Deletable = ObjMain.GetData_DT(Qry_Del);
                if (DtS3_Deletable.Rows.Count > 0)
                {
                    R_filename = DtS3_Deletable.Rows[0]["fileName"].ToString();
                    R_bucketname = DtS3_Deletable.Rows[0]["BucketName"].ToString();
                    R_storename = DtS3_Deletable.Rows[0]["StoreName"].ToString();
                    R_clientname = DtS3_Deletable.Rows[0]["CompanyName"].ToString();
                    DeleteImageFromS3(R_filename, R_bucketname, R_storename, R_clientname);   // Delete the Image in S3Bucket 
                    UpdateImagePathWhileDelete(txtReadInventroyId.Text);                      // Make the ImagePath Null 



                }

            }
            else
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' No Image To Delete. ') ", true);

            }

            dtimg.DataSource = null;
            dtimg.DataBind();
            lblImageError.Text = string.Empty;

        }

        protected void btnImportMSBarcode_Click(object sender, EventArgs e)
        {
            
            if (FileUploadMasterSlave.HasFile)
            {
                string FileName = Path.GetFileName(FileUploadMasterSlave.PostedFile.FileName);
                string Extension = Path.GetExtension(FileUploadMasterSlave.PostedFile.FileName);
                string FolderPath = ConfigurationManager.AppSettings["FolderPath"];
                string FilePath = Server.MapPath(FolderPath + FileName);
                FileUploadMasterSlave.SaveAs(FilePath);
                Import_To_GridMasterSlave(FilePath, Extension, "Yes");

            }
            else
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Provide Excel File To Upload ') ", true);
            }
        }

        private void Import_To_GridMasterSlave(string FilePath, string Extension, string isHDR)
        {
            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
            }

            string conStr = "";
            switch (Extension)
            {
                case ".xls":    //Excel 97-03
                    conStr = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
                    break;
                case ".xlsx":   //Excel 07
                    conStr = ConfigurationManager.ConnectionStrings["Excel07ConString"].ConnectionString;
                    break;
            }

            conStr = String.Format(conStr, FilePath, isHDR);
            OleDbConnection connExcel = new OleDbConnection(conStr);
            OleDbCommand cmdExcel = new OleDbCommand();
            OleDbDataAdapter oda = new OleDbDataAdapter();
            DataTable dt = new DataTable();
            cmdExcel.Connection = connExcel;
            //Get the name of First Sheet
            connExcel.Open();
            DataTable dtExcelSchema;
            dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
            connExcel.Close();
            //Read Data from First Sheet
            connExcel.Open();
            cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";
            oda.SelectCommand = cmdExcel;
            oda.Fill(dt);
            Session["dt"] = dt;
            foreach (DataRow row in dt.Rows)
            {
                string sMasterbarcode = row["masterbarcode"].ToString();
                string sSlaveBarcode = row["slavebarcode"].ToString();

                if (sMasterbarcode != "")
                {
                    if (CheckSlaveBarcode(BranchAlias, sSlaveBarcode) == "True") //Check if slave barcode if exist inside inventorymulticode
                    {
                        string Command = "Delete from {0}.Inventorymulticode where slavebarcode ='{1}';";
                        string sDeleteSlave = string.Format(Command, BranchAlias, sSlaveBarcode);

                        DeleteMSBarcode = ObjCloudMain.ExecuteNonQuery(sDeleteSlave);
                    }

                    string commandA = "insert into {0}.inventorymulticode(masterbarcode,slavebarcode)values(@masterbarcode,@slavebarcode)";
                    string sInsertMSBarcodeCmd = string.Format(commandA, BranchAlias);
                    MySqlParameter[] parameters =
                   {
                     new MySqlParameter("@masterbarcode",sMasterbarcode),
                     new MySqlParameter("@slavebarcode",sSlaveBarcode),
                    };
                    ImportMSBarcode = ObjMain.ExecuteQuery(sInsertMSBarcodeCmd, parameters);
                }
            }
            connExcel.Close();
            //Bind Data to GridView
            GridView1.Caption = Path.GetFileName(FilePath);
            GridView1.DataSource = dt;
            GridView1.DataBind();
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Master and Slave Imported  Successfully ') ", true);

        }

        public string CheckSlaveBarcode(string sDB, string sBarcode)
        {
            string sResutl = string.Empty;
            string sCmdCheck = "Select * from {0}.inventorymulticode where SlaveBarcode = '{1}' ;";
            string command = string.Format(sCmdCheck, sDB, sBarcode);
            DataTable Dt = new DataTable();
            Dt = ObjMain.GetData_DT(command);
            if (Dt.Rows.Count == 0)
            {
                return "False";
            }
            else
            {
                return "True";
            }
        }

        private void Import_To_Grid(string FilePath, string Extension, string isHDR)
        {
            //if (cmbBranches.Visible == false)
            //{
            //    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;
            //}


            //try
            //{
            //    string conStr = "";
            //    switch (Extension)
            //    {
            //        case ".xls":    //Excel 97-03
            //            conStr = ConfigurationManager.ConnectionStrings["Excel03ConString"].ConnectionString;
            //            break;
            //        case ".xlsx":   //Excel 07
            //            conStr = ConfigurationManager.ConnectionStrings["Excel07ConString"].ConnectionString;
            //            break;
            //    }
            //    conStr = String.Format(conStr, FilePath, isHDR);
            //    OleDbConnection connExcel = new OleDbConnection(conStr);
            //    OleDbCommand cmdExcel = new OleDbCommand();
            //    OleDbDataAdapter oda = new OleDbDataAdapter();
            //    DataTable dt = new DataTable();
            //    cmdExcel.Connection = connExcel;
            //    //Get the name of First Sheet
            //    connExcel.Open();
            //    DataTable dtExcelSchema;
            //    dtExcelSchema = connExcel.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
            //    string SheetName = dtExcelSchema.Rows[0]["TABLE_NAME"].ToString();
            //    connExcel.Close();
            //    //Read Data from First Sheet
            //    connExcel.Open();
            //    cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";
            //    oda.SelectCommand = cmdExcel;
            //    oda.Fill(dt);
            //    Session["dt"] = dt;
            //    //conn.Open();
            //    foreach (DataRow row in dt.Rows)
            //    {
            //        string RBarcode = row["Barcode"].ToString();
            //        string RInventoryName = row["InventoryName"].ToString();
            //        string RDescription = row["Description"].ToString();
            //        string RCategoryId = row["CategoryID"].ToString();
            //        string RPrice = row["Price"].ToString();


            //        //if (!string.IsNullOrEmpty(RBarcode.ToString()))
            //        if (RBarcode != string.Empty || RBarcode != null)
            //        {

            //            if (RPrice.Equals(null) || RPrice.Equals(string.Empty))
            //            {
            //                ObjPL.Price1 = 0;
            //            }
            //            else
            //            {
            //                ObjPL.Price1 = Convert.ToDecimal(RPrice);
            //            }



            //            string RPrice2 = row["Price2"].ToString();

            //            if (RPrice2.Equals(null) || RPrice2.Equals(string.Empty))
            //            {
            //                ObjPL.Price2 = 0;
            //            }
            //            else
            //            {
            //                ObjPL.Price2 = Convert.ToDecimal(RPrice2);
            //            }


            //            string RPrice3 = row["Price3"].ToString();
            //            if (RPrice3.Equals(null) || RPrice3.Equals(string.Empty))
            //            {
            //                ObjPL.Price3 = 0;
            //            }
            //            else
            //            {
            //                ObjPL.Price3 = Convert.ToDecimal(RPrice3);
            //            }


            //            string RPrice4 = row["Price4"].ToString();

            //            if (RPrice4.Equals(null) || RPrice4.Equals(string.Empty))
            //            {
            //                ObjPL.Price4 = 0;
            //            }
            //            else
            //            {
            //                ObjPL.Price4 = Convert.ToDecimal(RPrice4);
            //            }


            //            string RStock = row["Stock"].ToString();
            //            if (RStock.Equals(null) || RStock.Equals(string.Empty))
            //            {
            //                ObjPL.PQuantity = 0;
            //            }
            //            else
            //            {
            //                ObjPL.PQuantity = Convert.ToDecimal(RStock);
            //            }


            //            string RUnitCost = row["UnitCost"].ToString();

            //            if (RUnitCost.Equals(null) || RUnitCost.Equals(string.Empty))
            //            {
            //                ObjPL.UnitCost = 0;
            //            }
            //            else
            //            {
            //                ObjPL.UnitCost = Convert.ToDecimal(RUnitCost);
            //            }
            //            string RNoPriceShift = row["NoPriceShift"].ToString();
            //            string RGroup1 = row["Group1"].ToString();
            //            string RGroup2 = row["Group2"].ToString();
            //            string RGroup3 = row["Group3"].ToString();
            //            string RGroup4 = row["Group4"].ToString();
            //            string RGroup5 = row["Group5"].ToString();
            //            string RStockCode = row["StockCode"].ToString();
            //            string RUnnit = row["Unit"].ToString();
            //            ObjPL.Units = RUnnit;

            //            string RCommPer1 = row["CommissionPercent1"].ToString();

            //            if (RCommPer1.Equals(null) || RCommPer1.Equals(string.Empty))
            //            {
            //                ObjPL.CommPer1 = 0;
            //            }
            //            else
            //            {
            //                ObjPL.CommPer1 = Convert.ToDouble(RCommPer1);
            //            }
            //            string RCommPer2 = row["CommissionPercent2"].ToString();

            //            if (RCommPer2.Equals(null) || RCommPer2.Equals(string.Empty))
            //            {
            //                ObjPL.CommPer2 = 0;
            //            }
            //            else
            //            {
            //                ObjPL.CommPer2 = Convert.ToDouble(RCommPer2);
            //            }

            //            string RCommPer3 = row["CommissionPercent3"].ToString();

            //            if (RCommPer3.Equals(null) || RCommPer3.Equals(string.Empty))
            //            {
            //                ObjPL.CommPer3 = 0;
            //            }
            //            else
            //            {
            //                ObjPL.CommPer3 = Convert.ToDouble(RCommPer3);
            //            }
            //            string RCommAmt1 = row["CommissionAmount1"].ToString();
            //            if (RCommAmt1.Equals(null) || RCommAmt1.Equals(string.Empty))
            //            {
            //                ObjPL.CommAmt1 = 0;
            //            }
            //            else
            //            {
            //                ObjPL.CommAmt1 = Convert.ToDecimal(RCommAmt1);
            //            }

            //            string RCommAmt2 = row["CommissionAmount2"].ToString();
            //            if (RCommAmt2.Equals(null) || RCommAmt2.Equals(string.Empty))
            //            {
            //                ObjPL.CommAmt2 = 0;
            //            }
            //            else
            //            {
            //                ObjPL.CommAmt2 = Convert.ToDecimal(RCommAmt2);
            //            }
            //            string RERPItemCode1 = row["ERPItemCode1"].ToString();
            //            string RERPItemCode2 = row["ERPItemCode2"].ToString();
            //            string RERPItemDesc = row["ERPItemDesc"].ToString();
            //            string ImagePath = row["Imagepath"].ToString();



            //            string ChkQry = "select barcode from  " + BranchAlias + ".inventory where  barcode='" + RBarcode + "'";
            //            ChkValue = ObjCloudMain.ExecuteScalar(ChkQry);

            //            if (ChkValue != "")
            //            {
            //                string ChkQuery = "select inventoryID from  " + BranchAlias + ".inventory where  barcode='" + RBarcode + "'";
            //                ChkInvenId = ObjCloudMain.ExecuteScalar(ChkQuery);
            //                ObjPL.InventoryId = ChkInvenId;
            //                // Update Code Here.. 

            //                string UPTQry = "Update " + BranchAlias + ".Inventory Set InventoryName='" + RInventoryName + "', Description='" + RDescription + "', CategoryID=" + RCategoryId + ", " +
            //                " Unit='" + ObjPL.Units + "',Price=" + ObjPL.Price1 + ",Price2=" + ObjPL.Price2 + ",Price3=" + ObjPL.Price3 + ", Price4=" + ObjPL.Price4 + ", Group1='" + RGroup1 + "',Group2='" + RGroup2 + "', " +
            //                " Group3='" + RGroup3 + "',Group4='" + RGroup4 + "',Group5='" + RGroup5 + "',CommissionPercent1=" + ObjPL.CommPer1 + ",CommissionPercent2=" + ObjPL.CommPer2 + ",CommissionPercent3=" + ObjPL.CommPer3 + ",CommissionAmount1=" + ObjPL.CommAmt1 + ",CommissionAmount2=" + ObjPL.CommAmt2 + ",ERPItemCode1='" + RERPItemCode1 + "',ERPItemCode2='" + RERPItemCode2 + "',ERPItemDesc='" + RERPItemDesc + "', " +
            //                " StockCode='" + RStockCode + "' , Imagepath='" + ImagePath + "' " +
            //                " Where InventoryID=" + ObjPL.InventoryId + " ";
            //                K = ObjCloudMain.ExecuteNonQuery(UPTQry);

            //                // Update InventoryCostaverage 
            //                if (RStock.Equals(null) || RStock.Equals(string.Empty) || RStock.Equals("0"))
            //                {
            //                    ObjPL.PQuantity = 0;
            //                    ObjPL.PAmount = 0;
            //                }
            //                else
            //                {
            //                    if (RUnitCost.Equals(null) || RUnitCost.Equals(string.Empty) || RUnitCost.Equals("0"))
            //                    {


            //                    }
            //                    else
            //                    {

            //                        OldPQty = Convert.ToDecimal(ObjCloudMain.ExecuteScalar("select PQuantity from " + BranchAlias + ".inventorycostaverage where inventoryid=" + ObjPL.InventoryId + " "));
            //                        OldUnitCost = Convert.ToDecimal(ObjCloudMain.ExecuteScalar("select UnitCost  from " + BranchAlias + ".inventorycostaverage where inventoryid=" + ObjPL.InventoryId + " "));
            //                        CutQty = Convert.ToDecimal(ObjCloudMain.ExecuteScalar("select CutQuantity  from " + BranchAlias + ".inventorycostaverage where inventoryid=" + ObjPL.InventoryId + " "));

            //                        OldPQty -= CutQty;         // Minus with Pqty with Cut Qty 
            //                        ObjPL.PQuantity -= CutQty;
            //                        OldPAmount = OldPQty * OldUnitCost;
            //                        NewPAmount = ObjPL.PQuantity * ObjPL.UnitCost;
            //                        // Avg UnitCost

            //                        OldPAmount += NewPAmount;
            //                        ObjPL.PQuantity += OldPQty;
            //                        JAmount = OldPAmount / ObjPL.PQuantity;


            //                        // Unit Cost Avg Calculation 

            //                        // Update In InventoryCostaverage
            //                        string UPTQry2 = "Update " + BranchAlias + ".inventorycostaverage  set PQuantity=" + ObjPL.PQuantity + ",PAmount=" + OldPAmount + ", UnitCost=" + JAmount + "  where InventoryID=" + ObjPL.InventoryId + "   ";
            //                        U = ObjCloudMain.ExecuteNonQuery(UPTQry2);
            //                        // Update In InventoryAdjust
            //                        sCmd = "Insert INTO " + BranchAlias + ".inventoryadjust(InventoryID, AdjustQuantity, UnitCost, Notes,DateAdjusted, EmployeeID)values(" + ObjPL.InventoryId + "," + Convert.ToDecimal(RStock) + " ,  " + ObjPL.UnitCost + ",'Excel-CloudImport','" + Curr_DateOnly + "',1) ";
            //                        K = ObjCloudMain.ExecuteNonQuery(sCmd);
            //                    }



            //                }

            //            }
            //            else
            //            {
            //                // Insert Code into Inventory
            //                ObjPL.InventoryId = ObjSel.GetMax_RunningNo(BranchAlias);
            //                string InsQry = "insert into " + BranchAlias + ".inventory(InventoryID,BarCode,InventoryName,Description,CategoryID,Unit,Price,"
            //                + "Price2,Price3,Price4,DateCreated,Group1,Group2,Group3,Group4,Group5,NoPriceShift,Active,Updated,"
            //                + "  Notes,BranchUpdated,StockCode,ReorderLevel,SafetyLevel,MaxiumLevel,CommissionPercent1,CommissionPercent2,CommissionPercent3,CommissionAmount1,CommissionAmount2,ERPItemCode1,ERPItemCode2,ERPItemDesc,Imagepath )"
            //                + "  values (" + ObjPL.InventoryId + "  ,'" + RBarcode + "', '" + RInventoryName + "','" + RDescription + "'," + RCategoryId + ", "
            //                + "   '" + ObjPL.Units + "'," + ObjPL.Price1 + "," + ObjPL.Price2 + "," + ObjPL.Price3 + "," + ObjPL.Price4 + ",'" + Curr_DateOnly + "','" + RGroup1 + "','" + RGroup2 + "',"
            //                + "  '" + RGroup3 + "','" + RGroup4 + "','" + RGroup5 + "',0,-1,0,' ',0, '" + RStockCode + "'," + ObjPL.ReoderLevel + " ," + ObjPL.SaftyLevel + ","
            //                + "   " + ObjPL.MaixmumLevel + "," + ObjPL.CommPer1 + "," + ObjPL.CommPer2 + "," + ObjPL.CommPer3 + "," + ObjPL.CommAmt1 + "," + ObjPL.CommAmt2 + ",'" + RERPItemCode1 + "','" + RERPItemCode2 + "','" + RERPItemDesc + "','" + ImagePath + "' ); ";
            //                K = ObjCloudMain.ExecuteNonQuery(InsQry);


            //                if (RStock.Equals(string.Empty) || RStock.Equals(null) || RStock.Equals("0"))
            //                {
            //                    // Insert  CostAvg Table 
            //                    string Query1 = "INSERT INTO " + BranchAlias + ".inventorycostaverage(`InventoryID`, `PQuantity`, `PAmount`, `CutQuantity`, `CutAmount`, `UnitCost`, `RetailQty`, `RetailAmount`)" +
            //                    "VALUES (" + ObjPL.InventoryId + ",'0.0000','0.0000','0.0000','0.0000','0.0000','0','0.0000');";
            //                    L = ObjCloudMain.ExecuteNonQuery(Query1);
            //                    // Update Running No 
            //                    string QueryUPT = "update " + BranchAlias + ".runningnumber set RunningNo=" + ObjPL.InventoryId + "   where ModuleName='Inventory';";
            //                    U = ObjCloudMain.ExecuteNonQuery(QueryUPT);

            //                }
            //                else
            //                {

            //                    if (RUnitCost.Equals(null) || RUnitCost.Equals(string.Empty) || RUnitCost.Equals("0"))
            //                    {
            //                        ObjPL.UnitCost = 0;
            //                        ObjPL.PAmount = 0;
            //                        ObjPL.PQuantity = 0;
            //                        // Insert  CostAvg Table : If Have Stock But No UnitCost 
            //                        string Query2 = "INSERT INTO " + BranchAlias + ".inventorycostaverage(`InventoryID`, `PQuantity`, `PAmount`, `CutQuantity`, `CutAmount`, `UnitCost`, `RetailQty`, `RetailAmount`)" +
            //                       "VALUES (" + ObjPL.InventoryId + "," + ObjPL.PQuantity + "," + ObjPL.PAmount + ",'0.0000','0.0000'," + ObjPL.UnitCost + ",'0','0.0000');";
            //                        L = ObjCloudMain.ExecuteNonQuery(Query2);

            //                        // Update Running No 
            //                        string QueryUPT = "update " + BranchAlias + ".runningnumber set RunningNo=" + ObjPL.InventoryId + "   where ModuleName='Inventory';";
            //                        U = ObjCloudMain.ExecuteNonQuery(QueryUPT);

            //                    }
            //                    else
            //                    {
            //                        ObjPL.UnitCost = Convert.ToDecimal(RUnitCost);
            //                        ObjPL.PAmount = Convert.ToDecimal(RUnitCost) * Convert.ToDecimal(RStock);


            //                        // Insert  CostAvg Table : If Have Stock
            //                        string Query2 = "INSERT INTO " + BranchAlias + ".inventorycostaverage(`InventoryID`, `PQuantity`, `PAmount`, `CutQuantity`, `CutAmount`, `UnitCost`, `RetailQty`, `RetailAmount`)" +
            //                       "VALUES (" + ObjPL.InventoryId + "," + ObjPL.PQuantity + "," + ObjPL.PAmount + ",'0.0000','0.0000'," + ObjPL.UnitCost + ",'0','0.0000');";
            //                        L = ObjCloudMain.ExecuteNonQuery(Query2);
            //                        // Insert InventoryAdjust : If Have Stock
            //                        sCmd = "Insert INTO " + BranchAlias + ".inventoryadjust(InventoryID, AdjustQuantity, UnitCost,Notes,DateAdjusted, EmployeeID)values(" + ObjPL.InventoryId + "," + ObjPL.PQuantity + " ,  " + ObjPL.UnitCost + ",'Excel-CloudImport','" + Curr_DateOnly + "',1) ";
            //                        K = ObjCloudMain.ExecuteNonQuery(sCmd);
            //                        // Update Running No 
            //                        string QueryUPT = "update " + BranchAlias + ".runningnumber set RunningNo=" + ObjPL.InventoryId + "   where ModuleName='Inventory';";
            //                        U = ObjCloudMain.ExecuteNonQuery(QueryUPT);


            //                    }


            //                }

            //            }

            //        }
            //        else
            //        {
            //            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Your Imported Excel File Have some issue ! ');location.href='InventoryMaster.aspx' ", true);
            //        }



            //    }
            //    connExcel.Close();
            //    //Bind Data to GridView
            //    GridView1.Caption = Path.GetFileName(FilePath);
            //    GridView1.DataSource = dt;
            //    GridView1.DataBind();
            //    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Inventory Imported  Successfully ');location.href='InventoryMaster.aspx' ", true);



            //}
            //catch (Exception Ex)
            //{
            //    throw Ex;
            //}
            //finally
            //{


            //}

            // Prevention SQL Injection  : 07-10-21
            // Prevention XSS

            //nid added for CSV Import on 22-Jun-2021
            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
            }


            try
            {

                //Create a DataTable.  
                DataTable dt = new DataTable();
                dt.Columns.AddRange(new DataColumn[22] { new DataColumn("Barcode", typeof(string)),
                new DataColumn("InventoryName", typeof(string)), new DataColumn("Description", typeof(string)), new DataColumn("CategoryName", typeof(string)),
                new DataColumn("Price",typeof(string)),new DataColumn("Price2",typeof(string)),new DataColumn("Price3",typeof(string)),new DataColumn("Price4",typeof(string)),
                new DataColumn("Stock",typeof(string)),new DataColumn("UnitCost",typeof(string)),new DataColumn("NoPriceShift",typeof(string)),
                new DataColumn("Group1",typeof(string)),new DataColumn("Group2",typeof(string)),new DataColumn("Group3",typeof(string)),new DataColumn("Group4",typeof(string)),new DataColumn("Group5",typeof(string)),
                new DataColumn("StockCode", typeof(string)), new DataColumn("Unit", typeof(string)), new DataColumn("Notes", typeof(string)),
                new DataColumn("ImagePath", typeof(string)),new DataColumn("OnHand", typeof(string)),new DataColumn("CR", typeof(string))
                });

                //Read the contents of CSV file.  
                string csvData = File.ReadAllText(FilePath);

                if (ValidateCSVHeader(FilePath) != false)
                {

                    // #2.Validate excel Data 
                    
                    ListtoDataTableConverter listto = new ListtoDataTableConverter();

                    List<CsvDataModel> _validDataList = new List<CsvDataModel>();
                    // After validate csv file make the csv data  as list 
                    _validDataList = ImportAndValidateCsvData(FileUpload1.PostedFile.InputStream);
                    // After geeting the list .Convert it to  List of datat To Datatable of data 
                    // DtResult  had the Final Result as Datatable object.
                    DataTable DtResult = listto.ToDataTable(_validDataList);

                    // Loop it (DataTable)  for import Process 
                    if (DtResult.Rows.Count <= 3000)
                    {
                        #region   Remove it later : Previous approach to read excel to DataTable
                        bool skip = true;
                        //Execute a loop over the rows.  
                        foreach (string row in csvData.Split('\n'))
                        {
                            if (!skip)
                            {
                                if (!string.IsNullOrEmpty(row))
                                {
                                    dt.Rows.Add();
                                    int i = 0;

                                    //Execute a loop over the columns.  
                                    Regex regx = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");
                                    //foreach (string cell in row.Split(','))
                                    foreach (string cell in regx.Split(row))
                                    {
                                        dt.Rows[dt.Rows.Count - 1][i] = Regex.Replace(cell.Replace("\xfeff", ""), @"[\""]", "", RegexOptions.None); ;
                                        //T = dt.Rows.Count ;
                                        i++;
                                    }
                                }
                            }
                            skip = false;
                        }
                        #endregion
                        
                        foreach (DataRow row in DtResult.Rows)
                        {

                            string RBarcode = row["Barcode"].ToString().Trim();
                            //TS = RBarcode;
                            string RInventoryName = row["InventoryName"].ToString().Trim();
                            string RDescription = row["Description"].ToString().Trim();
                            string RCategoryId = "1";
                            //string ChkQry1 = "select categoryid from  {0}.inventorycategories where  categoryname='{1}' ";
                            string ChkQry1 = "select categoryid from  {0}.inventorycategories where  description='{1}' ";           //nid added Description for checking on 11-Jul-2023
                            RCategoryName = row["CategoryName"].ToString().Trim();      //nid added this check on 08-Mar-2023
                            if (RCategoryName.Length < 16)
                            {
                                Ln = RCategoryName.Length;
                            }
                            else
                            {
                                Ln = 16;
                            }
                            //string Command = string.Format(ChkQry1, BranchAlias, row["CategoryName"].ToString().Trim());      //nid hide 08-Mar-2023
                            //string Command = string.Format(ChkQry1, BranchAlias, row["CategoryName"].ToString().Substring(0, Ln).Trim());
                            string Command = string.Format(ChkQry1, BranchAlias, row["CategoryName"].ToString().Trim()); //nid changed on 11-Jul-2023

                            ChkValue = ObjMain.ExecuteScalar(Command);
                            if (ChkValue != "")
                            {
                                RCategoryId = ChkValue;
                            }
                            else
                            {
                                //RCategoryId = "1";            //nid hide this line for create categories in auto mode on 30-Jan-2023

                                //for getting max CategoryID
                                int LCatID = 0;
                                string sCmd1 = "Select IF(Max(CategoryID) IS Null,0,Max(CategoryID)) as LCatID From {0}.inventorycategories;";
                                string CommandCat1 = string.Format(sCmd1, BranchAlias);
                                LCatID = Convert.ToInt32(ObjMain.ExecuteScalar(CommandCat1));
                                LCatID = LCatID + 1;
                                string new_CategoryName = row["CategoryName"].ToString().Trim();
                                //for inserting new category into InventoryCategories 
                                string sCmd2 = "Insert INTO {0}.InventoryCategories (CategoryID, CategoryNumber, CategoryName, Description, DateCreated, Active, Updated, BranchUpdated, Flag1, Flag2, FireIndex, Breakline, Flag3) VALUES " +
                                    " (@CategoryID, @CategoryNumber, @CategoryName, @Description, @DateCreated, @Active, @Updated, @BranchUpdated, @Flag1, @Flag2, @FireIndex, @Breakline, @Flag3);";
                                string uCommand = string.Format(sCmd2, BranchAlias);
                                MySqlParameter[] parameters =
                                 {
                                new MySqlParameter("@CategoryID",LCatID),
                                new MySqlParameter("@CategoryNumber",LCatID),
                                new MySqlParameter("@CategoryName",new_CategoryName),
                                new MySqlParameter("@Description",new_CategoryName),
                                new MySqlParameter("@DateCreated",Curr_DateOnly),
                                new MySqlParameter("@Active",-1),
                                new MySqlParameter("@Updated", 0),
                                new MySqlParameter("@BranchUpdated",0),
                                new MySqlParameter("@Flag1", "00000011"),
                                new MySqlParameter("@Flag2","00000000000000000000"),
                                new MySqlParameter("@FireIndex",0),
                                new MySqlParameter("@Breakline",0),
                                new MySqlParameter("@Flag3","00000000")
                             };
                                K = ObjMain.ExecuteQuery(uCommand, parameters);
                                if (K == 1)
                                {
                                    RCategoryId = LCatID.ToString().Trim();
                                }
                                else
                                {
                                    RCategoryId = "1";
                                }
                                // Update Running No 
                                string QueryUPT = "Update {0}.runningnumber Set RunningNo=" + LCatID + " Where ModuleName='InventoryCategory';";
                                string commandM = string.Format(QueryUPT, BranchAlias);
                                U = ObjCloudMain.ExecuteNonQuery(commandM);
                            }

                            string RPrice = row["Price"].ToString().Trim();
                            //RPrice = RPrice.Replace("\xfeff", "");

                            //if (!string.IsNullOrEmpty(RBarcode.ToString()))
                            //if (RBarcode != string.Empty || RBarcode != null )   // nid hide on 10-Nov-2021
                            if (RBarcode.Length != 0)       //nid added for avaoid Null barcodes on 10-Nov-2021
                            {

                                if (RPrice.Equals(null) || RPrice.Equals(string.Empty))
                                {
                                    ObjPL.Price1 = 0;
                                }
                                else
                                {
                                    ObjPL.Price1 = Convert.ToDecimal(RPrice);
                                }



                                string RPrice2 = row["Price2"].ToString().Trim();
                                //RPrice2=RPrice2.Replace("\xfeff", "");
                                if (RPrice2.Equals(null) || RPrice2.Equals(string.Empty))
                                {
                                    ObjPL.Price2 = 0;
                                }
                                else
                                {
                                    ObjPL.Price2 = Convert.ToDecimal(RPrice2);
                                }


                                string RPrice3 = row["Price3"].ToString().Trim();
                                //RPrice3 = RPrice3.Replace("\xfeff", "");
                                if (RPrice3.Equals(null) || RPrice3.Equals(string.Empty))
                                {
                                    ObjPL.Price3 = 0;
                                }
                                else
                                {
                                    ObjPL.Price3 = Convert.ToDecimal(RPrice3);
                                }


                                string RPrice4 = row["Price4"].ToString().Trim();
                                //RPrice4 = RPrice4.Replace("\xfeff", "");
                                if (RPrice4.Equals(null) || RPrice4.Equals(string.Empty))
                                {
                                    ObjPL.Price4 = 0;
                                }
                                else
                                {
                                    ObjPL.Price4 = Convert.ToDecimal(RPrice4);
                                }


                                string RStock = row["Stock"].ToString().Trim();
                                //RStock = RStock.Replace("\xfeff", "");
                                if (RStock.Equals(null) || RStock.Equals(string.Empty))
                                {
                                    ObjPL.PQuantity = 0;
                                }
                                else
                                {
                                    ObjPL.PQuantity = Convert.ToDecimal(RStock);
                                }


                                string RUnitCost = row["UnitCost"].ToString().Trim();
                                //RUnitCost  = RUnitCost.Replace("\xfeff", "");
                                if (RUnitCost.Equals(null) || RUnitCost.Equals(string.Empty))
                                {
                                    ObjPL.UnitCost = 0;
                                }
                                else
                                {
                                    ObjPL.UnitCost = Convert.ToDecimal(RUnitCost);
                                }
                                string RNoPriceShift = row["NoPriceShift"].ToString().Trim();

                                //string RGroup1 = row["Group1"].ToString().Trim();     //nid hide on 31-Jan-2023
                                //string RGroup2 = row["Group2"].ToString().Trim();
                                //string RGroup3 = row["Group3"].ToString().Trim();
                                //string RGroup4 = row["Group4"].ToString().Trim();
                                //string RGroup5 = row["Group5"].ToString().Trim();

                                //nid added for auto creation of groups on 31-Jan-2023
                                //Group1 Check
                                string RGroup1 = row["Group1"].ToString().Trim();
                                if (RGroup1 != "")
                                {
                                    string ChkQryG1 = "select groupid from  {0}.Group1 where  groupname='{1}' ";
                                    if (RGroup1.Length < 16)
                                    {
                                        Ln = RGroup1.Length;
                                    }
                                    else
                                    {
                                        Ln = 16;
                                    }
                                    string CommandG1 = string.Format(ChkQryG1, BranchAlias, row["Group1"].ToString().Substring(0, Ln).Trim());
                                    ChkValue = ObjMain.ExecuteScalar(CommandG1);
                                    if (ChkValue == "")
                                    {
                                        //for getting max GroupID
                                        int LGroupID = 0;
                                        string sCmd1 = "Select IF(Max(GroupID) IS Null,0,Max(GroupID)) as LGrpID From {0}.Group1;";
                                        string CommandGP1 = string.Format(sCmd1, BranchAlias);
                                        LGroupID = Convert.ToInt32(ObjMain.ExecuteScalar(CommandGP1));
                                        LGroupID = LGroupID + 1;
                                        string new_GroupName = row["Group1"].ToString().Substring(0, Ln).Trim();
                                        string new_GroupDesc = row["Group1"].ToString().Trim();
                                        //for inserting new GroupName into Group1 
                                        string sCmd2 = "Insert INTO {0}.Group1 (GroupID, GroupName, Description, DateCreated, Active, Updated, BranchUpdated) VALUES " +
                                            " (@GroupID, @GroupName, @Description, @DateCreated, @Active, @Updated, @BranchUpdated);";
                                        string uCommand = string.Format(sCmd2, BranchAlias);
                                        MySqlParameter[] parameters =
                                         {
                                            new MySqlParameter("@GroupID",LGroupID),
                                            new MySqlParameter("@GroupName",new_GroupName),
                                            new MySqlParameter("@Description",new_GroupDesc),
                                            new MySqlParameter("@DateCreated",Curr_DateOnly),
                                            new MySqlParameter("@Active",-1),
                                            new MySqlParameter("@Updated", 0),
                                            new MySqlParameter("@BranchUpdated",0)
                                        };
                                        K = ObjMain.ExecuteQuery(uCommand, parameters);
                                        if (K == 1)
                                        {
                                            // Update Running No 
                                            string QueryUPT = "Update {0}.runningnumber Set RunningNo=" + LGroupID + " Where ModuleName='Group1';";
                                            string commandM = string.Format(QueryUPT, BranchAlias);
                                            U = ObjCloudMain.ExecuteNonQuery(commandM);
                                        }
                                    }
                                }
                                //Group2 Check
                                string RGroup2 = row["Group2"].ToString().Trim();
                                if (RGroup2 != "")
                                {
                                    string ChkQryG2 = "select groupid from  {0}.Group2 where  groupname='{1}' ";
                                    if (RGroup2.Length < 16)
                                    {
                                        Ln = RGroup2.Length;
                                    }
                                    else
                                    {
                                        Ln = 16;
                                    }
                                    string CommandG2 = string.Format(ChkQryG2, BranchAlias, row["Group2"].ToString().Substring(0, Ln).Trim());
                                    ChkValue = ObjMain.ExecuteScalar(CommandG2);
                                    if (ChkValue == "")
                                    {
                                        //for getting max GroupID
                                        int LGroupID = 0;
                                        string sCmd1 = "Select IF(Max(GroupID) IS Null,0,Max(GroupID)) as LGrpID From {0}.Group2;";
                                        string CommandGP1 = string.Format(sCmd1, BranchAlias);
                                        LGroupID = Convert.ToInt32(ObjMain.ExecuteScalar(CommandGP1));
                                        LGroupID = LGroupID + 1;
                                        string new_GroupName = row["Group2"].ToString().Substring(0, Ln).Trim();
                                        string new_GroupDesc = row["Group2"].ToString().Trim();
                                        //for inserting new GroupName into Group2 
                                        string sCmd2 = "Insert INTO {0}.Group2 (GroupID, GroupName, Description, DateCreated, Active, Updated, BranchUpdated) VALUES " +
                                            " (@GroupID, @GroupName, @Description, @DateCreated, @Active, @Updated, @BranchUpdated);";
                                        string uCommand = string.Format(sCmd2, BranchAlias);
                                        MySqlParameter[] parameters =
                                        {
                                        new MySqlParameter("@GroupID",LGroupID),
                                        new MySqlParameter("@GroupName",new_GroupName),
                                        new MySqlParameter("@Description",new_GroupDesc),
                                        new MySqlParameter("@DateCreated",Curr_DateOnly),
                                        new MySqlParameter("@Active",-1),
                                        new MySqlParameter("@Updated", 0),
                                        new MySqlParameter("@BranchUpdated",0)
                                        };
                                        K = ObjMain.ExecuteQuery(uCommand, parameters);
                                        if (K == 1)
                                        {
                                            // Update Running No 
                                            string QueryUPT = "Update {0}.runningnumber Set RunningNo=" + LGroupID + " Where ModuleName='Group2';";
                                            string commandM = string.Format(QueryUPT, BranchAlias);
                                            U = ObjCloudMain.ExecuteNonQuery(commandM);
                                        }
                                    }
                                }
                                //Group3 Check
                                string RGroup3 = row["Group3"].ToString().Trim();
                                if (RGroup3 != "")
                                {
                                    string ChkQryG3 = "select groupid from  {0}.Group3 where  groupname='{1}' ";
                                    if (RGroup3.Length < 16)
                                    {
                                        Ln = RGroup3.Length;
                                    }
                                    else
                                    {
                                        Ln = 16;
                                    }
                                    string CommandG3 = string.Format(ChkQryG3, BranchAlias, row["Group3"].ToString().Substring(0, Ln).Trim());
                                    ChkValue = ObjMain.ExecuteScalar(CommandG3);
                                    if (ChkValue == "")
                                    {
                                        //for getting max GroupID
                                        int LGroupID = 0;
                                        string sCmd1 = "Select IF(Max(GroupID) IS Null,0,Max(GroupID)) as LGrpID From {0}.Group3;";
                                        string CommandGP1 = string.Format(sCmd1, BranchAlias);
                                        LGroupID = Convert.ToInt32(ObjMain.ExecuteScalar(CommandGP1));
                                        LGroupID = LGroupID + 1;
                                        string new_GroupName = row["Group3"].ToString().Substring(0, Ln).Trim();
                                        string new_GroupDesc = row["Group3"].ToString().Trim();
                                        //for inserting new GroupName into Group3 
                                        string sCmd2 = "Insert INTO {0}.Group3 (GroupID, GroupName, Description, DateCreated, Active, Updated, BranchUpdated) VALUES " +
                                            " (@GroupID, @GroupName, @Description, @DateCreated, @Active, @Updated, @BranchUpdated);";
                                        string uCommand = string.Format(sCmd2, BranchAlias);
                                        MySqlParameter[] parameters =
                                        {
                                            new MySqlParameter("@GroupID",LGroupID),
                                            new MySqlParameter("@GroupName",new_GroupName),
                                            new MySqlParameter("@Description",new_GroupDesc),
                                            new MySqlParameter("@DateCreated",Curr_DateOnly),
                                            new MySqlParameter("@Active",-1),
                                            new MySqlParameter("@Updated", 0),
                                            new MySqlParameter("@BranchUpdated",0)
                                        };
                                        K = ObjMain.ExecuteQuery(uCommand, parameters);
                                        if (K == 1)
                                        {
                                            // Update Running No 
                                            string QueryUPT = "Update {0}.runningnumber Set RunningNo=" + LGroupID + " Where ModuleName='Group3';";
                                            string commandM = string.Format(QueryUPT, BranchAlias);
                                            U = ObjCloudMain.ExecuteNonQuery(commandM);
                                        }
                                    }
                                }
                                //Group4 Check
                                string RGroup4 = row["Group4"].ToString().Trim();
                                if (RGroup4 != "")
                                {
                                    string ChkQryG4 = "select groupid from  {0}.Group4 where  groupname='{1}' ";
                                    if (RGroup4.Length < 16)
                                    {
                                        Ln = RGroup4.Length;
                                    }
                                    else
                                    {
                                        Ln = 16;
                                    }
                                    string CommandG4 = string.Format(ChkQryG4, BranchAlias, row["Group4"].ToString().Substring(0, Ln).Trim());
                                    ChkValue = ObjMain.ExecuteScalar(CommandG4);
                                    if (ChkValue == "")
                                    {
                                        //for getting max GroupID
                                        int LGroupID = 0;
                                        string sCmd1 = "Select IF(Max(GroupID) IS Null,0,Max(GroupID)) as LGrpID From {0}.Group4;";
                                        string CommandGP1 = string.Format(sCmd1, BranchAlias);
                                        LGroupID = Convert.ToInt32(ObjMain.ExecuteScalar(CommandGP1));
                                        LGroupID = LGroupID + 1;
                                        string new_GroupName = row["Group4"].ToString().Substring(0, Ln).Trim();
                                        string new_GroupDesc = row["Group4"].ToString().Trim();
                                        //for inserting new GroupName into Group4 
                                        string sCmd2 = "Insert INTO {0}.Group4 (GroupID, GroupName, Description, DateCreated, Active, Updated, BranchUpdated) VALUES " +
                                            " (@GroupID, @GroupName, @Description, @DateCreated, @Active, @Updated, @BranchUpdated);";
                                        string uCommand = string.Format(sCmd2, BranchAlias);
                                        MySqlParameter[] parameters =
                                         {
                                            new MySqlParameter("@GroupID",LGroupID),
                                            new MySqlParameter("@GroupName",new_GroupName),
                                            new MySqlParameter("@Description",new_GroupDesc),
                                            new MySqlParameter("@DateCreated",Curr_DateOnly),
                                            new MySqlParameter("@Active",-1),
                                            new MySqlParameter("@Updated", 0),
                                            new MySqlParameter("@BranchUpdated",0)
                                        };
                                        K = ObjMain.ExecuteQuery(uCommand, parameters);
                                        if (K == 1)
                                        {
                                            // Update Running No 
                                            string QueryUPT = "Update {0}.runningnumber Set RunningNo=" + LGroupID + " Where ModuleName='Group4';";
                                            string commandM = string.Format(QueryUPT, BranchAlias);
                                            U = ObjCloudMain.ExecuteNonQuery(commandM);
                                        }
                                    }
                                }
                                //Group5 Check
                                string RGroup5 = row["Group5"].ToString().Trim();
                                if (RGroup5 != "")
                                {
                                    string ChkQryG5 = "select groupid from  {0}.Group5 where  groupname='{1}' ";
                                    if (RGroup5.Length < 16)
                                    {
                                        Ln = RGroup5.Length;
                                    }
                                    else
                                    {
                                        Ln = 16;
                                    }
                                    string CommandG5 = string.Format(ChkQryG5, BranchAlias, row["Group5"].ToString().Substring(0, Ln).Trim());
                                    ChkValue = ObjMain.ExecuteScalar(CommandG5);
                                    if (ChkValue == "")
                                    {
                                        //for getting max GroupID
                                        int LGroupID = 0;
                                        string sCmd1 = "Select IF(Max(GroupID) IS Null,0,Max(GroupID)) as LGrpID From {0}.Group5;";
                                        string CommandGP1 = string.Format(sCmd1, BranchAlias);
                                        LGroupID = Convert.ToInt32(ObjMain.ExecuteScalar(CommandGP1));
                                        LGroupID = LGroupID + 1;
                                        string new_GroupName = row["Group5"].ToString().Substring(0, Ln).Trim();
                                        string new_GroupDesc = row["Group5"].ToString().Trim();
                                        //for inserting new GroupName into Group5 
                                        string sCmd2 = "Insert INTO {0}.Group5 (GroupID, GroupName, Description, DateCreated, Active, Updated, BranchUpdated) VALUES " +
                                            " (@GroupID, @GroupName, @Description, @DateCreated, @Active, @Updated, @BranchUpdated);";
                                        string uCommand = string.Format(sCmd2, BranchAlias);
                                        MySqlParameter[] parameters =
                                         {
                                            new MySqlParameter("@GroupID",LGroupID),
                                            new MySqlParameter("@GroupName",new_GroupName),
                                            new MySqlParameter("@Description",new_GroupDesc),
                                            new MySqlParameter("@DateCreated",Curr_DateOnly),
                                            new MySqlParameter("@Active",-1),
                                            new MySqlParameter("@Updated", 0),
                                            new MySqlParameter("@BranchUpdated",0)
                                        };
                                        K = ObjMain.ExecuteQuery(uCommand, parameters);
                                        if (K == 1)
                                        {
                                            // Update Running No 
                                            string QueryUPT = "Update {0}.runningnumber Set RunningNo=" + LGroupID + " Where ModuleName='Group5';";
                                            string commandM = string.Format(QueryUPT, BranchAlias);
                                            U = ObjCloudMain.ExecuteNonQuery(commandM);
                                        }
                                    }
                                }

                                string RStockCode = row["StockCode"].ToString().Trim();
                                string RUnnit = row["Unit"].ToString().Trim();
                                ObjPL.Units = RUnnit;
                                string RNotes = row["Notes"].ToString().Trim();
                                string ImagePath = row["Imagepath"].ToString().Trim();

                                string ChkQry = "select barcode from  {0}.inventory where  barcode='{1}' ";
                                string commandx = string.Format(ChkQry, BranchAlias, RBarcode);

                                ChkValue = ObjCloudMain.ExecuteScalar(commandx);

                                if (ChkValue != "")
                                {
                                    string ChkQuery = "select inventoryID from  {0}.inventory where  barcode='{1}' ";
                                    string commandY = string.Format(ChkQuery, BranchAlias, RBarcode);
                                    ChkInvenId = ObjCloudMain.ExecuteScalar(commandY);
                                    ObjPL.InventoryId = ChkInvenId;
                                    // Update Code Here.. 

                                    string UPTQry = "Update {0}.Inventory Set InventoryName=@InventoryName, Description=@Description, CategoryID=@CategoryID , " +
                                    " Unit=@Unit,Price=@Price,Price2=@Price2,Price3=@Price3, Price4=@Price4, Group1=@Group1,Group2=@Group2 , " +
                                    " Group3=@Group3,Group4=@Group4,Group5=@Group5, " +
                                    " StockCode=@StockCode , Notes=@Notes, Imagepath=@Imagepath " +
                                    " Where InventoryID=@InventoryID ";
                                    string Ins_Command = string.Format(UPTQry, BranchAlias);

                                    MySqlParameter[] parameters =
                                    {
                                         new MySqlParameter("@InventoryName",RInventoryName),
                                         new MySqlParameter("@Description",RDescription),
                                         new MySqlParameter("@CategoryID",RCategoryId),
                                         new MySqlParameter("@Unit",ObjPL.Units),
                                         new MySqlParameter("@Price", ObjPL.Price1),
                                         new MySqlParameter("@Price2",ObjPL.Price2),
                                         new MySqlParameter("@Price3", ObjPL.Price3),
                                         new MySqlParameter("@Price4",ObjPL.Price4),
                                         new MySqlParameter("@Group1",RGroup1),
                                         new MySqlParameter("@Group2",RGroup2),
                                         new MySqlParameter("@Group3",RGroup3),
                                         new MySqlParameter("@Group4",RGroup4),
                                         new MySqlParameter("@Group5",RGroup5),
                                         new MySqlParameter("@StockCode",RStockCode),
                                         new MySqlParameter("@Notes",RNotes),
                                         new MySqlParameter("@Imagepath",ImagePath),
                                         new MySqlParameter("@InventoryID",ObjPL.InventoryId),
                                    };
                                    K = ObjMain.ExecuteQuery(Ins_Command, parameters);

                                    // Update InventoryCostaverage 
                                    if (RStock.Equals(null) || RStock.Equals(string.Empty) || RStock.Equals("0"))
                                    {
                                        ObjPL.PQuantity = 0;
                                        ObjPL.PAmount = 0;

                                        //nid added for Update UnitCost as Fixed Cost if Cost got value on 28-Jun-2024
                                        if (ObjPL.UnitCost > 0)
                                        {
                                            string UPTQry3 = "Update {0}.inventorycostaverage  set  UnitCost=@UnitCost  where InventoryID=@InventoryID;";
                                            string commandF = string.Format(UPTQry3, BranchAlias);
                                            MySqlParameter[] parametersF =
                                            {
                                                new MySqlParameter("@UnitCost",ObjPL.UnitCost),
                                                new MySqlParameter("@InventoryID",ObjPL.InventoryId),

                                            };
                                            U = ObjCloudMain.ExecuteQuery(commandF, parametersF);
                                            // Update In InventoryAdjust for Fixed Cost update on 28-Jun-2024
                                            sCmd = "Insert INTO {0}.inventoryadjust(InventoryID, AdjustQuantity, UnitCost, Notes,DateAdjusted, EmployeeID)" +
                                                " values(@InventoryID,@AdjustQuantity,@UnitCost,@Notes,@DateAdjusted,@EmployeeID) ";

                                            string commandG = string.Format(sCmd, BranchAlias);
                                            MySqlParameter[] parametersG =
                                            {
                                                new MySqlParameter("@InventoryID", ObjPL.InventoryId),
                                                new MySqlParameter("@AdjustQuantity", 0),
                                                new MySqlParameter("@UnitCost",ObjPL.UnitCost),
                                                new MySqlParameter("@Notes","Excel-CloudImport-FC"),
                                                new MySqlParameter("@DateAdjusted",Curr_DateOnly),
                                                new MySqlParameter("@EmployeeID",1),

                                            };
                                            K = ObjMain.ExecuteQuery(commandG, parametersG);
                                        }

                                    }
                                    else
                                    {
                                        if (RUnitCost.Equals(null) || RUnitCost.Equals(string.Empty) || RUnitCost.Equals("0"))
                                        {


                                        }
                                        else
                                        {
                                            string QRA = "select PQuantity from {0}.inventorycostaverage where inventoryid={1} ";
                                            string commandA = string.Format(QRA, BranchAlias, ObjPL.InventoryId);
                                            OldPQty = Convert.ToDecimal(ObjCloudMain.ExecuteScalar(commandA));

                                            string QRB = "select UnitCost  from {0}.inventorycostaverage where inventoryid={1} ";
                                            string CommandB = string.Format(QRB, BranchAlias, ObjPL.InventoryId);
                                            OldUnitCost = Convert.ToDecimal(ObjCloudMain.ExecuteScalar(CommandB));

                                            string QRC = "select CutQuantity  from {0}.inventorycostaverage where inventoryid={1} ";
                                            string commandC = string.Format(QRC, BranchAlias, ObjPL.InventoryId);
                                            CutQty = Convert.ToDecimal(ObjCloudMain.ExecuteScalar(commandC));

                                            OldPQty -= CutQty;         // Minus with Pqty with Cut Qty 
                                            ObjPL.PQuantity -= CutQty;
                                            OldPAmount = OldPQty * OldUnitCost;
                                            NewPAmount = ObjPL.PQuantity * ObjPL.UnitCost;
                                            // Avg UnitCost

                                            OldPAmount += NewPAmount;
                                            ObjPL.PQuantity += OldPQty;

                                            if (ObjPL.PQuantity != 0)     // nid added 0 value division on 02-Nov-2021
                                            {
                                                JAmount = OldPAmount / ObjPL.PQuantity;
                                            }
                                            else
                                            {
                                                JAmount = OldPAmount;
                                            }

                                            // Unit Cost Avg Calculation 

                                            // Update In InventoryCostaverage
                                            string UPTQry2 = "Update {0}.inventorycostaverage  set PQuantity=@PQuantity,PAmount=@PAmount, UnitCost=@UnitCost  where InventoryID=@InventoryID;";
                                            string commandD = string.Format(UPTQry2, BranchAlias);
                                            MySqlParameter[] parametersD =
                                           {
                                                new MySqlParameter("@PQuantity", ObjPL.PQuantity),
                                                new MySqlParameter("@PAmount",OldPAmount),
                                                new MySqlParameter("@UnitCost",JAmount),
                                                new MySqlParameter("@InventoryID",ObjPL.InventoryId),

                                            };
                                            U = ObjCloudMain.ExecuteQuery(commandD, parametersD);
                                            // Update In InventoryAdjust
                                            sCmd = "Insert INTO {0}.inventoryadjust(InventoryID, AdjustQuantity, UnitCost, Notes,DateAdjusted, EmployeeID)" +
                                                " values(@InventoryID,@AdjustQuantity,@UnitCost,@Notes,@DateAdjusted,@EmployeeID) ";

                                            string commandE = string.Format(sCmd, BranchAlias);
                                            MySqlParameter[] parametersE =
                                            {
                                                new MySqlParameter("@InventoryID", ObjPL.InventoryId),
                                                new MySqlParameter("@AdjustQuantity", Convert.ToDecimal(RStock)),
                                                new MySqlParameter("@UnitCost",ObjPL.UnitCost),
                                                new MySqlParameter("@Notes","Excel-CloudImport"),
                                                new MySqlParameter("@DateAdjusted",Curr_DateOnly),
                                                new MySqlParameter("@EmployeeID",1),

                                            };
                                            K = ObjMain.ExecuteQuery(commandE, parametersE);

                                            //nid added for Update UnitCost as Fixed Cost if Cost got value on 28-Jun-2024
                                            if (ObjPL.UnitCost > 0) 
                                            { 
                                                string UPTQry3 = "Update {0}.inventorycostaverage  set  UnitCost=@UnitCost  where InventoryID=@InventoryID;";
                                                string commandF = string.Format(UPTQry3, BranchAlias);
                                                MySqlParameter[] parametersF =
                                                {
                                                    new MySqlParameter("@UnitCost",ObjPL.UnitCost),
                                                    new MySqlParameter("@InventoryID",ObjPL.InventoryId),

                                                };
                                                U = ObjCloudMain.ExecuteQuery(commandF, parametersF);
                                                // Update In InventoryAdjust for Fixed Cost update on 28-Jun-2024
                                                sCmd = "Insert INTO {0}.inventoryadjust(InventoryID, AdjustQuantity, UnitCost, Notes,DateAdjusted, EmployeeID)" +
                                                    " values(@InventoryID,@AdjustQuantity,@UnitCost,@Notes,@DateAdjusted,@EmployeeID) ";

                                                string commandG = string.Format(sCmd, BranchAlias);
                                                MySqlParameter[] parametersG =
                                                {
                                                    new MySqlParameter("@InventoryID", ObjPL.InventoryId),
                                                    new MySqlParameter("@AdjustQuantity", 0),
                                                    new MySqlParameter("@UnitCost",ObjPL.UnitCost),
                                                    new MySqlParameter("@Notes","Excel-CloudImport-FC"),
                                                    new MySqlParameter("@DateAdjusted",Curr_DateOnly),
                                                    new MySqlParameter("@EmployeeID",1),

                                                };
                                                K = ObjMain.ExecuteQuery(commandG, parametersG);
                                            }


                                        }



                                    }

                                }
                                else
                                {
                                    // Insert Code into Inventory
                                    ObjPL.InventoryId = ObjSel.GetMax_RunningNo(BranchAlias);
                                    string InsQry = "insert into {0}.inventory(InventoryID,BarCode,InventoryName,Description,CategoryID,Unit,Price,"
                                    + "  Price2,Price3,Price4,DateCreated,Group1,Group2,Group3,Group4,Group5,NoPriceShift,Active,Updated,"
                                    + "  Notes,BranchUpdated,StockCode,ReorderLevel,SafetyLevel,MaxiumLevel,CommissionPercent1,CommissionPercent2,"
                                    + "  CommissionPercent3,CommissionAmount1,CommissionAmount2,ERPItemCode1,ERPItemCode2,ERPItemDesc,Imagepath )"
                                    + "  values (@InventoryID,@BarCode, @InventoryName,@Description,@CategoryID, "
                                    + "  @Unit,@Price,@Price2,@Price3,@Price4,@DateCreated,@Group1,@Group2,"
                                    + "  @Group3,@Group4,@Group5,@NoPriceShift,@Active,@Updated,@Notes,@BranchUpdated, @StockCode,@ReorderLevel ,@SafetyLevel,"
                                    + "  @MaxiumLevel,@CommissionPercent1,@CommissionPercent2,@CommissionPercent3,@CommissionAmount1,@CommissionAmount2,"
                                    + "  @ERPItemCode1,@ERPItemCode2,@ERPItemDesc,@Imagepath); ";

                                    string uCommand = string.Format(InsQry, BranchAlias);

                                    MySqlParameter[] parameters =
                                    {
                                         new MySqlParameter("@InventoryID",ObjPL.InventoryId),
                                         new MySqlParameter("@BarCode",RBarcode),
                                         new MySqlParameter("@InventoryName",RInventoryName),
                                         new MySqlParameter("@Description",RDescription),
                                         new MySqlParameter("@CategoryID",RCategoryId),
                                         new MySqlParameter("@Unit",ObjPL.Units),
                                         new MySqlParameter("@Price", ObjPL.Price1),
                                         new MySqlParameter("@Price2",ObjPL.Price2),
                                         new MySqlParameter("@Price3", ObjPL.Price3),
                                         new MySqlParameter("@Price4",ObjPL.Price4),
                                         new MySqlParameter("@DateCreated",Curr_DateOnly),
                                         new MySqlParameter("@Group1",RGroup1),
                                         new MySqlParameter("@Group2",RGroup2),
                                         new MySqlParameter("@Group3",RGroup3),
                                         new MySqlParameter("@Group4",RGroup4),
                                         new MySqlParameter("@Group5",RGroup5),
                                         new MySqlParameter("@NoPriceShift",0),
                                         new MySqlParameter("@Active",-1),
                                         new MySqlParameter("@Updated",0),
                                         new MySqlParameter("@Notes",RNotes),
                                         new MySqlParameter("@BranchUpdated",0),
                                         new MySqlParameter("@StockCode",RStockCode),
                                         new MySqlParameter("@ReorderLevel",ObjPL.ReoderLevel),
                                         new MySqlParameter("@SafetyLevel",ObjPL.SaftyLevel),
                                         new MySqlParameter("@MaxiumLevel",ObjPL.MaixmumLevel),
                                         new MySqlParameter("@CommissionPercent1",ObjPL.CommPer1),
                                         new MySqlParameter("@CommissionPercent2",ObjPL.CommPer2),
                                         new MySqlParameter("@CommissionPercent3",ObjPL.CommPer3),
                                         new MySqlParameter("@CommissionAmount1",ObjPL.CommAmt1),
                                         new MySqlParameter("@CommissionAmount2",ObjPL.CommAmt2),
                                         new MySqlParameter("@ERPItemCode1",""),
                                         new MySqlParameter("@ERPItemCode2",""),
                                         new MySqlParameter("@ERPItemDesc",""),
                                         new MySqlParameter("@Imagepath",ImagePath),

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




                                    if (RStock.Equals(string.Empty) || RStock.Equals(null) || RStock.Equals("0"))
                                    {
                                        // Insert  CostAvg Table 
                                        string Query1 = "INSERT INTO {0}.inventorycostaverage(`InventoryID`, `PQuantity`, `PAmount`, `CutQuantity`, `CutAmount`, `UnitCost`, `RetailQty`, `RetailAmount`)" +
                                        "VALUES (@InventoryID,@PQuantity,@PAmount,@CutQuantity,@CutAmount,@UnitCost,@RetailQty,@RetailAmount);";
                                        string Commands = string.Format(Query1, BranchAlias);



                                        ICObj.InventoryID = int.Parse(ObjPL.InventoryId);
                                        ICObj.PQuantity = decimal.Parse("0.0000");
                                        ICObj.PAmount = decimal.Parse("0.0000");
                                        ICObj.CutQuantity = decimal.Parse("0.0000");
                                        ICObj.CutAmount = decimal.Parse("0.0000");
                                        ICObj.UnitCost = decimal.Parse("0.0000");
                                        ICObj.RetailQty = decimal.Parse("0.0000");
                                        ICObj.RetailAmount = decimal.Parse("0.0000");





                                        MySqlParameter[] parametersA =
                                        {
                                            new MySqlParameter("@InventoryID", ICObj.InventoryID),
                                            new MySqlParameter("@PQuantity",ICObj.PQuantity),
                                            new MySqlParameter("@PAmount",ICObj.PAmount),
                                            new MySqlParameter("@CutQuantity",ICObj.CutQuantity),
                                            new MySqlParameter("@CutAmount",ICObj.CutAmount),
                                            new MySqlParameter("@UnitCost",ICObj.UnitCost),
                                            new MySqlParameter("@RetailQty",ICObj.RetailQty),
                                            new MySqlParameter("@RetailAmount",ICObj.RetailAmount),
                                        };
                                        L = ObjMain.ExecuteQuery(Commands, parametersA);

                                        //nid added for Update UnitCost as Fixed Cost if Cost got value on 28-Jun-2024
                                        if (ObjPL.UnitCost > 0)
                                        {
                                            string UPTQry3 = "Update {0}.inventorycostaverage  set  UnitCost=@UnitCost  where InventoryID=@InventoryID;";
                                            string commandF = string.Format(UPTQry3, BranchAlias);
                                            MySqlParameter[] parametersF =
                                            {
                                                new MySqlParameter("@UnitCost",ObjPL.UnitCost),
                                                new MySqlParameter("@InventoryID",ObjPL.InventoryId),

                                                };
                                            U = ObjCloudMain.ExecuteQuery(commandF, parametersF);
                                            // Update In InventoryAdjust for Fixed Cost update on 28-Jun-2024
                                            sCmd = "Insert INTO {0}.inventoryadjust(InventoryID, AdjustQuantity, UnitCost, Notes,DateAdjusted, EmployeeID)" +
                                                " values(@InventoryID,@AdjustQuantity,@UnitCost,@Notes,@DateAdjusted,@EmployeeID) ";

                                            string commandG = string.Format(sCmd, BranchAlias);
                                            MySqlParameter[] parametersG =
                                            {
                                                new MySqlParameter("@InventoryID", ObjPL.InventoryId),
                                                new MySqlParameter("@AdjustQuantity",  decimal.Parse("0.0000")),
                                                new MySqlParameter("@UnitCost",ObjPL.UnitCost),
                                                new MySqlParameter("@Notes","Excel-CloudImport-FC"),
                                                new MySqlParameter("@DateAdjusted",Curr_DateOnly),
                                                new MySqlParameter("@EmployeeID",1),

                                                };
                                            K = ObjMain.ExecuteQuery(commandG, parametersG);
                                        }


                                        // Update Running No 
                                        string QueryUPT = "update {0}.runningnumber set RunningNo={1}   where ModuleName='Inventory';";
                                        string uptCommand = string.Format(QueryUPT, BranchAlias, ObjPL.InventoryId);
                                        U = ObjCloudMain.ExecuteNonQuery(uptCommand);



                                    }
                                    else
                                    {

                                        ICObj.InventoryID = int.Parse(ObjPL.InventoryId);
                                        ICObj.PQuantity = decimal.Parse("0.0000");
                                        ICObj.PAmount = decimal.Parse("0.0000");
                                        ICObj.CutQuantity = decimal.Parse("0.0000");
                                        ICObj.CutAmount = decimal.Parse("0.0000");
                                        ICObj.UnitCost = decimal.Parse("0.0000");
                                        ICObj.RetailQty = decimal.Parse("0.0000");
                                        ICObj.RetailAmount = decimal.Parse("0.0000");

                                        if (RUnitCost.Equals(null) || RUnitCost.Equals(string.Empty) || RUnitCost.Equals("0"))
                                        {
                                            ObjPL.UnitCost = 0;
                                            ObjPL.PAmount = 0;
                                            ObjPL.PQuantity = 0;
                                            // Insert  CostAvg Table : If Have Stock But No UnitCost 
                                            string Query2 = "INSERT INTO {0}.inventorycostaverage(`InventoryID`, `PQuantity`, `PAmount`, `CutQuantity`, `CutAmount`, `UnitCost`, `RetailQty`, `RetailAmount`)" +
                                           "VALUES (@InventoryID,@PQuantity,@PAmount,@CutQuantity,@CutAmount,@UnitCost,@RetailQty,@RetailAmount);";

                                            string command = string.Format(Query2, BranchAlias);

                                            MySqlParameter[] parametersA =
                                            {
                                                new MySqlParameter("@InventoryID",ObjPL.InventoryId),
                                                new MySqlParameter("@PQuantity",ObjPL.PQuantity),
                                                new MySqlParameter("@PAmount",ObjPL.PAmount),
                                                new MySqlParameter("@CutQuantity",ICObj.CutQuantity),
                                                new MySqlParameter("@CutAmount",ICObj.CutAmount),
                                                new MySqlParameter("@UnitCost",ObjPL.UnitCost),
                                                new MySqlParameter("@RetailQty",ICObj.RetailQty),
                                                new MySqlParameter("@RetailAmount",ICObj.RetailAmount),

                                            };

                                            L = ObjMain.ExecuteQuery(command, parametersA);

                                            // Update Running No 
                                            string QueryUPT = "update {0}.runningnumber set RunningNo={1} where ModuleName='Inventory';";
                                            string UptCommands = string.Format(QueryUPT, BranchAlias, ObjPL.InventoryId);
                                            U = ObjCloudMain.ExecuteNonQuery(UptCommands);

                                        }
                                        else
                                        {
                                            ObjPL.UnitCost = Convert.ToDecimal(RUnitCost);
                                            ObjPL.PAmount = Convert.ToDecimal(RUnitCost) * Convert.ToDecimal(RStock);


                                            // Insert  CostAvg Table : If Have Stock
                                            string Query2 = "INSERT INTO {0}.inventorycostaverage(`InventoryID`, `PQuantity`, `PAmount`, `CutQuantity`, `CutAmount`, `UnitCost`, `RetailQty`, `RetailAmount`)" +
                                           "VALUES (@InventoryID,@PQuantity,@PAmount,@CutQuantity,@CutAmount,@UnitCost,@RetailQty,@RetailAmount);";

                                            string commandX = string.Format(Query2, BranchAlias);
                                            MySqlParameter[] parametersB =
                                            {
                                                new MySqlParameter("@InventoryID",ObjPL.InventoryId),
                                                new MySqlParameter("@PQuantity",ObjPL.PQuantity),
                                                new MySqlParameter("@PAmount",ObjPL.PAmount),
                                                new MySqlParameter("@CutQuantity",ICObj.CutQuantity),
                                                new MySqlParameter("@CutAmount", ICObj.CutAmount),
                                                new MySqlParameter("@UnitCost",ObjPL.UnitCost),
                                                new MySqlParameter("@RetailQty",ICObj.RetailQty),
                                                new MySqlParameter("@RetailAmount",ICObj.RetailAmount),

                                            };
                                            L = ObjMain.ExecuteQuery(commandX, parametersB);

                                            // Insert InventoryAdjust : If Have Stock
                                            sCmd = "Insert INTO {0}.inventoryadjust(InventoryID, AdjustQuantity, UnitCost,Notes,DateAdjusted, EmployeeID)" +
                                                   " values(@InventoryID,@AdjustQuantity , @UnitCost,@Notes,@DateAdjusted,@EmployeeID) ";
                                            String commandY = string.Format(sCmd, BranchAlias);

                                            MySqlParameter[] parametersc =
                                            {
                                                new MySqlParameter("@InventoryID",ObjPL.InventoryId),
                                                new MySqlParameter("@AdjustQuantity",ObjPL.PQuantity),
                                                new MySqlParameter("@UnitCost",ObjPL.UnitCost),
                                                new MySqlParameter("@Notes","Excel-CloudImport"),
                                                new MySqlParameter("@DateAdjusted",Curr_DateOnly),
                                                new MySqlParameter("@EmployeeID",1),
                                            };

                                            K = ObjMain.ExecuteQuery(commandY, parametersc);

                                            //nid added for Update UnitCost as Fixed Cost if Cost got value on 28-Jun-2024
                                            if (ObjPL.UnitCost > 0)
                                            {
                                                string UPTQry3 = "Update {0}.inventorycostaverage  set  UnitCost=@UnitCost  where InventoryID=@InventoryID;";
                                                string commandF = string.Format(UPTQry3, BranchAlias);
                                                MySqlParameter[] parametersF =
                                                {
                                                new MySqlParameter("@UnitCost",ObjPL.UnitCost),
                                                new MySqlParameter("@InventoryID",ObjPL.InventoryId),

                                                };
                                                U = ObjCloudMain.ExecuteQuery(commandF, parametersF);
                                                // Update In InventoryAdjust for Fixed Cost update on 28-Jun-2024
                                                sCmd = "Insert INTO {0}.inventoryadjust(InventoryID, AdjustQuantity, UnitCost, Notes,DateAdjusted, EmployeeID)" +
                                                    " values(@InventoryID,@AdjustQuantity,@UnitCost,@Notes,@DateAdjusted,@EmployeeID) ";

                                                string commandG = string.Format(sCmd, BranchAlias);
                                                MySqlParameter[] parametersG =
                                                {
                                                new MySqlParameter("@InventoryID", ObjPL.InventoryId),
                                                new MySqlParameter("@AdjustQuantity", double.Parse("0")),
                                                new MySqlParameter("@UnitCost",ObjPL.UnitCost),
                                                new MySqlParameter("@Notes","Excel-CloudImport-FC"),
                                                new MySqlParameter("@DateAdjusted",Curr_DateOnly),
                                                new MySqlParameter("@EmployeeID",1),

                                                };
                                                K = ObjMain.ExecuteQuery(commandG, parametersG);
                                            }


                                            // Update Running No 
                                            string QueryUPT = "update {0}.runningnumber set RunningNo={1}  where ModuleName='Inventory';";
                                            string commandM = string.Format(QueryUPT, BranchAlias, ObjPL.InventoryId);
                                            U = ObjCloudMain.ExecuteNonQuery(commandM);

                                        }


                                    }

                                }

                            }
                            else
                            {
                                this.Page.ClientScript.RegisterStartupScript(this.GetType(), "Javascript", "javascript:GetActiveSession5();", true);
                                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Your Imported Excel File Have some issue ! ');location.href='InventoryMaster.aspx' ", true);

                            }



                        }
                        //connExcel.Close();
                        //Bind Data to GridView
                        GridView1.Caption = Path.GetFileName(FilePath);
                        GridView1.DataSource = dt;
                        GridView1.DataBind();

                        AlertA.Visible = true;
                        sb.Append("Inventory Imported  Successfully." + "<br/>");
                        
                        //ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Inventory Imported  Successfully ');", true);
                        //this.Page.ClientScript.RegisterStartupScript(this.GetType(), "Javascript", "javascript:GetActiveSession5();", true);
                        ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "text", "return GetActiveSession5()", true);
                        
                        lblimportError.Text = sb.ToString();
                    }
                    else
                    {

                        AlertA.Visible = true;                        // Enable the Error Message Div
                        Log.Info("Excel File only Can Import 3000 records.");
                        sb.AppendLine("Excel File only Can Import 3000 records." + "<br/>");
                        lblimportError.Text = sb.ToString();
                        this.Page.ClientScript.RegisterStartupScript(this.GetType(), "Javascript", "javascript:GetActiveSession5();", true);
                        // ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('Excel File only Can Import 3000 records.' );", true);
                        

                    }


                }
                else
                {
                    AlertA.Visible = true;              // Enable the Error Message Div
                    Log.Info("Invalid Excel Format");
                    sb.AppendLine("Invalid Excel Format." + "<br/>");
                    lblimportError.Text = sb.ToString();
                    this.Page.ClientScript.RegisterStartupScript(this.GetType(), "Javascript", "javascript:GetActiveSession5();", true);
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('Invalid Excel Format.' );", true);

                }



            }
            catch (Exception Ex)
            {
                AlertA.Visible = true;                 // Enable the Error Message Div
                Log.Info("Imported  Excel having some Data Issue.Import valid Excel File.");
                Log.Info("Database:" + BranchAlias);
                Log.Error("Excel Data Not In a Correct Format:" + Ex.Message);


                sb.AppendLine("Imported  Excel having some Data Type Issue." + "<br/>");
                sb.AppendLine("Excel Data Not In a Correct Format:" + Convert.ToString(Ex.Message) + "<br/>");
                lblimportError.Text = sb.ToString();
                this.Page.ClientScript.RegisterStartupScript(this.GetType(), "Javascript", "javascript:GetActiveSession5();", true);
            }
            finally
            {

                // Get the Weborder ini - From Pms Value . 
                string IS_WebOrder = ObjMain.ExecuteScalar("Select IsWebOrderApp from Portaldb.companydetails where cd_branchAlias='"+ BranchAlias + "'; ");
                if (IS_WebOrder.Equals("Y"))
                {
                    INS_PriceFlage(BranchAlias);
                    INS_ScheduleFlag(BranchAlias);
                    INS_WebStock(BranchAlias);
                }
                else
                { 
                
                }
               this.Page.ClientScript.RegisterStartupScript(this.GetType(), "Javascript", "javascript:GetActiveSession5();", true);

            }


        }
        
        protected void lnkExcel_Click(object sender, EventArgs e)
        {
            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 (Session["Isdowld_Acess"].ToString() == "N")
            {
                if (BranchFullName == "HQ")
                {
                    // This will Return BranchName( Actual Database Name )
                    // Modified This query Based in Excel Standard Import Format :10-02-20
                    //MySqlCommand cmd1 = new MySqlCommand("select *,sum(pquantity-(CutQuantity+RetailQty))as OnHandICA from " + BranchAlias + ".inventory as I  join " + BranchAlias + ".inventorycategories  as c ON I.Categoryid=c.categoryid  join " + BranchAlias + ".inventorycostaverage ic on ic.inventoryid=i.inventoryid group by i.inventoryid ", Cnn);
                    //sum(pquantity-(CutQuantity+RetailQty))as OnHand  john added on 06-April-2020 show pn hand on export inventory
                    //MySqlCommand cmd1 = new MySqlCommand("select I.Barcode , I.InventoryName, I.Description ,C.CategoryID,I.Price,I.Price2,I.Price3,I.Price4,I.onhand as Stock,ic.Unitcost,i.NoPriceShift,I.Group1,I.Group2,I.Group3,I.Group4,I.Group5,I.StockCode,I.Unit,I.CommissionPercent1,I.CommissionPercent2,I.CommissionPercent3,I.CommissionAmount1,I.CommissionAmount2,I.ERPItemCode1,I.ERPItemCode2,I.ERPItemDesc,I.Imagepath,sum(pquantity-(CutQuantity+RetailQty))as OnHand   from " + BranchAlias + ".inventory as I  join " + BranchAlias + ".inventorycategories  as c ON I.Categoryid=c.categoryid  join " + BranchAlias + ".inventorycostaverage ic on ic.inventoryid=i.inventoryid group by i.inventoryid ;", Cnn);
                    
                    // string cmd1 = "select I.Barcode , I.InventoryName, I.Description ,C.CategoryName,I.Price,I.Price2,I.Price3,I.Price4,I.onhand as Stock,ic.Unitcost,i.NoPriceShift,I.Group1,I.Group2,I.Group3,I.Group4,I.Group5,I.StockCode,I.Unit,I.Notes,I.Imagepath,sum(pquantity-(CutQuantity+RetailQty))as OnHand   from {0}.inventory as I  join {0}.inventorycategories  as c ON I.Categoryid=c.categoryid  join {0}.inventorycostaverage ic on ic.inventoryid=i.inventoryid group by i.inventoryid ;";
                    string cmd1 = "select I.Barcode , I.InventoryName, I.Description ,C.Description as CategoryName,I.Price,I.Price2,I.Price3,I.Price4,I.onhand as Stock,ic.Unitcost,i.NoPriceShift,I.Group1,I.Group2,I.Group3,I.Group4,I.Group5,I.StockCode,I.Unit,I.Notes,I.Imagepath,sum(pquantity-(CutQuantity+RetailQty))as OnHand   from {0}.inventory as I  join {0}.inventorycategories  as c ON I.Categoryid=c.categoryid  join {0}.inventorycostaverage ic on ic.inventoryid=i.inventoryid group by i.inventoryid ;";                 //nid added Description instead of CategoryName on 11-Jul-2023
                    string command = string.Format(cmd1, BranchAlias);
                    DataTable Dt1 = new DataTable();
                    Dt1 = ObjMain.GetData_DT(command);



                    //4.CSVHelper Memmory stream write method on 20-Jan-2023
                    var memoryStream = new MemoryStream();
                    //using (var swriter = new StreamWriter(memoryStream))      //nid hide on 13-Mar-2023
                    using (var swriter = new StreamWriter(memoryStream, Encoding.GetEncoding("utf-8"))) //nid added for rectify Chinese Language issue on 13-Mar-2023
                    {
                        using (var csv = new CsvWriter(swriter, CultureInfo.InvariantCulture))
                        using (var CHAIN = Dt1)
                        {

                            foreach (DataColumn column in CHAIN.Columns)
                            {
                                csv.WriteField(column.ColumnName);
                            }
                            csv.NextRecord();


                            foreach (DataRow row in CHAIN.Rows)
                            {

                                for (var i = 0; i < CHAIN.Columns.Count; i++)
                                {
                                    csv.WriteField(row[i]);
                                }
                                csv.NextRecord();
                            }

                            swriter.Flush();
                            memoryStream.Seek(0, SeekOrigin.Begin);
                            var resultInBytes = memoryStream.ToArray();

                            Response.Clear();
                            Response.ContentType = "text/csv"; // or application/force-download
                            Response.AddHeader("content-disposition", "attachment; filename=" + BranchFullName + "_InventoryMaster.csv");
                            Response.BinaryWrite(resultInBytes);
                            Response.End();
                            memoryStream.Flush();
                            memoryStream.Close();
                        }
                    }




                }
                else
                {

                    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
            {
                MySqlConnection Cnn = new MySqlConnection(ConStr_Rds);
                Cnn.Open();
                if (cmbBranches.Visible == false)
                {
                    //sum(pquantity-(CutQuantity+RetailQty))as OnHand  john added on 06-April-2020 show pn hand on export inventory
                    //MySqlCommand cmd1 = new MySqlCommand("select I.Barcode, I.InventoryName, I.Description ,C.CategoryID,I.Price,I.Price2,I.Price3,I.Price4,I.onhand as Stock,ic.Unitcost,i.NoPriceShift,I.Group1,I.Group2,I.Group3,I.Group4,I.Group5,I.StockCode,I.Unit,I.CommissionPercent1,I.CommissionPercent2,I.CommissionPercent3,I.CommissionAmount1,I.CommissionAmount2,I.ERPItemCode1,I.ERPItemCode2,I.ERPItemDesc,I.Imagepath,sum(pquantity-(CutQuantity+RetailQty))as OnHand   from " + BranchAlias + ".inventory as I  join " + BranchAlias + ".inventorycategories  as c ON I.Categoryid=c.categoryid  join " + BranchAlias + ".inventorycostaverage ic on ic.inventoryid=i.inventoryid group by i.inventoryid ;", Cnn);
                    string cmd1 = "select I.Barcode, I.InventoryName, I.Description ,C.Description as CategoryName,I.Price,I.Price2,I.Price3,I.Price4,I.onhand as Stock,ic.Unitcost,i.NoPriceShift,I.Group1,I.Group2,I.Group3,I.Group4,I.Group5,I.StockCode,I.Unit,I.Notes,I.Imagepath,sum(pquantity-(CutQuantity+RetailQty))as OnHand   from " + BranchAlias + ".inventory as I  join {0}.inventorycategories  as c ON I.Categoryid=c.categoryid  join {0}.inventorycostaverage ic on ic.inventoryid=i.inventoryid 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=InventoryMaster.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>";   // ( No issue is there but import working )
                    //string style = @"&lt;style> .text { mso-number-format:\@; } </style> ";     //( No's issue settle but import not working )  
                    //Response.Write(style);
                    //Response.Output.Write(sw.ToString());
                    //Response.Flush();
                    //Response.End();

                    ////nid added for CSV Export on 22-Jun-2021
                    ////Build the CSV file data as a Comma separated string.
                    //string csv = string.Empty;
                    //String zwnbsp = "\xfeff";

                    //foreach (DataColumn column in Dt1.Columns)
                    //{
                    //    //Add the Header row for CSV file.
                    //    csv += zwnbsp;
                    //    csv += column.ColumnName + ',';
                    //}

                    ////Add new line.
                    //csv += "\r\n";

                    //foreach (DataRow row in Dt1.Rows)
                    //{
                    //    foreach (DataColumn column in Dt1.Columns)
                    //    {
                    //        //Add the Data rows.
                    //        //csv += zwnbsp;
                    //        if (row[column.ColumnName].ToString().Contains(","))
                    //        {
                    //            //column.ColumnName = "\"" + row[column.ColumnName.ToString()] + "\"";
                    //            string rStr = "\"" + row[column.ColumnName.ToString()] + "\"";
                    //            //csv += column.ColumnName + ',';
                    //            csv += rStr + ',';
                    //        }
                    //        else
                    //        {
                    //            csv += zwnbsp;
                    //            csv += row[column.ColumnName].ToString().Replace(",", ";") + ',';
                    //        }
                    //    }

                    //    //Add new line.
                    //    csv += "\r\n";
                    //}

                    ////Download the CSV file.
                    //Response.Clear();
                    //Response.Buffer = true;
                    //Response.AddHeader("content-disposition", "attachment;filename="+ BranchFullName + "_InventoryMaster.csv");
                    //Response.Charset = "";
                    //Response.ContentType = "application/text";
                    ////Response.ContentEncoding = System.Text.Encoding.UTF8;
                    //Response.Output.Write(csv);
                    ////Response.Output.Write(csv, Encoding.ASCII.GetPreamble(), 0, Encoding.ASCII.GetPreamble().Length);
                    ////Response.Output.Write(csv, Encoding.GetEncoding (1252) );
                    //Response.Flush();
                    //Response.End();


                    //4.CSVHelper Memmory stream write method on 20-Jan-2023
                    var memoryStream = new MemoryStream();
                    //using (var swriter = new StreamWriter(memoryStream))      //nid hide on 13-Mar-2023
                    using (var swriter = new StreamWriter(memoryStream, Encoding.GetEncoding("utf-8"))) //nid added for rectify Chinese Language issue on 13-Mar-2023

                    {
                        using (var csv = new CsvWriter(swriter, CultureInfo.InvariantCulture))
                        using (var CHAIN = Dt1)
                        {

                            foreach (DataColumn column in CHAIN.Columns)
                            {
                                csv.WriteField(column.ColumnName);
                            }
                            csv.NextRecord();


                            foreach (DataRow row in CHAIN.Rows)
                            {

                                for (var i = 0; i < CHAIN.Columns.Count; i++)
                                {
                                    csv.WriteField(row[i]);
                                }
                                csv.NextRecord();
                            }

                            swriter.Flush();
                            memoryStream.Seek(0, SeekOrigin.Begin);
                            var resultInBytes = memoryStream.ToArray();

                            Response.Clear();
                            Response.ContentType = "text/csv"; // or application/force-download
                            Response.AddHeader("content-disposition", "attachment; filename=" + BranchFullName + "_InventoryMaster.csv");
                            Response.BinaryWrite(resultInBytes);
                            Response.End();
                            memoryStream.Flush();
                            memoryStream.Close();
                        }
                    }


                }
                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 )
                                                                                                                                                   // Modified This query Based in Excel Standard Import Format :10-02-20
                                                                                                                                                   //MySqlCommand cmd1 = new MySqlCommand("select *,sum(pquantity-(CutQuantity+RetailQty))as OnHandICA from " + BranchAlias + ".inventory as I  join " + BranchAlias + ".inventorycategories  as c ON I.Categoryid=c.categoryid  join " + BranchAlias + ".inventorycostaverage ic on ic.inventoryid=i.inventoryid group by i.inventoryid ", Cnn);
                                                                                                                                                   //sum(pquantity-(CutQuantity+RetailQty))as OnHand  john added on 06-April-2020 show pn hand on export inventory
                                                                                                                                                   //MySqlCommand cmd1 = new MySqlCommand("select I.Barcode , I.InventoryName, I.Description ,C.CategoryID,I.Price,I.Price2,I.Price3,I.Price4,I.onhand as Stock,ic.Unitcost,i.NoPriceShift,I.Group1,I.Group2,I.Group3,I.Group4,I.Group5,I.StockCode,I.Unit,I.CommissionPercent1,I.CommissionPercent2,I.CommissionPercent3,I.CommissionAmount1,I.CommissionAmount2,I.ERPItemCode1,I.ERPItemCode2,I.ERPItemDesc,I.Imagepath,sum(pquantity-(CutQuantity+RetailQty))as OnHand   from " + BranchAlias + ".inventory as I  join " + BranchAlias + ".inventorycategories  as c ON I.Categoryid=c.categoryid  join " + BranchAlias + ".inventorycostaverage ic on ic.inventoryid=i.inventoryid group by i.inventoryid ;", Cnn);
                    string cmd1 = "select I.Barcode , I.InventoryName, I.Description ,C.Description as CategoryName,I.Price,I.Price2,I.Price3,I.Price4,I.onhand as Stock,ic.Unitcost,i.NoPriceShift,I.Group1,I.Group2,I.Group3,I.Group4,I.Group5,I.StockCode,I.Unit,I.Notes,I.Imagepath,sum(pquantity-(CutQuantity+RetailQty))as OnHand   from {0}.inventory as I  join {0}.inventorycategories  as c ON I.Categoryid=c.categoryid  join {0}.inventorycostaverage ic on ic.inventoryid=i.inventoryid 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=InventoryMaster.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>";     // ( No issue is there but import working )
                    //string style = @"&lt;style> .text { mso-number-format:\@; } </style> ";     //( No's issue settle but import not working ) 
                    //Response.Write(style);
                    //Response.Output.Write(sw.ToString());
                    //Response.Flush();
                    //Response.End();

                    //2. Record update to CSV method
                    ////nid added for CSV Export on 22-Jun-2021

                    ////Build the CSV file data as a Comma separated string.
                    //string csv = string.Empty;
                    //String zwnbsp = "\xfeff";
                    //foreach (DataColumn column in Dt1.Columns)
                    //{
                    //    //Add the Header row for CSV file.
                    //    csv += zwnbsp;
                    //    csv += column.ColumnName + ',';
                    //}

                    ////Add new line.
                    //csv += "\r\n";

                    //foreach (DataRow row in Dt1.Rows)
                    //{
                    //    foreach (DataColumn column in Dt1.Columns)
                    //    {
                    //        //Add the Data rows.
                    //        //csv += zwnbsp;
                    //        if (row[column.ColumnName].ToString().Contains(","))
                    //        {
                    //            //column.ColumnName = "\"" + row[column.ColumnName.ToString()] + "\"";
                    //            //csv += column.ColumnName + ',';
                    //            string rstr = "\"" + row[column.ColumnName.ToString()] + "\"";
                    //            csv += rstr + ',';
                    //        }
                    //        else
                    //        {
                    //            csv += zwnbsp;
                    //            csv += row[column.ColumnName].ToString().Replace(",", ";") + ',';
                    //        }
                    //    }

                    //    //Add new line.
                    //    csv += "\r\n";
                    //}


                    ////Download the CSV file.
                    //Response.Clear();
                    //Response.Buffer = true;
                    //Response.AddHeader("content-disposition", "attachment;filename=" + BranchFullName + "_InventoryMaster.csv");
                    //Response.Charset = "";
                    //Response.ContentType = "application/text";
                    ////Response.ContentEncoding = System.Text.Encoding.UTF8;
                    //Response.Output.Write(csv);
                    ////Response.Output.Write(csv, Encoding.GetEncoding(1252));
                    //Response.Flush();
                    //Response.End();


                    //3. CSVHelper nuget package method on 20-Jan-2023
                    ////var writer = new StreamWriter("C://"+BranchFullName + "_InventoryMaster.csv");
                    //var writer = new StreamWriter(BranchFullName + "_InventoryMaster.csv");
                    //var csvW = new CsvWriter(writer, CultureInfo.InvariantCulture);
                    //{
                    //        foreach (DataColumn dc in Dt1.Columns)
                    //        {
                    //            //csv.WriteField(dc.ColumnName);
                    //            csvW.WriteField(dc.ColumnName);
                    //        }
                    //        csvW.NextRecord();

                    //        foreach (DataRow dr in Dt1.Rows)
                    //        {
                    //            foreach (DataColumn dc in Dt1.Columns)
                    //            {
                    //                csvW.WriteField(dr[dc]);
                    //            }
                    //            csvW.NextRecord();
                    //        }

                    //    //writer.ToString().Dump();
                    //    writer.Write(csvW.ToString());
                    //    //writer.Flush();
                    //    csvW.Dispose();
                    //    //writer.Close();
                    //}
                    ////Download the CSV file.
                    ////Response.Clear();
                    ////Response.Buffer = true;
                    ////Response.AddHeader("content-disposition", "attachment;filename=" + BranchFullName + "_InventoryMaster.csv");
                    ////Response.Charset = "";
                    ////Response.ContentType = "application/text";
                    //////Response.ContentEncoding = System.Text.Encoding.UTF8;
                    ////Response.TransmitFile(Server.MapPath( BranchFullName + "_InventoryMaster.csv"));
                    //////Response.WriteFile(BranchFullName + "_InventoryMaster.csv");
                    //////Response.Output.Write(csv, Encoding.GetEncoding(1252));
                    ////Response.Flush();
                    ////Response.End();
                    ////csvW.Dispose();
                    ////writer.Close();


                    //4.CSVHelper Memmory stream write method on 20-Jan-2023
                    var memoryStream = new MemoryStream();
                    //using (var swriter = new StreamWriter(memoryStream))      //nid hide on 13-Mar-2023
                    using (var swriter = new StreamWriter(memoryStream, Encoding.GetEncoding("utf-8"))) //nid added for rectify Chinese Language issue on 13-Mar-2023
                    {
                        using (var csv = new CsvWriter(swriter, CultureInfo.InvariantCulture))
                        using (var CHAIN = Dt1)
                        {

                            foreach (DataColumn column in CHAIN.Columns)
                            {
                                csv.WriteField(column.ColumnName);
                            }
                            csv.NextRecord();


                            foreach (DataRow row in CHAIN.Rows)
                            {

                                for (var i = 0; i < CHAIN.Columns.Count; i++)
                                {
                                    csv.WriteField(row[i]);
                                }
                                csv.NextRecord();
                            }

                            swriter.Flush();
                            memoryStream.Seek(0, SeekOrigin.Begin);
                            var resultInBytes = memoryStream.ToArray();

                            Response.Clear();
                            Response.ContentType = "text/csv"; // or application/force-download
                            Response.AddHeader("content-disposition", "attachment; filename=" + BranchFullName + "_InventoryMaster.csv");
                            Response.BinaryWrite(resultInBytes);
                            Response.End();
                            memoryStream.Flush();
                            memoryStream.Close();
                        }
                    }



                }

            }

        }

        protected void btnExportMSBarcode_Click(object sender, EventArgs e)
        {
            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 (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)
                {
                    string cmd1 = "Select masterbarcode,slavebarcode from {0}.Inventorymulticode";
                    string command = string.Format(cmd1, BranchAlias);
                    DataSet ds = new DataSet();
                    DataTable DtMSBarcode = new DataTable();

                    DtMSBarcode = ObjMain.GetData_DT(command);
                    //Create a dummy GridView
                    GridView GridView1 = new GridView();
                    GridView1.ShowFooter = true;


                    GridView1.AllowPaging = false;
                    GridView1.DataSource = DtMSBarcode;
                    GridView1.DataBind();
                    Response.Clear();
                    Response.Buffer = true;
                    Response.AddHeader("content-disposition",
                     "attachment;filename=MasterSlaveBarcode.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
                {

                    string cmd1 = "Select masterbarcode,slavebarcode from {0}.Inventorymulticode ";

                    string command = string.Format(cmd1, BranchAlias);
                    DataSet ds = new DataSet();
                    DataTable DtMSBarcode = new DataTable();
                    DtMSBarcode = ObjMain.GetData_DT(command);

                    //Create a dummy GridView
                    GridView GridView1 = new GridView();
                    GridView1.ShowFooter = true;


                    GridView1.AllowPaging = false;
                    GridView1.DataSource = DtMSBarcode;
                    GridView1.DataBind();
                    Response.Clear();
                    Response.Buffer = true;
                    Response.AddHeader("content-disposition",
                     "attachment;filename=MasterSlaveBarcode.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();
                }

            }

        }

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


                string _branch = ActiveCallvalue != null ? ActiveCallvalue.ToString() : "";
               
            }
            else
            {
                Response.Redirect("Login.aspx");

            }

        }

        protected void btnUpdateInv_Click(object sender, EventArgs e)
        {
            if (txtBarcode.Text == "")
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Please enter valid Barcode ') ", true);
                return;
            }
            if (cmbCategoryName.SelectedIndex != 0)
            {

                UpdateInventoryInfo();
                // SaveImage();     Old Approach for saving image 
                // MakeTaxSetting();
                txtReadInventroyId.Text = string.Empty;
                cmbCategoryName.SelectedIndex = 0;
                txtBarcode.Text = "";
                txtInventoryName.Text = "";
                txtPrice1.Text = "";
                txtPrice2.Text = "";
                txtPrice3.Text = "";
                txtDescription.Text = "";
                ClearInvForm();
                dtimg.DataSource = null;
                dtimg.DataBind();
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Inventory Updated Successfully ');location.href='InventoryMaster.aspx' ", true);


            }
            else
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' You must select the CategoryName ') ", true);
            }
        }

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

            }
            #endregion

            string ReadInventoryidOnScheduleFlag = "select Barcode from {0}.inventory where  Barcode=@Barcode ; ";
            string command_ReadScheduleflag = string.Format(ReadInventoryidOnScheduleFlag, BranchAlias);
            MySqlParameter[] parameters =
            {
                     new MySqlParameter("@Barcode",_Barcode),
                    };
            _barcode = ObjMain.NewExecuteScalar(command_ReadScheduleflag, parameters);

            return _barcode;

        }

        public void UpdateInventoryInfo()
        {
            // Prevention XSS
            // Prevention SQL Injection 

            string sSpicy = string.Empty;
            string sChef = string.Empty;
            string sBeef = string.Empty;
            string sChicken = string.Empty;
            string sPork = string.Empty;
            string sTakeAway = string.Empty;

            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


            }




            UPT_MakeTaxSetting();                       //  Update - Tax Setting 
            Flag2Value2();                                    // Printer Setting 



            ObjPL.InventoryId = txtReadInventroyId.Text;
            ObjPL.Units = cmbUnits.SelectedItem.Text;

            if (txtPrice1.Text == "")
            {
                ObjPL.Price1 = 0;
            }
            else
            {
                ObjPL.Price1 = Convert.ToDecimal(txtPrice1.Text);
            }
            if (txtPrice2.Text == "")
            {
                ObjPL.Price2 = 0;
            }
            else
            {
                ObjPL.Price2 = Convert.ToDecimal(txtPrice2.Text);
            }

            if (txtPrice3.Text == "")
            {
                ObjPL.Price3 = 0;
            }
            else
            {
                ObjPL.Price3 = Convert.ToDecimal(txtPrice3.Text);
            }

            if (txtPrice4.Text == "")
            {
                ObjPL.Price4 = 0;
            }
            else
            {
                ObjPL.Price4 = Convert.ToDecimal(txtPrice4.Text);
            }

            if (txtReorder.Text == "")
            {
                ObjPL.ReoderLevel = 0;
            }
            else
            {
                ObjPL.ReoderLevel = Convert.ToInt64(txtReorder.Text);
            }

            if (txtSafty.Text == "")
            {
                ObjPL.SaftyLevel = 0;
            }
            else
            {
                ObjPL.SaftyLevel = Convert.ToInt64(txtSafty.Text);
            }

            if (txtMaximum.Text == "")
            {
                ObjPL.MaixmumLevel = 0;
            }
            else
            {
                ObjPL.MaixmumLevel = Convert.ToInt64(txtMaximum.Text);
            }
            if (hidenInventoryTax.Value == "")
            {
                TaxValue2();
            }
            if (HideInvenPrinter.Value == "")
            {
                Flag2Value2();
            }
            if (cmbGroup1.SelectedIndex == 0)
            {
                cmbGroup1.SelectedItem.Text = "";
            }
            if (cmbGroup2.SelectedIndex == 0)
            {
                cmbGroup2.SelectedItem.Text = "";
            }
            if (cmbGroup3.SelectedIndex == 0)
            {
                cmbGroup3.SelectedItem.Text = "";
            }
            if (cmbGroup4.SelectedIndex == 0)
            {
                cmbGroup4.SelectedItem.Text = "";
            }
            if (cmbGroup5.SelectedIndex == 0)
            {
                cmbGroup5.SelectedItem.Text = "";
            }


            // Active or Inactive Value 

            if (chkActiveStatus.Checked == true)
            {
                ObjPL.AciveValue = "1";
            }
            else
            {
                ObjPL.AciveValue = "0";
            }

            //John added on 07-Aug-2020
            if (chkSpicy.Checked == true)
            {
                sSpicy = "1";
            }
            else
            {
                sSpicy = "0";
            }

            if (chkChef.Checked == true)
            {
                sChef = "1";
            }
            else
            {
                sChef = "0";
            }

            if (chkBeef.Checked == true)
            {
                sBeef = "1";
            }
            else
            {
                sBeef = "0";
            }

            if (chkChicken.Checked == true)
            {
                sChicken = "1";
            }
            else
            {
                sChicken = "0";
            }

            if (chkPork.Checked == true)
            {
                sPork = "1";
            }
            else
            {
                sPork = "0";
            }

            if (chkTA.Checked == true)
            {
                sTakeAway = "1";
            }
            else
            {
                sTakeAway = "0";
            }

            if (ChkNotAvailable.Checked == true)
            {
                sAvailable = "1";
            }
            else
            {
                sAvailable = "0";
            }

            if (ChkShowItem.Checked == true)
            {
                sShowItem = "1";
            }
            else
            {
                sShowItem = "0";
            }

            if (chkMainProductRelation.Checked == true)
            {
                sProductRelationMain = "1";
            }
            else
            {
                sProductRelationMain = "0";
            }

            if (chkNotIncludeProductRelation.Checked == true)
            {
                sProductRelationNotInculde = "1";
            }
            else
            {
                sProductRelationNotInculde = "0";
            }


            if (ChkShowItem.Checked == true)
            {
                // Promo checks
                if (chkPromo.Checked == true)
                {
                    sPromo = "1";
                }
                else
                {
                    sPromo = "0";
                }
            }
            else
            {
                sPromo = "0";
            }


            // No Discount : (NoPriceShift)
            if (ChkNoDiscount.Checked == true)
            {
                sNodiscount = "1";
            }
            else
            {
                sNodiscount = "0";
            }

            //Product Relation //john added on 18-Sept-2024
                if (chkMainProductRelation.Checked == true)
            {
                sProductRelationMain = "1";
            }
            else
            {
                sProductRelationMain = "0";
            }

            if (chkNotIncludeProductRelation.Checked == true)
            {
                sProductRelationNotInculde = "1";
            }
            else
            {
                sProductRelationNotInculde = "0";
            }


            // Calling S3 image FileUpload
            // SaveImagedetailstoS3(BranchAlias, txtReadInventroyId.Text);  Removed Here . This Function Called Upload Button itself 

            //==========================
            //string Query = "Update " + BranchAlias + ".Inventory Set InventoryName='" + txtInventoryName.Text + "', Description='" + txtDescription.Text + "', CategoryID=" + cmbCategoryName.SelectedValue + ", " +
            //    " Class=" + cmbClass.SelectedItem.Value + ",Unit='" + ObjPL.Units + "',Price=" + ObjPL.Price1 + ",Price2=" + ObjPL.Price2 + ",Price3=" + ObjPL.Price3 + ", Price4=" + ObjPL.Price4 + ", Group1='" + cmbGroup1.SelectedItem.Text + "',Group2='" + cmbGroup2.SelectedItem.Text + "', " +
            //    " Group3='" + cmbGroup3.SelectedItem.Text + "',Group4='" + cmbGroup4.SelectedItem.Text + "',Group5='" + cmbGroup5.SelectedItem.Text + "',  Active= '" + ObjPL.AciveValue + "' ,  " +
            //    " StockCode='" + txtStockCode.Text + "',Flag1='" + hidNewTax.Value + "',Flag2='" + HideInvenPrinter.Value + "',ReorderLevel=" + ObjPL.ReoderLevel + ",MaxiumLevel=" + ObjPL.MaixmumLevel + ",SafetyLevel=" + ObjPL.SaftyLevel + ", " +
            //    " WebIcon1= '" + sSpicy + "',WebIcon2 = '" + sChef + "', WebIcon3='" + sBeef + "',WebIcon4='" + sChicken + "',WebIcon5='" + sPork + "'" +
            //    " Where InventoryID=" + ObjPL.InventoryId + " ";


            if (hdnfileid.Value != "")
            {

                string sWebpriceCaptionID = ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text); // JOHN ADDED ON 13-JAN-2021
                //john added productrelationmain,productrelationnotinclude on 18-Sept-2024
                string Query = "Update {0}.Inventory Set InventoryName=@InventoryName, Description=@Description, CategoryID=@CategoryID , " +
                   " Class=@Class,Unit=@Unit,Price=@Price,Price2=@Price2,Price3=@Price3, Price4=@Price4 , " +
                   " Group1=@Group1,Group2=@Group2 , " +
                   " Group3=@Group3,Group4=@Group4,Group5=@Group5,NoPriceShift=@NoPriceShift,Active= @Active, " +
                   " StockCode=@StockCode,Flag1=@Flag1,Flag2=@Flag2,ReorderLevel=@ReorderLevel,MaxiumLevel=@MaxiumLevel,SafetyLevel=@SafetyLevel , " +
                   " TakeAwayFlag =@TakeAwayFlag,OutofStock=@OutofStock ,showitem=@showitem, webpricecaptionid = @webpricecaptionid,Notes=@Notes , " +
                   " imagepath=@imagepath,Fileid=@Fileid,Promo=@Promo,TAId=@TAId, " +
                   " productrelationmain = @productrelationmain,productrelationnotinclude=@productrelationnotinclude,WebstockCount=@WebstockCount " +
                   " Where InventoryID=@InventoryID " ;
                string command = string.Format(Query, BranchAlias);
                MySqlParameter[] parameters =
                   {

                     new MySqlParameter("@InventoryName",txtInventoryName.Text.ToString().Trim()),
                     new MySqlParameter("@Description",txtDescription.Text.ToString().Trim()),
                     new MySqlParameter("@CategoryID",cmbCategoryName.SelectedValue),
                     new MySqlParameter("@Class",cmbClass.SelectedItem.Value),
                     new MySqlParameter("@Unit",ObjPL.Units),
                     new MySqlParameter("@Price",ObjPL.Price1),
                     new MySqlParameter("@Price2",ObjPL.Price2),
                     new MySqlParameter("@Price3",ObjPL.Price3),
                     new MySqlParameter("@Price4",ObjPL.Price4),
                     new MySqlParameter("@Group1",cmbGroup1.SelectedItem.Text),
                     new MySqlParameter("@Group2",cmbGroup2.SelectedItem.Text),
                     new MySqlParameter("@Group3",cmbGroup3.SelectedItem.Text),
                     new MySqlParameter("@Group4",cmbGroup4.SelectedItem.Text),
                     new MySqlParameter("@Group5",cmbGroup5.SelectedItem.Text),
                     new MySqlParameter("@NoPriceShift",sNodiscount),
                     new MySqlParameter("@Active",ObjPL.AciveValue),
                     new MySqlParameter("@StockCode",txtRStockCode.Text),
                     new MySqlParameter("@Flag1",hidNewTax.Value),
                     new MySqlParameter("@Flag2",HideInvenPrinter.Value),
                     new MySqlParameter("@ReorderLevel",ObjPL.ReoderLevel),
                     new MySqlParameter("@MaxiumLevel",ObjPL.MaixmumLevel),
                     new MySqlParameter("@SafetyLevel",ObjPL.SaftyLevel),
                     new MySqlParameter("@TakeAwayFlag",sTakeAway),
                     new MySqlParameter("@OutofStock",sAvailable),
                     new MySqlParameter("@showitem",sShowItem),
                     new MySqlParameter("@webpricecaptionid",sWebpriceCaptionID),
                     new MySqlParameter("@Notes", txtNotes.Text),
                     new MySqlParameter("@imagepath",hdnurl.Value),
                     new MySqlParameter("@Fileid",FileID),
                     new MySqlParameter("@Promo",sPromo),
                     new MySqlParameter("@TAId",cmbTakeAway.SelectedValue),
                     new MySqlParameter("@productrelationmain",sProductRelationMain),
                     new MySqlParameter("@productrelationnotinclude", sProductRelationNotInculde),
                     new MySqlParameter("@WebstockCount", Convert.ToDecimal(txtWebstockcount.Text)),
                     new MySqlParameter("@InventoryID", ObjPL.InventoryId),
                     };

                K = ObjMain.ExecuteQuery(command, parameters);

                UpdatePriceFlag(BranchAlias, ObjPL.InventoryId);

            }
            else
            {

                string sWebpriceCaptionID = ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text); // JOHN ADDED ON 13-JAN-2021
                string Query = "Update {0}.Inventory Set  InventoryName=@InventoryName, Description=@Description, CategoryID=@CategoryID , " +
                  " Class=@Class,Unit=@Unit,Price=@Price,Price2=@Price2,Price3=@Price3, Price4=@Price4 , " +
                  " Group1=@Group1,Group2=@Group2,Group3=@Group3,Group4=@Group4,Group5=@Group5,NoPriceShift=@NoPriceShift,Active= @Active ," +
                  " StockCode=@StockCode,Flag1=@Flag1,Flag2=@Flag2,ReorderLevel=@ReorderLevel,MaxiumLevel=@MaxiumLevel,SafetyLevel=@SafetyLevel , " +
                  " TakeAwayFlag=@TakeAwayFlag,OutofStock=@OutofStock,showitem=@showitem, webpricecaptionid=@webpricecaptionid,Notes=@Notes, " +
                  " Promo=@Promo,TAId=@TAId,  " +
                  " productrelationmain = @productrelationmain,productrelationnotinclude=@productrelationnotinclude,WebstockCount=@WebstockCount " +
                  " Where InventoryID=@InventoryID ";
                string command = string.Format(Query, BranchAlias);
                MySqlParameter[] parameters =
                   {

                     new MySqlParameter("@InventoryName",txtInventoryName.Text.ToString().Trim()),
                     new MySqlParameter("@Description",txtDescription.Text.ToString().Trim()),
                     new MySqlParameter("@CategoryID",cmbCategoryName.SelectedValue),
                     new MySqlParameter("@Class",cmbClass.SelectedItem.Value),
                     new MySqlParameter("@Unit",ObjPL.Units),
                     new MySqlParameter("@Price",ObjPL.Price1),
                     new MySqlParameter("@Price2",ObjPL.Price2),
                     new MySqlParameter("@Price3",ObjPL.Price3),
                     new MySqlParameter("@Price4",ObjPL.Price4),
                     new MySqlParameter("@Group1",cmbGroup1.SelectedItem.Text),
                     new MySqlParameter("@Group2",cmbGroup2.SelectedItem.Text),
                     new MySqlParameter("@Group3",cmbGroup3.SelectedItem.Text),
                     new MySqlParameter("@Group4",cmbGroup4.SelectedItem.Text),
                     new MySqlParameter("@Group5",cmbGroup5.SelectedItem.Text),
                     new MySqlParameter("@NoPriceShift",sNodiscount),
                     new MySqlParameter("@Active",ObjPL.AciveValue),
                     new MySqlParameter("@StockCode",txtRStockCode.Text),
                     new MySqlParameter("@Flag1",hidNewTax.Value),
                     new MySqlParameter("@Flag2",HideInvenPrinter.Value),
                     new MySqlParameter("@ReorderLevel",ObjPL.ReoderLevel),
                     new MySqlParameter("@MaxiumLevel",ObjPL.MaixmumLevel),
                     new MySqlParameter("@SafetyLevel",ObjPL.SaftyLevel),
                     new MySqlParameter("@TakeAwayFlag",sTakeAway),
                     new MySqlParameter("@OutofStock",sAvailable),
                     new MySqlParameter("@showitem",sShowItem),
                     new MySqlParameter("@webpricecaptionid",sWebpriceCaptionID),
                     new MySqlParameter("@Notes", txtNotes.Text),
                     new MySqlParameter("@Promo",sPromo),
                     new MySqlParameter("@TAId",cmbTakeAway.SelectedValue),
                     new MySqlParameter("@productrelationmain",sProductRelationMain),
                     new MySqlParameter("@productrelationnotinclude", sProductRelationNotInculde),
                     new MySqlParameter("@WebstockCount", Convert.ToDecimal(txtWebstockcount.Text)),
                     new MySqlParameter("@InventoryID", ObjPL.InventoryId),
                     };

                K = ObjMain.ExecuteQuery(command, parameters);
                UpdatePriceFlag(BranchAlias, ObjPL.InventoryId);


            }


            //if (sPromo == "0") //John added on 16-Aug-2021 Validate if Item is WebOrderPromo
            //{
            //    RemovePromoItem(BranchAlias, ObjPL.InventoryId); //Remove Item in WebOrderPromo Table
            //}
            //else if (chkPromo.Checked == true)
            //{
            //    SavePromoItem(BranchAlias, ObjPL.InventoryId, txtBarcode.Text); //Save Item in WebOrderPromo Table
            //}

        }

        /// <summary>
        ///  This Function Updates the PriceFlag Values Using InventoryId 
        /// </summary>
        /// <param name="sdb"></param>
        /// <param name="Inventoryid"></param>
        public void UpdatePriceFlag(string sdb, string Inventoryid)
        {
            string PriceVal = string.Empty, Price2Val = string.Empty, Price3Val = string.Empty, Price4Val = string.Empty;


            if (chkPrice1.Checked == true)
            {

                PriceVal = "1";
            }
            else if (chkPrice1.Checked == false)
            {
                PriceVal = "0";
            }

            if (chkPrice2.Checked == true)
            {

                Price2Val = "1";
            }
            else if (chkPrice2.Checked == false)
            {
                Price2Val = "0";
            }
            if (chkPrice3.Checked == true)
            {

                Price3Val = "1";
            }
            else if (chkPrice3.Checked == false)
            {
                Price3Val = "0";
            }
            if (chkPrice4.Checked == true)
            {

                Price4Val = "1";
            }
            else if (chkPrice4.Checked == false)
            {
                Price4Val = "0";
            }


            string TQuery = "Update  {0}.PriceFlag set Price_Flag=@Price_Flag, Price2_Flag=@Price2_Flag,Price3_Flag=@Price3_Flag,Price4_Flag=@Price4_Flag where  inventoryid=@inventoryid ;";
            string Tcommand = string.Format(TQuery, sdb);
            MySqlParameter[] Tparameters =
                         {
                             new MySqlParameter("@Price_Flag",PriceVal),
                             new MySqlParameter("@Price2_Flag",Price2Val),
                             new MySqlParameter("@Price3_Flag",Price3Val),
                             new MySqlParameter("@Price4_Flag",Price4Val),
                             new MySqlParameter("@inventoryid",Inventoryid),

                            };

            K = ObjMain.ExecuteQuery(Tcommand, Tparameters);

        }

        //public void LoadCategoriesDataList()   Date28
        //{

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

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

        //}

        //protected void cmbCategorySarch_SelectedIndexChanged(object sender, EventArgs e)
        //{
        //    ModalPopupExtender7.Show();

        //    //Page.ClientScript.RegisterStartupScript(this.GetType(), "hash", "location.hash = '#GridContend';", 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
        //    {
        //        BranchAlias = Session["Branch_HQ"].ToString();
        //    }

        //    if (cmbCategorySarch.SelectedIndex != 0)
        //    {
        //        string sActivex = string.Empty;

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


        //        //string Inv_Qry5 = "select * from " + BranchAlias + ".inventory as I join  " + BranchAlias + ".inventorycategories  as c ON I.Categoryid=c.categoryid ORDER BY I.inventoryID asc LIMIT " + txtTop.Text.ToString().Trim() + "";
        //        string Inv_Qry5 = "Select *,sum(pquantity-(CutQuantity+RetailQty))as OnHandICA from " + 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=" + cmbCategorySarch.SelectedItem.Value + "   " + sActivex + "    group by I.inventoryid";
        //        DT = ObjMain.GetData_DT(Inv_Qry5);
        //        grdInventoryView.DataSource = DT;
        //        grdInventoryView.DataBind();
        //        txtSearchVal.Text = "";
        //        lblSearchResult.Text = "SEARCH RESULT";
        //    }

        //}

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

                }
                #endregion
            }
            else
            {
                BranchAlias = Session["Branch_HQ"].ToString();
            }
            if (cmbSearch.SelectedIndex == 1)
            {
                
               // LoadInventoryview();  Karthi   Hided on 07-10-2025
                txtSearchVal.Enabled = true;
                grdInventoryView.DataSource = null;
                grdInventoryView.DataBind();


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

                //LoadInventoryview();
                grdInventoryView.DataSource = null;
                grdInventoryView.DataBind();
            }
            else if (cmbSearch.SelectedIndex == 3)
            {
               
               // LoadInventoryview();
                txtSearchVal.Enabled = true;
                grdInventoryView.DataSource = null;
                grdInventoryView.DataBind();
            }
            else if (cmbSearch.SelectedIndex == 4)
            {

                // LoadInventoryview();
                grdInventoryView.DataSource = null;
                grdInventoryView.DataBind();
            }
            else if (cmbSearch.SelectedIndex == 5)
            {
                
                // LoadInventoryview();
                txtSearchVal.Enabled = true;
                grdInventoryView.DataSource = null;
                grdInventoryView.DataBind();
            }
            if (cmbSearch.SelectedIndex == 6)
            {
                
                txtSearchVal.Enabled = true;
                grdInventoryView.DataSource = null;
                grdInventoryView.DataBind();
            }
            else if (cmbSearch.SelectedIndex == 1 || cmbSearch.SelectedIndex == 2 || cmbSearch.SelectedIndex == 3 || cmbSearch.SelectedIndex == 4 || cmbSearch.SelectedIndex == 5 || cmbSearch.SelectedIndex == 6)
            {

            }
            else
            {
                // LoadInventoryview();
            }

            if (cmbSearch.SelectedIndex == 7)
            {

                txtSearchVal.Text = "";
                grdInventoryView.DataSource = null;
                grdInventoryView.DataBind();

            }




        }

        protected void cmbSGroups_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbSearch.SelectedIndex == 8)
            {
                string group1Value = "group1";
                LoadGroupDetail(group1Value, txtSearchVal.Text.ToString().Trim());

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

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

            }

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

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

            }




        }

        public void LoadGroupDetail(string groupname, string SearchText)
        {



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

                }
                #endregion

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




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


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

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

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

                    };


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

        }

        public void  ActiveCall()
          {

            string _default_branch = ObjMain.ExecuteScalar("select DefaultBranch from portaldb.companymaster where cm_id = " + Session["CM_ID"] + ";");

            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.GETBrachAlias8(Session["CM_ID"].ToString(), Session["Branch_HQ"].ToString(), Session["UserId"].ToString());
                }

                #endregion




            }

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

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

            if (ReadHQ == "HQ")
            {
                cmbBranches.Items.FindByText(ReadHQ).Selected = true;
            }
            else
            {
                Curr_BranchFullName = ObjUserBL.GetBranchCurr_BranchVal(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), cd_BranchAlias);
                Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), Curr_BranchFullName);  // This will Return BranchName( Actual Database Name )
                cmbBranches.Items.FindByText(Curr_BranchFullName).Selected = true;
                Branchidval = ObjUserBL.GetBranchIDbyName(ActiveCallvalue, ActiveCallvalue);

            }

            #endregion
           if (Branchidval != "")
            {
                DT = ObjUserBL.GetPageRightsDetailsPIDNew(Session["UserId"].ToString(), PID, Branchidval);
            }
            else
            {
               DT = ObjUserBL.GetPageRightsDetailsPIDNew(Session["UserId"].ToString(), PID, Session["Fistbranch"].ToString());
               

            }

            if (DT.Rows.Count > 0)
            {
                Page_Acess = DT.Rows[0]["Acess_status"].ToString();
                Read_Acess = DT.Rows[0]["Read_Access"].ToString();
                Write_Acess = DT.Rows[0]["Write_Access"].ToString();
                Isdowld_Acess = DT.Rows[0]["IDwld_Access"].ToString();

                Session["Page_Acess"] = Page_Acess;
                Session["Read_Acess"] = Read_Acess;
                Session["Write_Acess"] = Write_Acess;
                Session["Isdowld_Acess"] = Isdowld_Acess;
            }
            Rcd_id = ObjMain.ExecuteScalar("select cd_id from portaldb.companydetails where cd_branchid=" + cmbBranches.SelectedItem.Value + " and cd_branchalias='" + ActiveCallvalue + "';");
            RPortalid = ObjMain.ExecuteScalar("select portaltypeid  from portaldb.invoicedetails where cd_id=" + Rcd_id + ";");
            DtLicense = ObjUserBL.GetLicenseDetails(RPortalid);
            if (DtLicense.Rows.Count > 0)
            {

                L_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

                    // LoadInventoryview();


                    string chk_Condition = ObjMain.ExecuteScalar("select IsWebOrderApp from portaldb.companydetails where  cd_branchAlias='" + BranchAlias + "';");
                    if (chk_Condition.Equals("Y"))
                    {


                        string _inventoryrows = string.Empty;
                        string _priceflagrows = string.Empty;
                        string Inven_sCmd = "Select count(*) as InventoryRows from {0}.Inventory; ";
                        string Invent_command = string.Format(Inven_sCmd, BranchAlias);
                        _inventoryrows = ObjMain.ExecuteScalar(Invent_command);



                        string priceflag_sCmd = "Select count(*) as PriceflagRows from {0}.priceflag; ";
                        string priceflag_command = string.Format(priceflag_sCmd, BranchAlias);
                        _priceflagrows = ObjMain.ExecuteScalar(priceflag_command);

                        if (_inventoryrows != _priceflagrows)
                        {
                            INS_PriceFlage(BranchAlias);
                            INS_WebStock(BranchAlias);
                        }
                    }



                    txtEffectiveDt.Text = Curr_DateOnly;
                    LoadGrp1(BranchAlias);
                    LoadGrp2(BranchAlias);
                    LoadGrp3(BranchAlias);
                    LoadGrp4(BranchAlias);
                    LoadGrp5(BranchAlias);
                    LoadCategoryList(BranchAlias);
                    LoadUnits(BranchAlias);
                    LoadTaxLables();
                    LoadPriceCaptionHeader(BranchAlias); //FOR PRICE CAPTION HEADER JOHN ADDED ON 13-JAN-2021 
                                                         // Loading Tax Combobox

                    LoadTakeawayCharge(BranchAlias);
                    LoadPrinterValue();

                    // Assign s3 realted Parameter values 
                    //  clientname.Value=Session["CM_ID"].ToString();
                    lblclientname.Text = Session["CM_ID"].ToString();
                    lblstorename.Text = BranchAlias;
                    Session["BranchFullName"] = BranchFullName;

                    lblSelectedBranchCaption1.Text = BranchFullName;
                    lblSelctedBranchCaption2.Text = BranchFullName;
                    this.Page.ClientScript.RegisterStartupScript(this.GetType(), "Javascript", "javascript:GetActiveSession5();", true);




                    Session["BranchDB"] = BranchAlias;

                    //string dbValue = BranchAlias;
                    //var encodedValue = HttpUtility.JavaScriptStringEncode(dbValue);
                    //ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "MyFun1", "Loadunitpricelable('"+ encodedValue+"');", true);



                    string safeValue = Server.HtmlEncode(Cmb_BranchName);
                    string script = $"localStorage.setItem('Initialbranch', '{safeValue}');";
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "SetLocalStorage", script, true);






                    #region UnitPrice Hide and Show 

                    string is_view_unitcost = "select inivalue from " + BranchAlias + ".weborderinginisetting where id =82;";
                    string Read_Value_unitcost = ObjMain.ExecuteScalar(is_view_unitcost);
                    string _branch = Session["BranchDB"] != null ? Session["BranchDB"].ToString() : "";
                    ScriptManager.RegisterStartupScript(
                                     this,
                                     this.GetType(),
                                     "Javascript",
                                     $"Loadunitpricelable('{_branch}');",
                                     true
                                 );

                    #endregion



                    btnUpdateInv.Visible = false;
                    btnDelete.Visible = false;
                    txtReadInventroyId.Enabled = false;
                    txtReadInventroyId.CssClass = "form-control";

                    //John added on 31-Oct-2020 PriceCaption
                    //lblPrice1.InnerText = "Price 1 ( " + ObjSel.GetPriceCaption(BranchAlias, 1) + " )";
                    //txtCaptionPrice1.Text = ObjSel.GetPriceCaption(BranchAlias, 1);
                    //lblPrice2.InnerText = "Price 2 ( " + ObjSel.GetPriceCaption(BranchAlias, 2) + " )";
                    //txtCaptionPrice2.Text = ObjSel.GetPriceCaption(BranchAlias, 2);
                    //lblPrice3.InnerText = "Price 3 ( " + ObjSel.GetPriceCaption(BranchAlias, 3) + " )";
                    //txtCaptionPrice3.Text = ObjSel.GetPriceCaption(BranchAlias, 3);
                    //lblPrice4.InnerText = "Price 4 ( " + ObjSel.GetPriceCaption(BranchAlias, 4) + " )";
                    //txtCaptionPrice4.Text = ObjSel.GetPriceCaption(BranchAlias, 4);
                    lblPrice1.InnerText = "Price 1 ( " + ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "1") + " )";
                    txtCaptionPrice1.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "1");
                    lblPrice2.InnerText = "Price 2 ( " + ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "2") + " )";
                    txtCaptionPrice2.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "2");
                    lblPrice3.InnerText = "Price 3 ( " + ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "3") + " )";
                    txtCaptionPrice3.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "3");
                    lblPrice4.InnerText = "Price 4 ( " + ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "4") + " )";
                    txtCaptionPrice4.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "4");

                    //ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderID(BranchAlias), "1");

                    lblclientname.Text = Session["CM_ID"].ToString();
                    lblstorename.Text = BranchAlias;


                    UPDATEBRANCH(BranchAlias);

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


            }
            else
            {

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

                }
                #endregion

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

                    btnSubmit.CssClass = "btn btn-primary";
                    //btnShow.CssClass = "btn btn-success active";
                    btnSubmit.Enabled = false;
                    btnDelete.Enabled = false;
                    //btnShow.Enabled = false;
                }
                else
                {

                }



                // LoadInventoryview();

                string chk_Condition = ObjMain.ExecuteScalar("select IsWebOrderApp from portaldb.companydetails where  cd_branchAlias='" + BranchAlias + "';");
                if (chk_Condition.Equals("Y"))
                {


                    string _inventoryrows = string.Empty;
                    string _priceflagrows = string.Empty;
                    string Inven_sCmd = "Select count(*) as InventoryRows from {0}.Inventory; ";
                    string Invent_command = string.Format(Inven_sCmd, BranchAlias);
                    _inventoryrows = ObjMain.ExecuteScalar(Invent_command);



                    string priceflag_sCmd = "Select count(*) as PriceflagRows from {0}.priceflag; ";
                    string priceflag_command = string.Format(priceflag_sCmd, BranchAlias);
                    _priceflagrows = ObjMain.ExecuteScalar(priceflag_command);

                    if (_inventoryrows != _priceflagrows)
                    {
                        INS_PriceFlage(BranchAlias);
                        INS_WebStock(BranchAlias);
                    }
                }

                txtEffectiveDt.Text = Curr_DateOnly;
                LoadGrp1(BranchAlias);
                LoadGrp2(BranchAlias);
                LoadGrp3(BranchAlias);
                LoadGrp4(BranchAlias);
                LoadGrp5(BranchAlias);
                LoadCategoryList(BranchAlias);
                LoadUnits(BranchAlias);
                LoadPriceCaptionHeader(BranchAlias); //FOR PRICE CAPTION HEADER JOHN ADDED ON 13-JAN-2021 
                LoadTaxLables();
                LoadPrinterValue();
                LoadTakeawayCharge(BranchAlias);
                // Assign s3 realted Parameter values 
                //  clientname.Value=Session["CM_ID"].ToString();
                lblclientname.Text = Session["CM_ID"].ToString();
                lblstorename.Text = BranchAlias;

                BranchFullName = cmbBranches.SelectedItem.Text;

                Session["BranchFullName"] = BranchFullName;
                lblSelectedBranchCaption1.Text = BranchFullName;
                lblSelctedBranchCaption2.Text = BranchFullName;
                this.Page.ClientScript.RegisterStartupScript(this.GetType(), "Javascript", "javascript:GetActiveSession5();", true);

                Session["BranchDB"] = BranchAlias;

               


                string safeValue = Server.HtmlEncode(Cmb_BranchName);
                string script = $"localStorage.setItem('Initialbranch', '{safeValue}');";
                ScriptManager.RegisterStartupScript(this, this.GetType(), "SetLocalStorage", script, true);



                #region UnitPrice Hide and Show 

                string is_view_unitcost = "select inivalue from " + BranchAlias + ".weborderinginisetting where id =82;";
                string Read_Value_unitcost = ObjMain.ExecuteScalar(is_view_unitcost);
                string _branch = Session["BranchDB"] != null ? Session["BranchDB"].ToString() : "";
                ScriptManager.RegisterStartupScript(
                                 this,
                                 this.GetType(),
                                 "Javascript",
                                 $"Loadunitpricelable('{_branch}');",
                                 true
                             );

                #endregion


                // By Default

                btnUpdateInv.Visible = false;
                btnDelete.Visible = false;
                txtReadInventroyId.Enabled = false;
                txtReadInventroyId.CssClass = "form-control";

                //John added on 31-Oct-2020 PriceCaption
                //lblPrice1.InnerText = "Price 1 ( " + ObjSel.GetPriceCaption(BranchAlias, 1) + " )";
                //txtCaptionPrice1.Text = ObjSel.GetPriceCaption(BranchAlias, 1);
                //lblPrice2.InnerText = "Price 2 ( " + ObjSel.GetPriceCaption(BranchAlias, 2) + " )";
                //txtCaptionPrice2.Text = ObjSel.GetPriceCaption(BranchAlias, 2);
                //lblPrice3.InnerText = "Price 3 ( " + ObjSel.GetPriceCaption(BranchAlias, 3) + " )";
                //txtCaptionPrice3.Text = ObjSel.GetPriceCaption(BranchAlias, 3);
                //lblPrice4.InnerText = "Price 4 ( " + ObjSel.GetPriceCaption(BranchAlias, 4) + " )";
                //txtCaptionPrice4.Text = ObjSel.GetPriceCaption(BranchAlias, 4);
                lblPrice1.InnerText = "Price 1 ( " + ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "1") + " )";
                txtCaptionPrice1.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "1");
                lblPrice2.InnerText = "Price 2 ( " + ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "2") + " )";
                txtCaptionPrice2.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "2");
                lblPrice3.InnerText = "Price 3 ( " + ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "3") + " )";
                txtCaptionPrice3.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "3");
                lblPrice4.InnerText = "Price 4 ( " + ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "4") + " )";
                txtCaptionPrice4.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "4");
                UPDATEBRANCH(BranchAlias);
                //ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderID(BranchAlias), "1");
            }

             

            string _branch2 = BranchAlias != null ? BranchAlias.ToString() : "";
            ScriptManager.RegisterStartupScript(
                             this,
                             this.GetType(),
                             "Javascript",
                             $"Loadunitpricelable('{_branch2}');",
                             true
                         );




        }


        public void LoadDefaultCall()
        {

            string _default_branch = ObjMain.ExecuteScalar("select DefaultBranch from portaldb.companymaster where cm_id = " + Session["CM_ID"] + ";");

          


           

            #region  HQ Validation in ActiveCall Function : Starts 
            
           
            #endregion
            if (_default_branch != "")
            {
                DT = ObjUserBL.GetPageRightsDetailsPIDNew(Session["UserId"].ToString(), PID, _default_branch);
            }
          
            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=" + _default_branch + " and cm_id=" + Session["CM_ID"].ToString() + ";");
            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")
                {


                    #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 =ObjMain.ExecuteScalar("select branchfullname from "+ Session["Branch_HQ"] + ".branches where branchid = "+ _default_branch + "");     // 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

                    // LoadInventoryview();


                    string chk_Condition = ObjMain.ExecuteScalar("select IsWebOrderApp from portaldb.companydetails where  cd_branchAlias='" + BranchAlias + "';");
                    if (chk_Condition.Equals("Y"))
                    {


                        string _inventoryrows = string.Empty;
                        string _priceflagrows = string.Empty;
                        string Inven_sCmd = "Select count(*) as InventoryRows from {0}.Inventory; ";
                        string Invent_command = string.Format(Inven_sCmd, BranchAlias);
                        _inventoryrows = ObjMain.ExecuteScalar(Invent_command);



                        string priceflag_sCmd = "Select count(*) as PriceflagRows from {0}.priceflag; ";
                        string priceflag_command = string.Format(priceflag_sCmd, BranchAlias);
                        _priceflagrows = ObjMain.ExecuteScalar(priceflag_command);

                        if (_inventoryrows != _priceflagrows)
                        {
                            INS_PriceFlage(BranchAlias);
                            INS_WebStock(BranchAlias);
                        }
                    }



                    txtEffectiveDt.Text = Curr_DateOnly;
                    LoadGrp1(BranchAlias);
                    LoadGrp2(BranchAlias);
                    LoadGrp3(BranchAlias);
                    LoadGrp4(BranchAlias);
                    LoadGrp5(BranchAlias);
                    LoadCategoryList(BranchAlias);
                    LoadUnits(BranchAlias);
                    LoadTaxLables();
                    LoadPriceCaptionHeader(BranchAlias); //FOR PRICE CAPTION HEADER JOHN ADDED ON 13-JAN-2021 
                                                         // Loading Tax Combobox

                    LoadTakeawayCharge(BranchAlias);
                    LoadPrinterValue();

                    // Assign s3 realted Parameter values 
                    //  clientname.Value=Session["CM_ID"].ToString();
                    lblclientname.Text = Session["CM_ID"].ToString();
                    lblstorename.Text = BranchAlias;
                    Session["BranchFullName"] = BranchFullName;

                    lblSelectedBranchCaption1.Text = BranchFullName;
                    lblSelctedBranchCaption2.Text = BranchFullName;
                    this.Page.ClientScript.RegisterStartupScript(this.GetType(), "Javascript", "javascript:GetActiveSession5();", true);




                    Session["BranchDB"] = BranchAlias;

                    //string dbValue = BranchAlias;
                    //var encodedValue = HttpUtility.JavaScriptStringEncode(dbValue);
                    //ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), "MyFun1", "Loadunitpricelable('"+ encodedValue+"');", true);



                    string safeValue = Server.HtmlEncode(Cmb_BranchName);
                    string script = $"localStorage.setItem('Initialbranch', '{safeValue}');";
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "SetLocalStorage", script, true);






                    #region UnitPrice Hide and Show 

                    string is_view_unitcost = "select inivalue from " + BranchAlias + ".weborderinginisetting where id =82;";
                    string Read_Value_unitcost = ObjMain.ExecuteScalar(is_view_unitcost);
                    string _branch = Session["BranchDB"] != null ? Session["BranchDB"].ToString() : "";
                    ScriptManager.RegisterStartupScript(
                                     this,
                                     this.GetType(),
                                     "Javascript",
                                     $"Loadunitpricelable('{_branch}');",
                                     true
                                 );

                    #endregion



                    btnUpdateInv.Visible = false;
                    btnDelete.Visible = false;
                    txtReadInventroyId.Enabled = false;
                    txtReadInventroyId.CssClass = "form-control";

                    //John added on 31-Oct-2020 PriceCaption
                    //lblPrice1.InnerText = "Price 1 ( " + ObjSel.GetPriceCaption(BranchAlias, 1) + " )";
                    //txtCaptionPrice1.Text = ObjSel.GetPriceCaption(BranchAlias, 1);
                    //lblPrice2.InnerText = "Price 2 ( " + ObjSel.GetPriceCaption(BranchAlias, 2) + " )";
                    //txtCaptionPrice2.Text = ObjSel.GetPriceCaption(BranchAlias, 2);
                    //lblPrice3.InnerText = "Price 3 ( " + ObjSel.GetPriceCaption(BranchAlias, 3) + " )";
                    //txtCaptionPrice3.Text = ObjSel.GetPriceCaption(BranchAlias, 3);
                    //lblPrice4.InnerText = "Price 4 ( " + ObjSel.GetPriceCaption(BranchAlias, 4) + " )";
                    //txtCaptionPrice4.Text = ObjSel.GetPriceCaption(BranchAlias, 4);
                    lblPrice1.InnerText = "Price 1 ( " + ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "1") + " )";
                    txtCaptionPrice1.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "1");
                    lblPrice2.InnerText = "Price 2 ( " + ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "2") + " )";
                    txtCaptionPrice2.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "2");
                    lblPrice3.InnerText = "Price 3 ( " + ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "3") + " )";
                    txtCaptionPrice3.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "3");
                    lblPrice4.InnerText = "Price 4 ( " + ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "4") + " )";
                    txtCaptionPrice4.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "4");

                    //ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderID(BranchAlias), "1");

                    lblclientname.Text = Session["CM_ID"].ToString();
                    lblstorename.Text = BranchAlias;


                    UPDATEBRANCH(BranchAlias);

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


            }
            else
            {

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

                }
                #endregion

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

                    btnSubmit.CssClass = "btn btn-primary";
                    //btnShow.CssClass = "btn btn-success active";
                    btnSubmit.Enabled = false;
                    btnDelete.Enabled = false;
                    //btnShow.Enabled = false;
                }
                else
                {

                }



                // LoadInventoryview();

                string chk_Condition = ObjMain.ExecuteScalar("select IsWebOrderApp from portaldb.companydetails where  cd_branchAlias='" + BranchAlias + "';");
                if (chk_Condition.Equals("Y"))
                {


                    string _inventoryrows = string.Empty;
                    string _priceflagrows = string.Empty;
                    string Inven_sCmd = "Select count(*) as InventoryRows from {0}.Inventory; ";
                    string Invent_command = string.Format(Inven_sCmd, BranchAlias);
                    _inventoryrows = ObjMain.ExecuteScalar(Invent_command);



                    string priceflag_sCmd = "Select count(*) as PriceflagRows from {0}.priceflag; ";
                    string priceflag_command = string.Format(priceflag_sCmd, BranchAlias);
                    _priceflagrows = ObjMain.ExecuteScalar(priceflag_command);

                    if (_inventoryrows != _priceflagrows)
                    {
                        INS_PriceFlage(BranchAlias);
                        INS_WebStock(BranchAlias);
                    }
                }

                txtEffectiveDt.Text = Curr_DateOnly;
                LoadGrp1(BranchAlias);
                LoadGrp2(BranchAlias);
                LoadGrp3(BranchAlias);
                LoadGrp4(BranchAlias);
                LoadGrp5(BranchAlias);
                LoadCategoryList(BranchAlias);
                LoadUnits(BranchAlias);
                LoadPriceCaptionHeader(BranchAlias); //FOR PRICE CAPTION HEADER JOHN ADDED ON 13-JAN-2021 
                LoadTaxLables();
                LoadPrinterValue();
                LoadTakeawayCharge(BranchAlias);
                // Assign s3 realted Parameter values 
                //  clientname.Value=Session["CM_ID"].ToString();
                lblclientname.Text = Session["CM_ID"].ToString();
                lblstorename.Text = BranchAlias;

                BranchFullName = cmbBranches.SelectedItem.Text;

                Session["BranchFullName"] = BranchFullName;
                lblSelectedBranchCaption1.Text = BranchFullName;
                lblSelctedBranchCaption2.Text = BranchFullName;
                this.Page.ClientScript.RegisterStartupScript(this.GetType(), "Javascript", "javascript:GetActiveSession5();", true);

                Session["BranchDB"] = BranchAlias;




                string safeValue = Server.HtmlEncode(Cmb_BranchName);
                string script = $"localStorage.setItem('Initialbranch', '{safeValue}');";
                ScriptManager.RegisterStartupScript(this, this.GetType(), "SetLocalStorage", script, true);



                #region UnitPrice Hide and Show 

                string is_view_unitcost = "select inivalue from " + BranchAlias + ".weborderinginisetting where id =82;";
                string Read_Value_unitcost = ObjMain.ExecuteScalar(is_view_unitcost);
                string _branch = Session["BranchDB"] != null ? Session["BranchDB"].ToString() : "";
                ScriptManager.RegisterStartupScript(
                                 this,
                                 this.GetType(),
                                 "Javascript",
                                 $"Loadunitpricelable('{_branch}');",
                                 true
                             );

                #endregion


                // By Default

                btnUpdateInv.Visible = false;
                btnDelete.Visible = false;
                txtReadInventroyId.Enabled = false;
                txtReadInventroyId.CssClass = "form-control";

                //John added on 31-Oct-2020 PriceCaption
                //lblPrice1.InnerText = "Price 1 ( " + ObjSel.GetPriceCaption(BranchAlias, 1) + " )";
                //txtCaptionPrice1.Text = ObjSel.GetPriceCaption(BranchAlias, 1);
                //lblPrice2.InnerText = "Price 2 ( " + ObjSel.GetPriceCaption(BranchAlias, 2) + " )";
                //txtCaptionPrice2.Text = ObjSel.GetPriceCaption(BranchAlias, 2);
                //lblPrice3.InnerText = "Price 3 ( " + ObjSel.GetPriceCaption(BranchAlias, 3) + " )";
                //txtCaptionPrice3.Text = ObjSel.GetPriceCaption(BranchAlias, 3);
                //lblPrice4.InnerText = "Price 4 ( " + ObjSel.GetPriceCaption(BranchAlias, 4) + " )";
                //txtCaptionPrice4.Text = ObjSel.GetPriceCaption(BranchAlias, 4);
                lblPrice1.InnerText = "Price 1 ( " + ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "1") + " )";
                txtCaptionPrice1.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "1");
                lblPrice2.InnerText = "Price 2 ( " + ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "2") + " )";
                txtCaptionPrice2.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "2");
                lblPrice3.InnerText = "Price 3 ( " + ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "3") + " )";
                txtCaptionPrice3.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "3");
                lblPrice4.InnerText = "Price 4 ( " + ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "4") + " )";
                txtCaptionPrice4.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "4");
                UPDATEBRANCH(BranchAlias);
                //ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderID(BranchAlias), "1");
            }



            string _branch2 = BranchAlias != null ? BranchAlias.ToString() : "";
            ScriptManager.RegisterStartupScript(
                             this,
                             this.GetType(),
                             "Javascript",
                             $"Loadunitpricelable('{_branch2}');",
                             true
                         );




        }


        public void CreateTimeschedule(string BranchAlias, string inventoryid)
        {
            // Step : 1
            // Get the list of Inventoryid's 
            string Inventoryid = string.Empty;
            string Barcode = string.Empty;

            string ReadInventoryids = "select Inventoryid,Barcode from {0}.inventory where  Inventoryid=@Inventoryid; ";
            String command = string.Format(ReadInventoryids, BranchAlias);

            MySqlParameter[] parameters =
                   {
                     new MySqlParameter("@Inventoryid",inventoryid),
                   };

            DtRead = ObjMain.NewGetData_DT(command, parameters);


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

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


                // Step : 2
                // Read the Timing Baseschedule - Day by day 

                string ReadBaseTiming = "select * from  {0}.Baseschedule;";
                string command1 = string.Format(ReadBaseTiming, BranchAlias);

                DtTimeRead = ObjCloudMain.GetData_DT(command1);

                for (int k = 0; k < DtTimeRead.Rows.Count; k++)
                {
                    DataRow drr = DtTimeRead.Rows[k];
                    string DayName = drr["Days"].ToString();
                    string T1_StTm = drr["T1_StTm"].ToString();
                    DateTime T1_A = Convert.ToDateTime(T1_StTm);

                    string T1_EndTm = drr["T1_EndTm"].ToString();
                    DateTime T1_B = Convert.ToDateTime(T1_EndTm);


                    string T2_StTm = drr["T2_StTm"].ToString();
                    string T2_EndTm = drr["T2_EndTm"].ToString();
                    string T3_StTm = drr["T3_StTm"].ToString();
                    string T3_EndTm = drr["T3_EndTm"].ToString();


                    // Check Whether the Record Exist Or Not ( Key - Day & Inventoryid )

                    string ChecktimescheduleQuery = "select Barcode from   {0}.timeschedule  where Days=@DayName and Inventoryid=@Inventoryid ; ";

                    string newquery2 = string.Format(ChecktimescheduleQuery, BranchAlias);
                    MySqlParameter[] param =
                    {
                     new MySqlParameter("@DayName",DayName),
                     new MySqlParameter("@Inventoryid",Inventoryid),
                    };

                    //string Checktimeschedule = ObjCloudMain.ExecuteScalar(ChecktimescheduleQuery);     Exiting  Code 
                    string Checktimeschedule = ObjMain.NewExecuteScalar(newquery2, param);


                    if (Checktimeschedule != "")
                    {


                        // Call Update : If Exist
                        string UPT_Timing = "Update {0}.timeschedule  set  T1_StTm=@T1_StTm ,T1_EndTm=@T1_EndTm   where Days=@DayName  and Inventoryid=@Inventoryid ; ";
                        string command2 = string.Format(UPT_Timing, BranchAlias);

                        MySqlParameter[] param1 =
                        {
                             new MySqlParameter("@T1_StTm",T1_StTm),
                             new MySqlParameter("@T1_EndTm",T1_EndTm),
                             new MySqlParameter("@DayName",DayName),
                             new MySqlParameter("@Inventoryid",Inventoryid),

                        };

                        Z = ObjMain.ExecuteQuery(command2, param1);
                        //N   Z = ObjMain.ExecuteNonQuery(UPT_Timing);        // Existing code 



                    }
                    else
                    {


                        // Call Insert : If not Exist
                        string Ins_Timing = "insert into {0}.timeschedule (Days,Days_Visibility,T1_StTm,T1_EndTm,T2_StTm,T2_EndTm,T3_StTm,T3_EndTm,Inventoryid,Barcode) "
                        + " values( @DayName ,@Days_Visibility, @T1_StTm ,@T1_EndTm ,@T2_StTm,@T2_EndTm ,@T3_StTm ,@T3_EndTm ,@Inventoryid ,@Barcode ); ";

                        string command3 = string.Format(Ins_Timing, BranchAlias);
                        MySqlParameter[] param2 =
                           {
                             new MySqlParameter("@DayName",DayName),
                             new MySqlParameter("@Days_Visibility","1"),
                             new MySqlParameter("@T1_StTm",T1_A),
                             new MySqlParameter("@T1_EndTm",T1_B),
                             new MySqlParameter("@T2_StTm",T2_StTm),
                             new MySqlParameter("@T2_EndTm",T2_EndTm),
                             new MySqlParameter("@T3_StTm",T3_StTm),
                             new MySqlParameter("@T3_EndTm",T3_EndTm),
                             new MySqlParameter("@Inventoryid",Inventoryid),
                             new MySqlParameter("@Barcode",Barcode),

                            };

                        Z = ObjMain.ExecuteQuery(command3, param2);


                    }

                }


            }


        }

        /// <summary>
        /// This Fuction uses to Creates the Tax Settings 
        /// </summary>
        public void MakeTaxSetting()
        {
            string[] Taxing = new string[8];


            //  1: Inventory Flag ; 0:Category Flag
            if (chkTaxRate6.Checked == true || chkTaxRate5.Checked == true || chkTax4.Checked == true || chkTax3.Checked == true || chkTax2.Checked == true || chkTax1.Checked == true)
            {
                Taxing[0] = "1";

            }
            else
            {
                Taxing[0] = "0";

            }

            Taxing[1] = "0";     // Always '0'

            if (chkTaxRate6.Checked == true)
            {
                Taxing[2] = "1";

            }
            else
            {
                Taxing[2] = "0";
            }

            if (chkTaxRate5.Checked == true)
            {
                Taxing[3] = "1";
            }
            else
            {
                Taxing[3] = "0";
            }
            if (chkTax4.Checked == true)
            {
                Taxing[4] = "1";
            }
            else
            {
                Taxing[4] = "0";
            }

            if (chkTax3.Checked == true)
            {
                Taxing[5] = "1";
            }
            else
            {
                Taxing[5] = "0";
            }
            if (chkTax2.Checked == true)
            {
                Taxing[6] = "1";
            }
            else
            {
                Taxing[6] = "0";
            }
            if (chkTax1.Checked == true)
            {
                Taxing[7] = "1";

            }
            else
            {
                Taxing[7] = "0";
            }


            StringBuilder Build_Tax = new StringBuilder();
            foreach (string val in Taxing)
            {
                Build_Tax.Append(val);
            }

            hidNewTax.Value = Convert.ToString(Build_Tax);
        }

        public void UPT_MakeTaxSetting()
        {
            string[] Taxing = new string[8];
            //  1: Inventory Flag ; 0:Category Flag

            if (chkTaxRate6.Checked == true || chkTaxRate5.Checked == true || chkTax4.Checked == true || chkTax3.Checked == true || chkTax2.Checked == true || chkTax1.Checked == true)
            {
                Taxing[0] = "1";

            }
            else
            {
                Taxing[0] = "0";

            }

            Taxing[1] = "0";     // Always '0' Value 


            if (chkTaxRate6.Checked == true)
            {
                Taxing[2] = "1";

            }
            else
            {
                Taxing[2] = "0";
            }

            if (chkTaxRate5.Checked == true)
            {
                Taxing[3] = "1";
            }
            else
            {
                Taxing[3] = "0";
            }
            if (chkTax4.Checked == true)
            {
                Taxing[4] = "1";
            }
            else
            {
                Taxing[4] = "0";
            }

            if (chkTax3.Checked == true)
            {
                Taxing[5] = "1";
            }
            else
            {
                Taxing[5] = "0";
            }
            if (chkTax2.Checked == true)
            {
                Taxing[6] = "1";
            }
            else
            {
                Taxing[6] = "0";
            }
            if (chkTax1.Checked == true)
            {
                Taxing[7] = "1";

            }
            else
            {
                Taxing[7] = "0";
            }

            // String Builder used to appending the string1 ,string2 in String Array
            StringBuilder Build_Tax = new StringBuilder();
            foreach (string val in Taxing)
            {
                Build_Tax.Append(val);
            }

            hidNewTax.Value = Convert.ToString(Build_Tax);
        }

        public string GenericTax(int taxid)
        {
            string TaxName = string.Empty;

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

            }
            #endregion

            string Query_Tax = "Select TaxName  from   {0}.tax  where Taxid=@Taxid ;";
            string command = string.Format(Query_Tax, BranchAlias);

            MySqlParameter[] parameters =
                   {
                     new MySqlParameter("@Taxid",taxid),
                   };

            TaxName = ObjMain.NewExecuteScalar(command, parameters);

            return TaxName;
        }

        /// <summary>
        ///  This Funcation to load the Lable from the TaxMaster 
        /// </summary>
        public void LoadTaxLables()
        {
            lblATax6.Text = GenericTax(6);
            lblATax5.Text = GenericTax(5);
            lblATax4.Text = GenericTax(4);
            lblATax3.Text = GenericTax(3);
            lblATax2.Text = GenericTax(2);
            lblATax1.Text = GenericTax(1);
        }

        protected void OnSelectedIndexChanged(object sender, EventArgs e)
        {
            
            //Accessing TemplateField Column controls.
            string Barcode = (grdInventoryView.SelectedRow.FindControl("lblBarCode") as Label).Text;

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

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

            Session["LastBarcode"] = txtBarcode.Text.ToString();


            TxtMBarcode.Text = txtBarcode.Text; //for Misc
           
            
            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

            }

            lblImageError.Text = "";
            DTInvInfo = ObjSel.GetInvInfo(BranchAlias, txtBarcode.Text.ToString().Trim());
            if (DTInvInfo.Rows.Count == 0)
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Item not found, please enter valid Barcode ')", true);
                ClearInvForm();
                return;
            }
            else
            {
                if (Session["Write_Acess"].ToString() == "N")
                {
                    if (cmbBranches.SelectedItem.Text == "HQ")
                    {

                    }
                    else
                    {
                        btnUpdateInv.Enabled = false;
                        btnDelete.Enabled = false;
                        //btnShow.Enabled = false;
                        btnUpdateInv.CssClass = "btn btn-primary";
                        //btnShow.CssClass = "btn btn-success active";
                    }
                }
                txtEffectiveDt.Text = Curr_DateOnly;
                ShowInventory();
                btnSubmit.Visible = false;
                btnUpdateInv.Visible = true;
                btnDelete.Visible = true;
                
            }

            ShowSlaveListUnderMaster(BranchAlias, TxtMBarcode.Text);
            aMisc.Attributes.Add("class", "nav-link");
            Misc.Attributes.Add("class", "tab-pane fade");
            aBasic.Attributes.Add("class", "nav-link active border-left-0");
            home.Attributes.Add("class", "tab-pane fade show active");

            //lblPrice1.InnerText = "Price 1 ( " + ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderID(BranchAlias), "1") + " )";
            //txtCaptionPrice1.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderID(BranchAlias), "1");
            //lblPrice2.InnerText = "Price 2 ( " + ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderID(BranchAlias), "2") + " )";
            //txtCaptionPrice2.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderID(BranchAlias), "2");
            //lblPrice3.InnerText = "Price 3 ( " + ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderID(BranchAlias), "3") + " )";
            //txtCaptionPrice3.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderID(BranchAlias), "3");
            //lblPrice4.InnerText = "Price 4 ( " + ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderID(BranchAlias), "4") + " )";
            //txtCaptionPrice4.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderID(BranchAlias), "4");

            lblPrice1.InnerText = "Price 1 ( " + ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "1") + " )";
            txtCaptionPrice1.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "1");
            lblPrice2.InnerText = "Price 2 ( " + ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "2") + " )";
            txtCaptionPrice2.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "2");
            lblPrice3.InnerText = "Price 3 ( " + ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "3") + " )";
            txtCaptionPrice3.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "3");
            lblPrice4.InnerText = "Price 4 ( " + ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "4") + " )";
            txtCaptionPrice4.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "4");


            
            //ScriptManager.RegisterStartupScript(Page, this.GetType(), "ScrollPage", "window.scroll(0,20);", true);



        }

        //protected void grdInventoryView_RowCommand(object sender, GridViewCommandEventArgs e)
        //{
        //    if (e.CommandName == "Select")
        //    {


        //        //Determine the RowIndex of the Row whose Button was clicked.
        //        int rowIndex = Convert.ToInt32(e.CommandArgument);
        //        //Reference the GridView Row.
        //        GridViewRow row = grdInventoryView.Rows[rowIndex];
        //        //Fetch value of Name.
        //        string Barcode = (row.FindControl("lblBarCode") as Label).Text.ToString().Trim();
        //        //Page.ClientScript.RegisterStartupScript(this.GetType(), "hash", "location.hash = '#Inventoryx';", true);




        //    }
        //}

        public void LoadDetailsOnSession()
        {

            btnUpdateInv.Attributes.Add("onclick", "return false;");
            btnSubmit.Attributes.Add("onclick", "return false;");
            btnDelete.Attributes.Add("onclick", "return false;");
            //Accessing TemplateField Column controls.
            string Barcode = Session["LastValue"].ToString();

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

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



            TxtMBarcode.Text = txtBarcode.Text; //for Misc
            
          

            if (cmbBranches.Visible == false)
            {
                BranchAlias = Session["Branch_HQ"].ToString();
            }
            else
            {
                #region  Validation Between HQ Branch and Normal Branch 

                string QueryCal = "select ActiveValue from portaldb.usermaster  where Userid=" + Session["UserId"].ToString() + " ";
                ActiveCallvalue = ObjMain.ExecuteScalar(QueryCal);


                if (BranchFullName == "HQ")
                {
                    BranchAlias = Session["Branch_HQ"].ToString();
                }
                else
                {
                    BranchAlias = ActiveCallvalue;

                    Curr_BranchFullName = ObjUserBL.GetBranchCurr_BranchVal(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), 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;


                }
                #endregion

            }

            lblImageError.Text = "";
            DTInvInfo = ObjSel.GetInvInfo(BranchAlias, txtBarcode.Text.ToString().Trim());
            if (DTInvInfo.Rows.Count == 0)
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Item not found, please enter valid Barcode ')", true);
                ClearInvForm();
                return;
            }
            else
            {
                if (Session["Write_Acess"].ToString() == "N")
                {
                    if (cmbBranches.SelectedItem.Text == "HQ")
                    {

                    }
                    else
                    {
                        btnUpdateInv.Enabled = false;
                        //btnShow.Enabled = false;
                        btnUpdateInv.CssClass = "btn btn-primary";
                        //btnShow.CssClass = "btn btn-success active";
                    }
                }
                txtEffectiveDt.Text = Curr_DateOnly;
                ShowInventoryNew();
                btnSubmit.Visible = false;
                btnUpdateInv.Visible = true;
            }

            ShowSlaveListUnderMaster(BranchAlias, TxtMBarcode.Text);
            aMisc.Attributes.Add("class", "nav-link");
            Misc.Attributes.Add("class", "tab-pane fade");
            aBasic.Attributes.Add("class", "nav-link active border-left-0");
            home.Attributes.Add("class", "tab-pane fade show active");

            //lblPrice1.InnerText = "Price 1 ( " + ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderID(BranchAlias), "1") + " )";
            //txtCaptionPrice1.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderID(BranchAlias), "1");
            //lblPrice2.InnerText = "Price 2 ( " + ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderID(BranchAlias), "2") + " )";
            //txtCaptionPrice2.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderID(BranchAlias), "2");
            //lblPrice3.InnerText = "Price 3 ( " + ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderID(BranchAlias), "3") + " )";
            //txtCaptionPrice3.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderID(BranchAlias), "3");
            //lblPrice4.InnerText = "Price 4 ( " + ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderID(BranchAlias), "4") + " )";
            //txtCaptionPrice4.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderID(BranchAlias), "4");

            lblPrice1.InnerText = "Price 1 ( " + ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "1") + " )";
            txtCaptionPrice1.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "1");
            lblPrice2.InnerText = "Price 2 ( " + ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "2") + " )";
            txtCaptionPrice2.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "2");
            lblPrice3.InnerText = "Price 3 ( " + ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "3") + " )";
            txtCaptionPrice3.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "3");
            lblPrice4.InnerText = "Price 4 ( " + ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "4") + " )";
            txtCaptionPrice4.Text = ObjSel.GetPriceCaptionName(BranchAlias, ObjSel.GetPriceCaptionHeaderIDByName(BranchAlias, cmbPriceTypeCaption.Text), "4");



            //ScriptManager.RegisterStartupScript(Page, this.GetType(), "ScrollPage", "window.scroll(0,20);", true);





        }

        public void LoadPrinterValue()
        {
            string Printer_Query = "select id,PrinterNo,PrinterName,Visible  from  {0}.PrinterLable;";
            string command_Printer = string.Format(Printer_Query, BranchAlias);
            DTPrinterList = ObjCloudMain.GetData_DT(command_Printer);

            if (DTPrinterList.Rows.Count > 0)
            {
                // Load 19th 
                RPrintno19 = DTPrinterList.Rows[0]["Visible"].ToString();
                Printno19 = DTPrinterList.Rows[0]["PrinterNo"].ToString();
                Printno19 = DTPrinterList.Rows[0]["PrinterNo"].ToString();
                PrinterName19 = DTPrinterList.Rows[0]["PrinterName"].ToString();

                id19.Value = DTPrinterList.Rows[0]["id"].ToString();
                txtPrinterNo19.Text = Printno19;
                txtPrinterName19.Text = PrinterName19;
                lblLPrinter19.Text = PrinterName19;  // Assign to  Lable

                if (RPrintno19.Equals("0"))
                {
                    chkVP19.Checked = false;
                    chk2RP19.Visible = false;
                    lblLPrinter19.Visible = false;
                }
                else
                {
                    chkVP19.Checked = true;
                    chk2RP19.Visible = true;
                    lblLPrinter19.Visible = true;
                }


                // Load 18th
                RPrintno18 = DTPrinterList.Rows[1]["Visible"].ToString();
                id18.Value = DTPrinterList.Rows[1]["id"].ToString();
                Printno18 = DTPrinterList.Rows[1]["PrinterNo"].ToString();
                PrinterName18 = DTPrinterList.Rows[1]["PrinterName"].ToString();
                txtPrinterNo18.Text = Printno18;
                txtPrinterName18.Text = PrinterName18;
                lblLPrinter18.Text = PrinterName18;  // Assign to  Lable
                if (RPrintno18.Equals("0"))
                {
                    chkVP18.Checked = false;
                    chk2RP18.Visible = false;
                    lblLPrinter18.Visible = false;
                }
                else
                {
                    chkVP18.Checked = true;
                    chk2RP18.Visible = true;
                    lblLPrinter18.Visible = true;
                }



                // Load 17th 
                RPrintno17 = DTPrinterList.Rows[2]["Visible"].ToString();
                id17.Value = DTPrinterList.Rows[2]["id"].ToString();
                Printno17 = DTPrinterList.Rows[2]["PrinterNo"].ToString();
                PrinterName17 = DTPrinterList.Rows[2]["PrinterName"].ToString();
                txtPrinterNo17.Text = Printno17;
                txtPrinterName17.Text = PrinterName17;
                lblLPrinter17.Text = PrinterName17;  // Assign to  Lable
                if (RPrintno17.Equals("0"))
                {
                    chkVP17.Checked = false;
                    chk2RP17.Visible = false;
                    lblLPrinter17.Visible = false;
                }
                else
                {
                    chkVP17.Checked = true;
                    chk2RP17.Visible = true;
                    lblLPrinter17.Visible = true;
                }

                // Load 16th 
                RPrintno16 = DTPrinterList.Rows[3]["Visible"].ToString();
                id16.Value = DTPrinterList.Rows[3]["id"].ToString();
                Printno16 = DTPrinterList.Rows[3]["PrinterNo"].ToString();
                PrinterName16 = DTPrinterList.Rows[3]["PrinterName"].ToString();

                txtPrinterNo16.Text = Printno16;
                txtPrinterName16.Text = PrinterName16;
                lblLPrinter16.Text = PrinterName16;  // Assign to  Lable
                if (RPrintno16.Equals("0"))
                {
                    chkVP16.Checked = false;
                    chk2RP16.Visible = false;
                    lblLPrinter16.Visible = false;
                }
                else
                {
                    chkVP16.Checked = true;
                    chk2RP16.Visible = true;
                    lblLPrinter16.Visible = true;
                }

                // Load 15th 
                RPrintno15 = DTPrinterList.Rows[4]["Visible"].ToString();
                id15.Value = DTPrinterList.Rows[4]["id"].ToString();
                Printno15 = DTPrinterList.Rows[4]["PrinterNo"].ToString();
                PrinterName15 = DTPrinterList.Rows[4]["PrinterName"].ToString();
                txtPrinterNo15.Text = Printno15;
                txtPrinterName15.Text = PrinterName15;
                lblLPrinter15.Text = PrinterName15;  // Assign to  Lable
                if (RPrintno15.Equals("0"))
                {
                    chkVP15.Checked = false;
                    chk2RP15.Visible = false;
                    lblLPrinter15.Visible = false;
                }
                else
                {
                    chkVP15.Checked = true;
                    chk2RP15.Visible = true;
                    lblLPrinter15.Visible = true;
                }

                // Load 14th

                RPrintno14 = DTPrinterList.Rows[5]["Visible"].ToString();
                id14.Value = DTPrinterList.Rows[5]["id"].ToString();
                Printno14 = DTPrinterList.Rows[5]["PrinterNo"].ToString();
                PrinterName14 = DTPrinterList.Rows[5]["PrinterName"].ToString();
                txtPrinterNo14.Text = Printno14;
                txtPrinterName14.Text = PrinterName14;
                lblLPrinter14.Text = PrinterName14;  // Assign to  Lable
                if (RPrintno14.Equals("0"))
                {
                    chkVP14.Checked = false;
                    chk2RP14.Visible = false;
                    lblLPrinter14.Visible = false;
                }
                else
                {
                    chkVP14.Checked = true;
                    chk2RP14.Visible = true;
                    lblLPrinter14.Visible = true;
                }

                // Load 13th
                RPrintno13 = DTPrinterList.Rows[6]["Visible"].ToString();
                id13.Value = DTPrinterList.Rows[6]["id"].ToString();
                Printno13 = DTPrinterList.Rows[6]["PrinterNo"].ToString();
                PrinterName13 = DTPrinterList.Rows[6]["PrinterName"].ToString();
                txtPrinterNo13.Text = Printno13;
                txtPrinterName13.Text = PrinterName13;
                lblLPrinter13.Text = PrinterName13;  // Assign to  Lable

                if (RPrintno13.Equals("0"))
                {
                    chkVP13.Checked = false;
                    chk2RP13.Visible = false;
                    lblLPrinter13.Visible = false;
                }
                else
                {
                    chkVP13.Checked = true;
                    chk2RP13.Visible = true;
                    lblLPrinter13.Visible = true;
                }


                // Load 12th
                RPrintno12 = DTPrinterList.Rows[7]["Visible"].ToString();
                id12.Value = DTPrinterList.Rows[7]["id"].ToString();
                Printno12 = DTPrinterList.Rows[7]["PrinterNo"].ToString();
                PrinterName12 = DTPrinterList.Rows[7]["PrinterName"].ToString();
                txtPrinterNo12.Text = Printno12;
                txtPrinterName12.Text = PrinterName12;
                lblLPrinter12.Text = PrinterName12;  // Assign to  Lable
                if (RPrintno12.Equals("0"))
                {
                    chkVP12.Checked = false;
                    chk2RP12.Visible = false;
                    lblLPrinter12.Visible = false;
                }
                else
                {
                    chkVP12.Checked = true;
                    chk2RP12.Visible = true;
                    lblLPrinter12.Visible = true;
                }

                // Load 11th
                RPrintno11 = DTPrinterList.Rows[8]["Visible"].ToString();
                id11.Value = DTPrinterList.Rows[8]["id"].ToString();
                Printno11 = DTPrinterList.Rows[8]["PrinterNo"].ToString();
                PrinterName11 = DTPrinterList.Rows[8]["PrinterName"].ToString();
                txtPrinterNo11.Text = Printno11;
                txtPrinterName11.Text = PrinterName11;
                lblLPrinter11.Text = PrinterName11;  // Assign to  Lable
                if (RPrintno11.Equals("0"))
                {
                    chkVP11.Checked = false;
                    chk2RP11.Visible = false;
                    lblLPrinter11.Visible = false;
                }
                else
                {
                    chkVP11.Checked = true;
                    chk2RP11.Visible = true;
                    lblLPrinter11.Visible = true;
                }


                // Load 10th 
                RPrintno10 = DTPrinterList.Rows[9]["Visible"].ToString();
                id10.Value = DTPrinterList.Rows[9]["id"].ToString();
                Printno10 = DTPrinterList.Rows[9]["PrinterNo"].ToString();
                PrinterName10 = DTPrinterList.Rows[9]["PrinterName"].ToString();
                txtPrinterNo10.Text = Printno10;
                txtPrinterName10.Text = PrinterName10;
                lblLPrinter10.Text = PrinterName10;  // Assign to  Lable
                if (RPrintno10.Equals("0"))
                {
                    chkVP10.Checked = false;
                    chk2RP10.Visible = false;
                    lblLPrinter10.Visible = false;
                }
                else
                {
                    chkVP10.Checked = true;
                    chk2RP10.Visible = true;
                    lblLPrinter10.Visible = true;
                }
                // Load 9th 
                RPrintno9 = DTPrinterList.Rows[10]["Visible"].ToString();
                id9.Value = DTPrinterList.Rows[10]["id"].ToString();
                Printno9 = DTPrinterList.Rows[10]["PrinterNo"].ToString();
                PrinterName9 = DTPrinterList.Rows[10]["PrinterName"].ToString();
                txtPrinterNo9.Text = Printno9;
                txtPrinterName9.Text = PrinterName9;
                lblLPrinter9.Text = PrinterName9;  // Assign to  Lable
                if (RPrintno9.Equals("0"))
                {
                    chkVP9.Checked = false;
                    chk2RP9.Visible = false;
                    lblLPrinter9.Visible = false;
                }
                else
                {
                    chkVP9.Checked = true;
                    chk2RP9.Visible = true;
                    lblLPrinter9.Visible = true;
                }

                // Load 8th 
                RPrintno8 = DTPrinterList.Rows[11]["Visible"].ToString();
                id8.Value = DTPrinterList.Rows[11]["id"].ToString();
                Printno8 = DTPrinterList.Rows[11]["PrinterNo"].ToString();
                PrinterName8 = DTPrinterList.Rows[11]["PrinterName"].ToString();
                txtPrinterNo8.Text = Printno8;
                txtPrinterName8.Text = PrinterName8;
                lblLPrinter8.Text = PrinterName8;  // Assign to  Lable
                if (RPrintno8.Equals("0"))
                {
                    chkVP8.Checked = false;
                    chk2RP8.Visible = false;
                    lblLPrinter8.Visible = false;
                }
                else
                {
                    chkVP8.Checked = true;
                    chk2RP8.Visible = true;
                    lblLPrinter8.Visible = true;
                }


                // Load 7th 
                RPrintno7 = DTPrinterList.Rows[12]["Visible"].ToString();
                id7.Value = DTPrinterList.Rows[12]["id"].ToString();
                Printno7 = DTPrinterList.Rows[12]["PrinterNo"].ToString();
                PrinterName7 = DTPrinterList.Rows[12]["PrinterName"].ToString();
                txtPrinterNo7.Text = Printno7;
                txtPrinterName7.Text = PrinterName7;
                lblLPrinter7.Text = PrinterName7;  // Assign to  Lable
                if (RPrintno7.Equals("0"))
                {
                    chkVP7.Checked = false;
                    chk2RP7.Visible = false;
                    lblLPrinter7.Visible = false;
                }
                else
                {
                    chkVP7.Checked = true;
                    chk2RP7.Visible = true;
                    lblLPrinter7.Visible = true;
                }


                // Load 6th 
                RPrintno6 = DTPrinterList.Rows[13]["Visible"].ToString();
                id6.Value = DTPrinterList.Rows[13]["id"].ToString();
                Printno6 = DTPrinterList.Rows[13]["PrinterNo"].ToString();
                PrinterName6 = DTPrinterList.Rows[13]["PrinterName"].ToString();
                txtPrinterNo6.Text = Printno6;
                txtPrinterName6.Text = PrinterName6;
                lblLPrinter6.Text = PrinterName6;  // Assign to  Lable
                if (RPrintno6.Equals("0"))
                {
                    chkVP6.Checked = false;
                    chk2RP6.Visible = false;
                    lblLPrinter6.Visible = false;
                }
                else
                {
                    chkVP6.Checked = true;
                    chk2RP6.Visible = true;
                    lblLPrinter6.Visible = true;
                }


                // Load 5th 
                RPrintno5 = DTPrinterList.Rows[14]["Visible"].ToString();
                id5.Value = DTPrinterList.Rows[14]["id"].ToString();
                Printno5 = DTPrinterList.Rows[14]["PrinterNo"].ToString();
                PrinterName5 = DTPrinterList.Rows[14]["PrinterName"].ToString();
                txtPrinterNo5.Text = Printno5;
                txtPrinterName5.Text = PrinterName5;
                lblLPrinter5.Text = PrinterName5;  // Assign to  Lable
                if (RPrintno5.Equals("0"))
                {
                    chkVP5.Checked = false;
                    chk2RP5.Visible = false;
                    lblLPrinter5.Visible = false;
                }
                else
                {
                    chkVP5.Checked = true;
                    chk2RP5.Visible = true;
                    lblLPrinter5.Visible = true;
                }

                // Load 4th 
                RPrintno4 = DTPrinterList.Rows[15]["Visible"].ToString();
                id4.Value = DTPrinterList.Rows[15]["id"].ToString();
                Printno4 = DTPrinterList.Rows[15]["PrinterNo"].ToString();
                PrinterName4 = DTPrinterList.Rows[15]["PrinterName"].ToString();
                txtPrinterNo4.Text = Printno4;
                txtPrinterName4.Text = PrinterName4;
                lblLPrinter4.Text = PrinterName4;  // Assign to  Lable
                if (RPrintno4.Equals("0"))
                {
                    chkVP4.Checked = false;
                    chk2RP4.Visible = false;
                    lblLPrinter4.Visible = false;
                }
                else
                {
                    chkVP4.Checked = true;
                    chk2RP4.Visible = true;
                    lblLPrinter4.Visible = true;
                }


                // Load 3rd 
                RPrintno3 = DTPrinterList.Rows[16]["Visible"].ToString();
                id3.Value = DTPrinterList.Rows[16]["id"].ToString();
                Printno3 = DTPrinterList.Rows[16]["PrinterNo"].ToString();
                PrinterName3 = DTPrinterList.Rows[16]["PrinterName"].ToString();
                txtPrinterNo3.Text = Printno3;
                txtPrinterName3.Text = PrinterName3;
                lblLPrinter3.Text = PrinterName3;  // Assign to  Lable
                if (RPrintno3.Equals("0"))
                {
                    chkVP3.Checked = false;
                    chk2RP3.Visible = false;
                    lblLPrinter3.Visible = false;
                }

                else
                {
                    chkVP3.Checked = true;
                    chk2RP3.Visible = true;
                    lblLPrinter3.Visible = true;
                }
                // Load 2nd 
                RPrintno2 = DTPrinterList.Rows[17]["Visible"].ToString();
                id2.Value = DTPrinterList.Rows[17]["id"].ToString();
                Printno2 = DTPrinterList.Rows[17]["PrinterNo"].ToString();
                PrinterName2 = DTPrinterList.Rows[17]["PrinterName"].ToString();
                txtPrinterNo2.Text = Printno2;
                txtPrinterName2.Text = PrinterName2;
                lblLPrinter2.Text = PrinterName2;  // Assign to  Lable
                if (RPrintno2.Equals("0"))
                {
                    chkVP2.Checked = false;
                    chk2RP2.Visible = false;
                    lblLPrinter2.Visible = false;
                }
                else
                {
                    chkVP2.Checked = true;
                    chk2RP2.Visible = true;
                    lblLPrinter2.Visible = true;
                }

                // Load 1st
                RPrintno1 = DTPrinterList.Rows[18]["Visible"].ToString();
                id1.Value = DTPrinterList.Rows[18]["id"].ToString();
                Printno1 = DTPrinterList.Rows[18]["PrinterNo"].ToString();
                PrinterName1 = DTPrinterList.Rows[18]["PrinterName"].ToString();
                txtPrinterNo1.Text = Printno1;
                txtPrinterName1.Text = PrinterName1;
                lblLPrinter1.Text = PrinterName1;  // Assign to  Lable
                if (RPrintno1.Equals("0"))
                {
                    chkVP1.Checked = false;
                    chk2RP1.Visible = false;
                    lblLPrinter1.Visible = false;
                }
                else
                {
                    chkVP1.Checked = true;
                    chk2RP1.Visible = true;
                    lblLPrinter1.Visible = true;
                }

            }

        }

        protected void btnPrinterLable_Click(object sender, EventArgs e)
        {
            string R19, R18, R17, R16, R15, R14, R13, R12, R11, R10, R9, R8, R7, R6, R5, R4, R3, R2, R1;
            if (chkVP19.Checked == true)
            {
                R19 = "1";
            }
            else
            {
                R19 = "0";

            }
            if (chkVP18.Checked == true)
            {
                R18 = "1";
            }
            else
            {
                R18 = "0";

            }
            if (chkVP17.Checked == true)
            {
                R17 = "1";
            }
            else
            {
                R17 = "0";

            }

            if (chkVP16.Checked == true)
            {
                R16 = "1";
            }
            else
            {
                R16 = "0";

            }
            if (chkVP15.Checked == true)
            {
                R15 = "1";
            }
            else
            {
                R15 = "0";

            }

            if (chkVP14.Checked == true)
            {
                R14 = "1";
            }
            else
            {
                R14 = "0";

            }

            if (chkVP13.Checked == true)
            {
                R13 = "1";
            }
            else
            {
                R13 = "0";

            }

            if (chkVP12.Checked == true)
            {
                R12 = "1";
            }
            else
            {
                R12 = "0";

            }

            if (chkVP11.Checked == true)
            {
                R11 = "1";
            }
            else
            {
                R11 = "0";

            }

            if (chkVP10.Checked == true)
            {
                R10 = "1";
            }
            else
            {
                R10 = "0";

            }

            if (chkVP9.Checked == true)
            {
                R9 = "1";
            }
            else
            {
                R9 = "0";

            }

            if (chkVP8.Checked == true)
            {
                R8 = "1";
            }
            else
            {
                R8 = "0";

            }


            if (chkVP7.Checked == true)
            {
                R7 = "1";
            }
            else
            {
                R7 = "0";

            }

            if (chkVP6.Checked == true)
            {
                R6 = "1";
            }
            else
            {
                R6 = "0";

            }


            if (chkVP5.Checked == true)
            {
                R5 = "1";
            }
            else
            {
                R5 = "0";

            }

            if (chkVP4.Checked == true)
            {
                R4 = "1";
            }
            else
            {
                R4 = "0";

            }

            if (chkVP3.Checked == true)
            {
                R3 = "1";
            }
            else
            {
                R3 = "0";

            }
            if (chkVP2.Checked == true)
            {
                R2 = "1";
            }
            else
            {
                R2 = "0";

            }

            if (chkVP1.Checked == true)
            {
                R1 = "1";
            }
            else
            {
                R1 = "0";

            }



            UpdatePrinterLable(id19.Value, R19, txtPrinterName19.Text);
            UpdatePrinterLable(id18.Value, R18, txtPrinterName18.Text);
            UpdatePrinterLable(id17.Value, R17, txtPrinterName17.Text);
            UpdatePrinterLable(id16.Value, R16, txtPrinterName16.Text);
            UpdatePrinterLable(id15.Value, R15, txtPrinterName15.Text);
            UpdatePrinterLable(id14.Value, R14, txtPrinterName14.Text);
            UpdatePrinterLable(id13.Value, R13, txtPrinterName13.Text);
            UpdatePrinterLable(id12.Value, R12, txtPrinterName12.Text);
            UpdatePrinterLable(id11.Value, R11, txtPrinterName11.Text);
            UpdatePrinterLable(id10.Value, R10, txtPrinterName10.Text);
            UpdatePrinterLable(id9.Value, R9, txtPrinterName9.Text);
            UpdatePrinterLable(id8.Value, R8, txtPrinterName8.Text);
            UpdatePrinterLable(id7.Value, R7, txtPrinterName7.Text);
            UpdatePrinterLable(id6.Value, R6, txtPrinterName6.Text);
            UpdatePrinterLable(id5.Value, R5, txtPrinterName5.Text);
            UpdatePrinterLable(id4.Value, R4, txtPrinterName4.Text);
            UpdatePrinterLable(id3.Value, R3, txtPrinterName3.Text);
            UpdatePrinterLable(id2.Value, R2, txtPrinterName2.Text);
            UpdatePrinterLable(id1.Value, R1, txtPrinterName1.Text);
            LoadPrinterValue();
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' PrinterLable  Updated Successfully '); ", true);
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ShowModalPrinterList();", true);


        }
        
        public void UpdatePrinterLable(string id, string Visible_Value, string PrinterName)
        {
            // SQL Injection Prevention : 06-10-21
            // Parameterized Appraoch 
            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();
            }



            string UPT_Query = "Update {0}.PrinterLable  set  PrinterName=@PrinterName,Visible=@Visible  where id=@id ;";
            string command_UPT_Query = string.Format(UPT_Query, BranchAlias);
            MySqlParameter[] parameters =
                  {
                     new MySqlParameter("@PrinterName",PrinterName),
                     new MySqlParameter("@Visible",Visible_Value),
                     new MySqlParameter("@id",id),

                    };
            int UP = 0;
            UP = ObjMain.ExecuteQuery(command_UPT_Query, parameters);

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

            txtSearchVal.CssClass = "form-control";
            Page.ClientScript.RegisterStartupScript(this.GetType(), "hash", "location.hash = '#Inventoryx';", true);

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

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

                }
                #endregion

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

            if (cmbSearch.SelectedIndex == 0)
            {
                //John added This All Condition

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

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




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

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

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

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

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


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

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

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

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


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

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

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

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

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

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

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

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

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


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

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


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

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

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

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


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

            }

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

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

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

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

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

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

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

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


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

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

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

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

            }


        }

        /// <summary>   
        ///  This functions Uses for Update Image in Inventory Table 
        ///  This is old Approach to save the image 
        ///  Currently not used  in the Page  
        /// </summary>

        /*
        public void SaveImage()
        {
            IISAppName = ObjSel.Get_IISAppName(Session["CM_ID"].ToString(), cmbBranches.SelectedValue);   // Getting IISAppName  
            try
            {
                if (cmbBranches.Visible == true)
                {
                    BranchFullName = Microsoft.Security.Application.Encoder.HtmlEncode(cmbBranches.SelectedItem.Text);            // This will Return Branch FullName 
                    Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);  // This will Return BranchName( Actual Database Name )

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

                if (IISAppName != "")
                {
                    //string path = @"C:/inetpub/wwwroot/OLAPPS/" + IISAppName.ToString().Trim() + "/WebImage/";           // OLOrder  is Application Name ( Need to Pass From UI In future ) 
                    //string path = @"C:/HOST/Virtual/OLAPPS/" + IISAppName.ToString().Trim() + "/WebImage/";   // John hide on 13-March-2021 Previous Path
                    string path = @"C:/inetpub/wwwroot/Images/";
                    string ChkPath = Path.Combine(path, Cmb_BranchName);
                    if (!Directory.Exists(ChkPath))
                    {
                        Directory.CreateDirectory(ChkPath);

                    }
                }
                else
                {
                    string path = @"C:/inetpub/wwwroot/OLOrder/WebImage/";           // OLOrder  is Application Name ( Need to Pass From UI In future ) 
                    string ChkPath = Path.Combine(path, Cmb_BranchName);
                    if (!Directory.Exists(ChkPath))
                    {
                        Directory.CreateDirectory(ChkPath);                         // If No Directory it will Create  

                    }
                }



                ObjPL.BarCode = ObjMain.ExecuteScalar("select barcode from  " + Cmb_BranchName + ".inventory where Inventoryid=" + txtReadInventroyId.Text.ToString().Trim() + "");
                if (Fileploadid.HasFile)
                {
                    if (IISAppName != "")
                    {
                        //SPath = @"C:/HOST/Virtual/OLAPPS/" + IISAppName.ToString().Trim() + "/WebImage/" + Cmb_BranchName; // John hide on 13-March-2021 Previous Path
                        SPath = @"C:/inetpub/wwwroot/Images/" + Cmb_BranchName; //John added on 13-Apr-2021
                    }
                    else
                    {
                        SPath = @"C:/inetpub/wwwroot/OLOrder/WebImage/" + Cmb_BranchName;
                    }

                    // Checking Image Path : if exist it will Delete already saved Image : Insert new one  // John hide on 13-March-2021 Previous Path
                    //ChkImagePath = ObjMain.ExecuteScalar("select SUBSTR(Imagepath,2) from " + Cmb_BranchName + ".inventory where inventoryid=" + txtReadInventroyId.Text.ToString().Trim() + "");
                    //if (ChkImagePath != "")
                    //{
                    //    if (IISAppName != "")
                    //    {
                    //        string PicPath = @"C:/HOST/Virtual/OLAPPS/" + IISAppName.ToString().Trim() + " " + ChkImagePath + "  ";
                    //        if (File.Exists(PicPath))
                    //        {
                    //            File.Delete(PicPath);
                    //        }
                    //    }
                    //    else
                    //    {
                    //        string PicPath = @"C:/inetpub/wwwroot/OLOrder " + ChkImagePath + "  ";
                    //        if (File.Exists(PicPath))
                    //        {
                    //            File.Delete(PicPath);
                    //        }
                    //    }
                    //}

                    //Path.Combine(str_uploadpath, fileName);  Test
                    //John Hide on 13-Apr-2021 Hide Previous Code
                    //string str = Fileploadid.FileName;
                    //string extension = System.IO.Path.GetExtension(Fileploadid.PostedFile.FileName);
                    //string FullExt = "~/" + SPath + "/" + ObjPL.BarCode.ToString().Trim() + extension.ToString();
                    //string FinalFullExt = Path.Combine(SPath, ObjPL.BarCode.ToString().Trim() + extension.ToString());
                    ////Fileploadid.PostedFile.SaveAs(Server.MapPath("~/" + SPath + "/" + ObjPL.BarCode.ToString().Trim() + extension));   // Old  Code
                    //Fileploadid.PostedFile.SaveAs(FinalFullExt);
                    //string SPathnew = "WebImage/" + Cmb_BranchName;
                    //ObjPL.ImgPath = "~/" + SPathnew + "/" + ObjPL.BarCode.ToString().Trim() + extension;
                    //=============================================================


                    //string From = @"E:\desktop\NEED THIS FORMAT.txt";
                    //string To = "https://suntoyocloud.com/Images/da1/NEED THIS FORMAT.txt";

                    ////using (WebClient client = new WebClient())
                    ////{
                    ////    client.Credentials = new NetworkCredential("Administrator", "?qNehGaw%;3vAio8B3;m%y&=CLlwB-zX");
                    ////    client.UploadFile(To, WebRequestMethods.Ftp.UploadFile, From);
                    ////}  

                    //WebClient client = new WebClient();
                    //client.Credentials = new NetworkCredential("Administrator", "?qNehGaw%;3vAio8B3;m%y&=CLlwB-zX");
                    //client.UploadFile(To, "PUT", From);


                    //SPath = "https://suntoyocloud.com/Images/da1/";
                    //SPath = "hthttp://192.168.15.168/Images/";
                    string extension = System.IO.Path.GetExtension(Fileploadid.PostedFile.FileName); //John added on 13-Apr-2021
                    string FinalFullExt = Path.Combine(SPath, ObjPL.BarCode.ToString().Trim() + extension.ToString()); //John added on 13-Apr-2021
                    Fileploadid.PostedFile.SaveAs(FinalFullExt); //John added on 13-Apr-2021
                    //string imageURL = "hthttp://192.168.15.168/Images/" + Cmb_BranchName + "/" + ObjPL.BarCode.ToString().Trim() + extension.ToString(); //John added on 13-Apr-2021 LOCAL IIS
                    string imageURL = "hthttps://suntoyocloud.com/Images/" + Cmb_BranchName + "/" + ObjPL.BarCode.ToString().Trim() + extension.ToString(); //if HOST
                    //ObjPL.ImgPath = SPath + "/" + ObjPL.BarCode.ToString().Trim() + extension.ToString(); //John added on 13-Apr-2021
                    string Qry2 = " UPDATE " + Cmb_BranchName + ".inventory SET   ImagePath='" + imageURL + "' WHERE  Inventoryid=" + txtReadInventroyId.Text.ToString().Trim() + " ";
                    L = ObjMain.ExecuteNonQuery(Qry2);
                }
                else
                {
                  //  ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('Provide the Image For the Product ! ')", true);
                }
            }
            catch (Exception Ex)
            {
                ObjError.Write(Ex);
            }


        }

       */
        private void UploadToIOrderla()
        {

        }

        private void GetSlaveInventory(string sDB)
        {
            // SQL Injection Prevention : 07-10-21 
            // Parameterized Approach 

            string sWhereCondition = string.Empty;
            if (cmbSSearch.Text != "All")
            {
                if (cmbSSearch.Text == "Barcode")
                {
                    sWhereCondition = " and Barcode like CONCAT('%',@SearchText,'%') ";
                }
                else if (cmbSSearch.Text == "Name")
                {
                    sWhereCondition = " and InventoryName like CONCAT('%',@SearchText,'%') ";
                }
                else if (cmbSSearch.Text == "Description")
                {
                    sWhereCondition = " and Description like CONCAT('%',@SearchText,'%') ";
                }
            }



            string sCmd = "Select InventoryID,Barcode,InventoryName,Description from {0}.Inventory where Barcode <> 'Round' and Class = 11 " + sWhereCondition + "";
            DataTable Dt = new DataTable();
            string command = string.Format(sCmd, sDB);

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

                    };

            Dt = ObjMain.NewGetData_DT(command, parameters);



            GrdMasterSlaveInventory.DataSource = Dt;
            GrdMasterSlaveInventory.DataBind();

            //aBasic.Attributes.Add("class", "nav-link");
            //home.Attributes.Add("class", "tab-pane fade");
            //aMisc.Attributes.Add("class", "nav-link active border-left-0");
            //Misc.Attributes.Add("class", "tab-pane fade show active");


        }

        private void ShowSlaveListUnderMaster(string sDB, string sMBarcode)
        {
            // SQL Injection Prevention : 07-10-21 
            // Parameterized Approach 
            string sCmd = "Select InventoryID,Barcode,InventoryName,Description from {0}.inventory A " +
                                " join {0}.inventorymulticode b on A.Barcode = B.Slavebarcode where A.Class = '11' and B.MasterBarcode ='{1}';";
            string command = string.Format(sCmd, sDB, sMBarcode);
            DataTable Dt = new DataTable();
            Dt = ObjMain.GetData_DT(command);
            GrdSlaveListUnderMaster.DataSource = Dt;
            GrdSlaveListUnderMaster.DataBind();
        }

        protected void btnSearchSlave_Click(object sender, EventArgs e)
        {
            string sCheckMasterBarcode = string.Empty;
            //DataTable = DTMResult
            DataTable DTMResult = new DataTable();
            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


            }

            if (txtBarcode.Text != "")
            {

                string sCmd = "Select Barcode from {0}.Inventory where barcode ='{1}' and class = 10";
                string command = string.Format(sCmd, Cmb_BranchName, txtBarcode.Text.ToString().Trim());
                DataTable Dt = new DataTable();
                Dt = ObjMain.GetData_DT(command);

                if (Dt.Rows.Count > 0)
                {
                    GetSlaveInventory(Cmb_BranchName);
                }
                else
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('Invalid Master Barcode')", true);
                    GrdMasterSlaveInventory.DataSource = null;
                    GrdMasterSlaveInventory.DataBind();

                }

                aBasic.Attributes.Add("class", "nav-link");
                home.Attributes.Add("class", "tab-pane fade");
                aMisc.Attributes.Add("class", "nav-link active border-left-0");
                Misc.Attributes.Add("class", "tab-pane fade show active");
            }
            else
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('Please Select Master Barcode')", true);
                GrdMasterSlaveInventory.DataSource = null;
                GrdMasterSlaveInventory.DataBind();
                aBasic.Attributes.Add("class", "nav-link");
                home.Attributes.Add("class", "tab-pane fade");
                aMisc.Attributes.Add("class", "nav-link active border-left-0");
                Misc.Attributes.Add("class", "tab-pane fade show active");
            }
            btnUpdateInv.Visible = false;
            btnDelete.Visible = false;
        }

        protected void btnAddSlave_Click(object sender, EventArgs e)
        {

            string confirmValue = Request.Form["confirm_value"];
            if (confirmValue == "Yes")
            {
                this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('You clicked YES!')", true);
            }
            else
            {
                this.Page.ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('You clicked NO!')", true);
            }
            #region    Validate Normal Branch & HQ  Branch 
            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

            }
            #endregion
            DataTable dt = new DataTable();
            dt.Columns.AddRange(new DataColumn[3] { new DataColumn("Id", typeof(int)),
                        new DataColumn("Barcode", typeof(string)),
                        new DataColumn("Name",typeof(string)) });
            foreach (GridViewRow row in GrdMasterSlaveInventory.Rows)
            {
                if ((row.FindControl("chkRow") as CheckBox).Checked)
                {
                    string sSlaveBarcode = (row.Cells[1].FindControl("lblBarcode") as Label).Text;
                    string a = row.Cells[1].Text;
                    InsertSlaveBarcode(Cmb_BranchName, TxtMBarcode.Text.Trim(), sSlaveBarcode);
                }
            }

            ShowSlaveListUnderMaster(Cmb_BranchName, TxtMBarcode.Text.Trim());

            btnSearchSlave_Click(btnSearchSlave, EventArgs.Empty);
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Info_msg", "alert('Slave barcode successfully added.')", true);
            ShowSlaveListUnderMaster(Cmb_BranchName, TxtMBarcode.Text.Trim());
        }

        private void InsertSlaveBarcode(string sDB, string sMBarcode, string sSBarcode)
        {
            // SQL Injection Prevention : 07-10-21 
            // Parameterized Approach 
            //string sResult; 
            //Check Slave Barcode if already Existing
            //Page.ClientScript.RegisterStartupScript(typeof(InventoryMaster), "ConfirmAlert", "<script>ConfirmAlert()</script>");
            string sCmdDel = "Delete from {0}.inventorymulticode where Slavebarcode ='{1}' ";
            string command = string.Format(sCmdDel, sDB, sSBarcode);

            DeleteExistingSlave = ObjCloudMain.ExecuteNonQuery(command);
            string sCmd = "Insert into {0}.inventorymulticode(`MasterBarcode`,`SlaveBarcode`)values(@MasterBarcode,@SlaveBarcode)";
            string commandA = string.Format(sCmd, sDB);

            MySqlParameter[] parameters =
                   {
                     new MySqlParameter("@MasterBarcode",sMBarcode),
                     new MySqlParameter("@SlaveBarcode",sSBarcode),
                    };



            InsertMultiBarcode = ObjMain.ExecuteQuery(commandA, parameters);
        }

        protected void GrdSlaveListUnderMaster_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            // Prevention xss 
            // Prevention SQL Injection 

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

            }
            #endregion



            string sBarcode = (GrdSlaveListUnderMaster.SelectedRow.FindControl("lblBarCode") as Label).Text;

            string sCmd = "Delete from {0}.Inventorymulticode where Slavebarcode = '{1}' ";
            string command = string.Format(sCmd, Cmb_BranchName, sBarcode);
            DeleteSlave = ObjCloudMain.ExecuteNonQuery(command);

            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Info_msg", "alert('Slave barcode already deleted.')", true);
            ShowSlaveListUnderMaster(Cmb_BranchName, TxtMBarcode.Text.Trim());

            aBasic.Attributes.Add("class", "nav-link");
            home.Attributes.Add("class", "tab-pane fade");
            aMisc.Attributes.Add("class", "nav-link active border-left-0");
            Misc.Attributes.Add("class", "tab-pane fade show active");
        }
        //nid added for Package Module on 06-Feb-2023
        protected void GrdPackagedItems_OnSelectedIndexChanged(object sender, EventArgs e)
        {
            // Prevention xss 
            // Prevention SQL Injection 

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

            }
            #endregion



            //string sBarcode = (GrdSlaveListUnderMaster.SelectedRow.FindControl("lblBarCode") as Label).Text;

            //string sCmd = "Delete from {0}.Inventorymulticode where Slavebarcode = {1} ";
            //string command = string.Format(sCmd, Cmb_BranchName, sBarcode);
            //DeleteSlave = ObjCloudMain.ExecuteNonQuery(command);

            //ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Info_msg", "alert('Slave barcode already deleted.')", true);
            //ShowSlaveListUnderMaster(Cmb_BranchName, TxtMBarcode.Text.Trim());

            //aBasic.Attributes.Add("class", "nav-link");
            //home.Attributes.Add("class", "tab-pane fade");
            //aMisc.Attributes.Add("class", "nav-link active border-left-0");
            //Misc.Attributes.Add("class", "tab-pane fade show active");
        }

        protected void btnPriceCaption_Click(object sender, EventArgs e)
        {
            // Prevention xss 
            // Prevention SQL Injection 

            #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

            for (int i = 1; i < 5; i++)
            {
                if (i == 1)
                {
                    UpdatePriceTypeCaption(Cmb_BranchName, i, txtCaptionPrice1.Text);
                }
                else if (i == 2)
                {
                    UpdatePriceTypeCaption(Cmb_BranchName, 2, txtCaptionPrice2.Text);
                }
                else if (i == 3)
                {
                    UpdatePriceTypeCaption(Cmb_BranchName, 3, txtCaptionPrice3.Text);
                }
                else if (i == 4)
                {
                    UpdatePriceTypeCaption(Cmb_BranchName, 4, txtCaptionPrice4.Text);
                }
            }


            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "success_msg", "alert('Price caption successfully updated');location.href='InventoryMaster.aspx' ", true);

        }

        private void UpdatePriceTypeCaption(string sDB, int iPriceType, string sPriceCaption)
        {
            // Prevention xss 
            // Prevention SQL Injection 

            string sCmd = "Update {0}.PriceCaption set PriceCaption =@PriceCaption where id =@id";

            string command = string.Format(sCmd, sDB);

            MySqlParameter[] parameters =
                   {
                     new MySqlParameter("@PriceCaption",sPriceCaption),
                     new MySqlParameter("@id",iPriceType),
                    };


            iUpdatePriceCaption = ObjMain.ExecuteQuery(command, parameters);

        }

        public void SaveImagedetailstoS3(string branchalias, string Inventoryid)
        {
            // Prevention SQL Injection : 07-10-21
            // Parameterized approach 
            // Prevention XSS


            // Get the Full S3Path 

            // var A = "https://suntoyo-aws-s3.s3.ap-southeast-1.amazonaws.com/49/da1/jpg/a01.jpg";


            if (hdnPath.Value != "")
            {

                var JsonResult = hdnPath.Value;


                Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(JsonResult);

                var V = myDeserializedClass.dbPath;
                hdnurl.Value = V;


                var Result = V.Split('/');

                string S3_http = Result[0];
                string S3_null = Result[1];
                string S3_S3link = Result[2];
                string S3_Companyname = Result[3];
                string S3_Brachname = Result[4];
                string S3_Extention = Result[5];
                string S3_FileName = Result[6];

                string FileName = S3_FileName.ToString().Trim();
                string BucketName = "suntoyo-aws-s3";
                string StoreName = S3_Brachname.ToString().Trim();
                string Url = V.ToString().Trim();
                string Extention = S3_Extention.ToString().Trim();
                int S3 = 0;

                string ChkIsExist = string.Empty;
                string cmd = " Select Inventoryid from  {0}.filedetails where Inventoryid={1}; ";

                string ChkIsExistQuery = string.Format(cmd, branchalias, Inventoryid);
                ChkIsExist = ObjMain.ExecuteScalar(ChkIsExistQuery);
                if (ChkIsExist != "")
                {
                    // Call Update Function 

                    string command = "UPDATE {0}.filedetails SET fileName=@fileName, BucketName=@BucketName,Url=@Url,Extention=@Extention ,ModifiedDate=@ModifiedDate " +
                        " where Inventoryid=@Inventoryid ; ";
                    //AND CompanyName = @CompanyName AND StoreName = @StoreName; Removed from the condition  16-11-21 
                    string S3_Update = string.Format(command, branchalias);


                    MySqlParameter[] parameters =
                    {
                     new MySqlParameter("@fileName",FileName),
                     new MySqlParameter("@BucketName",BucketName),
                     new MySqlParameter("@Url",Url),
                     new MySqlParameter("@Extention",Extention),
                     new MySqlParameter("@ModifiedDate",Curr_Date),
                     new MySqlParameter("@Inventoryid",Inventoryid),
                     new MySqlParameter("@CompanyName",S3_Companyname),
                     new MySqlParameter("@StoreName",StoreName),

                    };
                    S3 = ObjMain.ExecuteQuery(S3_Update, parameters);


                    // Get the Fileid 
                    string QUERYA = "select fileid from {0}.filedetails  where inventoryid=@Inventoryid ; ";

                    string CommandA = string.Format(QUERYA, branchalias);


                    MySqlParameter[] parametersA =
                   {
                     new MySqlParameter("@Inventoryid",Inventoryid),
                   };
                    FileID = ObjMain.NewExecuteScalar(CommandA, parametersA);
                    hdnfileid.Value = FileID;

                }
                else
                {
                    // Call Insert Functiom

                    string commandB = " INSERT INTO  {0}.filedetails(fileName,BucketName,CompanyName,StoreName, Url, Extention,Inventoryid) " +
                        " values(@fileName,@BucketName,@CompanyName,@StoreName,@Url,@Extention,@Inventoryid )";

                    string S3_Insert = string.Format(commandB, branchalias);
                    MySqlParameter[] parameters =
                   {
                     new MySqlParameter("@fileName",FileName),
                     new MySqlParameter("@BucketName",BucketName),
                     new MySqlParameter("@CompanyName",S3_Companyname),
                     new MySqlParameter("@StoreName",StoreName),
                     new MySqlParameter("@Url",Url),
                     new MySqlParameter("@Extention",Extention),
                     new MySqlParameter("@Inventoryid",Inventoryid),

                    };
                    S3 = ObjMain.ExecuteQuery(S3_Insert, parameters);



                    // Get the Fileid 
                    string QUERYA = "select fileid from {0}.filedetails  where inventoryid=@Inventoryid; ";

                    string CommandA = string.Format(QUERYA, branchalias);


                    MySqlParameter[] parametersA =
                   {
                     new MySqlParameter("@Inventoryid",Inventoryid),
                   };
                    FileID = ObjMain.NewExecuteScalar(CommandA, parametersA);
                    hdnfileid.Value = FileID;
                }


                string Qry_Image = "select substring( I.ImagePath,1) AS ImagePath from {0}.inventory as i  where inventoryid={1}";
                string commandx = string.Format(Qry_Image, BranchAlias, GInventoryID);
                DTImageResult = ObjCloudMain.GetData_DT(commandx);

             


            }
            else
            {


            }


        }

        [WebMethod]
        public static int SaveImagetoS3(string branchalias, string Barcode, string data)
        {
            // Prevention SQL Injection : 07-10-21
            // Parameterized approach 
            // Prevention XSS


            // Get the Full S3Path 

            

            DataTable DTImageResult = new DataTable();
            MYSQLDB objMain = new MYSQLDB();
            string FileID = string.Empty;
            string Curr_Date = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            // Get the Full S3Path 
            // var A = "https://suntoyo-aws-s3.s3.ap-southeast-1.amazonaws.com/49/da1/jpg/a01.jpg";
            int S3 = 0;
            int S3_U = 0;

            if (data != "")
            {

                var JsonResult = data;

                HttpContext.Current.Session["LastValue"] = Barcode;

                // Hided on 16-06-2025 
                // Root myDeserializedClass = JsonConvert.DeserializeObject<Root>(JsonResult);
                // var V = myDeserializedClass.dbPath;
                var V = JsonResult;


                //hdnurl.Value = V;  actual path 
                var Result = V.Split('/');
                string S3_http = Result[0];
                string S3_null = Result[1];
                string S3_S3link = Result[2];
                string S3_Companyname = Result[3];
                string S3_Brachname = Result[4];
                string S3_Extention = Result[5];
                string S3_FileName = Result[6];

                string FileName = S3_FileName.ToString().Trim();
                string BucketName = "suntoyo-aws-s3";
                string StoreName = S3_Brachname.ToString().Trim();
                string Url = V.ToString().Trim();
                string Extention = S3_Extention.ToString().Trim();


                string[] a = FileName.Split('.');
                string NewBarcode = a[0];

                string ChkIsExist = string.Empty;
                // Getting the Inventoryid using the Barcode 
                // Prevention SQL Injection   18-10-21
                // Prevention xss 
                // Parameterized Approach 

                string QR1 = " Select Inventoryid from  {0}.inventory where Barcode='{1}' ";
                string ReadqueryforInventoryid = string.Format(QR1, branchalias, NewBarcode);
                string Inventoryid = objMain.ExecuteScalar(ReadqueryforInventoryid);

                if (Inventoryid != "")
                {

                    string QR2 = " Select Inventoryid from  {0}.filedetails where Inventoryid={1}  ";
                    string ChkIsExistQuery = string.Format(QR2, branchalias, Inventoryid);
                    ChkIsExist = objMain.ExecuteScalar(ChkIsExistQuery);
                    if (ChkIsExist != "")
                    {
                        // Call Update 

                        string QR3 = "UPDATE {0}.filedetails SET fileName=@fileName, BucketName=@BucketName,Url=@Url,Extention=@Extention ,ModifiedDate=@ModifiedDate where Inventoryid=@Inventoryid AND CompanyName=@CompanyName AND StoreName=@StoreName; ";
                        string S3_Update = string.Format(QR3, branchalias);
                        MySqlParameter[] parameters =
                        {
                             new MySqlParameter("@fileName",FileName),
                             new MySqlParameter("@BucketName",BucketName),
                             new MySqlParameter("@Url",Url),
                             new MySqlParameter("@Extention",Extention),
                             new MySqlParameter("@ModifiedDate",Curr_Date),
                             new MySqlParameter("@Inventoryid",Inventoryid),
                             new MySqlParameter("@CompanyName",S3_Companyname),
                             new MySqlParameter("@StoreName",StoreName),

                        };


                        S3 = objMain.ExecuteQuery(S3_Update, parameters);

                        // Get the fileId 
                        string QR4 = "select fileid from {0}.filedetails  where inventoryid=@inventoryid and companyname=@companyname and StoreName=@StoreName ;";
                        string Command4 = string.Format(QR4, branchalias);
                        MySqlParameter[] parameters4 =
                       {

                             new MySqlParameter("@Inventoryid",Inventoryid),
                             new MySqlParameter("@CompanyName",S3_Companyname),
                             new MySqlParameter("@StoreName",StoreName),

                        };


                        FileID = objMain.NewExecuteScalar(Command4, parameters4);
                        // hdnfileid.Value = FileID;

                        // ImagePath Update in Inventory 
                        string QR5 = "update  {0}.Inventory set imagepath=@imagepath, fileid=@fileid where Inventoryid=@Inventoryid ; ";
                        string S3_InventoryUpdate = string.Format(QR5, branchalias);
                        MySqlParameter[] parameters5 =
                       {
                             new MySqlParameter("@imagepath", V),
                             new MySqlParameter("@fileid",FileID),
                             new MySqlParameter("@Inventoryid",Inventoryid),


                        };

                        S3_U = objMain.ExecuteQuery(S3_InventoryUpdate, parameters5);                      

                    }
                    else
                    {
                        // Call Insert 
                        string QR6 = " INSERT INTO  {0}.filedetails(fileName,BucketName,CompanyName,StoreName, Url, Extention,Inventoryid)" +
                            "values(@fileName,@BucketName,@CompanyName,@StoreName,@Url,@Extention,@Inventoryid)";
                        string S3_Insert = string.Format(QR6, branchalias);

                        MySqlParameter[] parameters6 =
                         {
                             new MySqlParameter("@fileName",FileName),
                             new MySqlParameter("@BucketName",BucketName),
                             new MySqlParameter("@CompanyName",S3_Companyname),
                             new MySqlParameter("@StoreName",StoreName),
                             new MySqlParameter("@Url",Url),
                             new MySqlParameter("@Extention",Extention),
                             new MySqlParameter("@Inventoryid",Inventoryid),
                        };

                        S3 = objMain.ExecuteQuery(S3_Insert, parameters6);
                        // Get the FileId 
                        string QR7 = "select fileid from {0}.filedetails  where inventoryid=@inventoryid and companyname=@companyname and StoreName=@StoreName ;";
                        string command7 = string.Format(QR7, branchalias);
                        MySqlParameter[] parameters7 =
                       {
                             new MySqlParameter("@Inventoryid",Inventoryid),
                             new MySqlParameter("@CompanyName",S3_Companyname.ToString().Trim()),
                             new MySqlParameter("@StoreName",StoreName),
                        };


                        FileID = objMain.NewExecuteScalar(command7, parameters7);

                        string QR8 = "update  {0}.Inventory set imagepath=@imagepath,fileid=@fileid where Inventoryid=@Inventoryid  ; ";
                        string S3_InventoryUpdate = string.Format(QR8, branchalias);
                        MySqlParameter[] parameters8 =
                        {
                             new MySqlParameter("@imagepath", V),
                             new MySqlParameter("@fileid",FileID),
                             new MySqlParameter("@Inventoryid",Inventoryid),


                        };

                        S3_U = objMain.ExecuteQuery(S3_InventoryUpdate, parameters8);
                        // hdnfileid.Value = FileID;
                    }

                    

                }
                else
                {


                }



            }
            else
            {
            }

            ClearCacheItems();


            return S3;




        }

        public class Root
        {
            public string dbPath { get; set; }
        }

        //public void SavePromoItem(string DB,string InventoryID,string Barcode) //John added on 16-Aug-2021 Insert WebOrderPromo
        //{            
        //    int NewMainPosition = int.Parse(ObjSel.GetLastWebOrderMainPosition(DB)) + 1; //Auto Increment MainPosition(Based on Last MainPostion +  1) SubPosition default = 1
        //    string InsertWebPromo = "Insert Into " + DB + ".WebOrderPromo(InventoryID,Barcode,MainPosition,SubPosition)Values('" + InventoryID + "','" + Barcode + "','" + NewMainPosition + "',1)";
        //    iInsertWebOrderPromo = ObjCloudMain.ExecuteNonQuery(InsertWebPromo);
        //}

        //public void RemovePromoItem(string DB, string InventoryID) //john added on 16-Aug-2021 Remove WebOderPromo
        //{
        //    string RemoveWebPromo = "Delete from " + DB + ".WebOrderPromo where InventoryID = '" + InventoryID + "'";
        //    IDeleteWebOrderPromo = ObjCloudMain.ExecuteNonQuery(RemoveWebPromo);
        //}




        //public string CheckSlaveBarcode()
        //{
        //    string sResutl = string.Empty;
        //    MySqlConnection Cn = new MySqlConnection(ConStr_Rds);
        //    Cn.Open();
        //    MySqlCommand sCmdCheck = new MySqlCommand("Select *from " + sDB + ".inventorymulticode where SlaveBarcode = '" + sSBarcode + "'", Cn);
        //    MySqlDataAdapter da = new MySqlDataAdapter(sCmdCheck);
        //    DataSet ds = new DataSet();
        //    DataTable Dt = new DataTable();
        //    da.Fill(Dt);
        //    Cn.Close();
        //    if (Dt.Rows.Count == 0)
        //    {

        //        return "False";
        //    }
        //    else
        //    {
        //        return "True";              

        //    }
        //}

        /// <summary>
        ///  This Fucntion Inserts Records into PriceFlag  Table  On Few Conditions
        /// </summary>
        /// <param name="sdb"></param>
        public void INS_PriceFlage(string sdb)
        {

            // Local Variable 

            string Inventoryid = string.Empty;
            string Barcode = string.Empty;

            //#1 Check the PriceFlage table Record  count 

            string PriceFlagQuery = "select * from {0}.PriceFlag;";
            string Price_command = string.Format(PriceFlagQuery, sdb);
            DtPriceFlag = ObjMain.GetData_DT(Price_command);

            //#2 Get Inventory Table Record Count 

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

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

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

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

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

                    // #1.2 IF Not Exist   
                    // Call Insert  Function : PriceFlag
                    #region   Insert Portion
                    string Ins_PriceFlag = " insert into {0}.PriceFlag (Inventoryid,Barcode,Price_Flag,Price2_Flag,Price3_Flag,Price4_Flag)" +
                                           " values " +
                                           " (@Inventoryid,@Barcode,@Price_Flag,@Price2_Flag,@Price3_Flag,@Price4_Flag);";
                    string Ins_command = string.Format(Ins_PriceFlag, sdb);
                    MySqlParameter[] parameters =
                        {
                             new MySqlParameter("@Inventoryid",Inventoryid),
                             new MySqlParameter("@Barcode",Barcode),
                             new MySqlParameter("@Price_Flag","0"),
                             new MySqlParameter("@Price2_Flag","0"),
                             new MySqlParameter("@Price3_Flag","0"),
                             new MySqlParameter("@Price4_Flag","0"),
                        };
                    Q = ObjMain.ExecuteQuery(Ins_command, parameters);




                    #endregion
                }


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

                string CheckA = string.Empty;

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

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

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

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

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

                    string ReadInventoryidOnPriceFlag = "select Inventoryid from {0}.PriceFlag where  Inventoryid=@Inventoryid ; ";
                    string command_ReadPriceflag = string.Format(ReadInventoryidOnPriceFlag, sdb);
                    MySqlParameter[] parameters =
                    {
                     new MySqlParameter("@Inventoryid",Inventoryid),
                    };
                    CheckA = ObjMain.NewExecuteScalar(command_ReadPriceflag, parameters);

                    if (CheckA != "")
                    {
                        // Record Already Exist In PriceFlag : Ignore for insert 
                    }
                    else
                    {
                        // Call Insert  Function : PriceFlag  
                        #region   Insert Portion
                        string Ins_PriceFlag = " insert into {0}.PriceFlag (Inventoryid,Barcode,Price_Flag,Price2_Flag,Price3_Flag,Price4_Flag)" +
                                               " values " +
                                               " (@Inventoryid,@Barcode,@Price_Flag,@Price2_Flag,@Price3_Flag,@Price4_Flag);";
                        string Ins_command = string.Format(Ins_PriceFlag, sdb);
                        MySqlParameter[] parametersM =
                            {
                             new MySqlParameter("@Inventoryid",Inventoryid),
                             new MySqlParameter("@Barcode",Barcode),
                             new MySqlParameter("@Price_Flag","0"),
                             new MySqlParameter("@Price2_Flag","0"),
                             new MySqlParameter("@Price3_Flag","0"),
                             new MySqlParameter("@Price4_Flag","0"),
                        };
                        Q = ObjMain.ExecuteQuery(Ins_command, parametersM);

                        #endregion

                    }


                }



            }
            else
            {
                // Nothing To :  Run 
            }




        }


        public void INS_WebStock(string sdb)
        {

            // Local Variable 

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

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

            //#2 Get Inventory Table Record Count 

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

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

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

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

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

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


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

                string CheckA = string.Empty;

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

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

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

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

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

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

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

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

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

                        #endregion


                    }


                }



            }
            else
            {
                // Nothing To :  Run 
            }




        }




        /// <summary>
        ///  This Function For the Logic of Include Or Exclude the Common Update 
        /// </summary>
        /// <param name="sdb"></param>
        public void INS_ScheduleFlag(string sdb)
        {

            // Local Variable 

            string Inventoryid = string.Empty;
            string Barcode = string.Empty;
            DataTable DtScheduleFlag = new DataTable();

            //#1 Check the PriceFlage table Record  count 

            string TimescheduleFlagQuery = "select * from {0}.timescheduleFlag;";
            string schedule_command = string.Format(TimescheduleFlagQuery, sdb);
            DtScheduleFlag = ObjMain.GetData_DT(schedule_command);

            //#2 Get Inventory Table Record Count 

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

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

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

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

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

                    // #1.2 IF Not Exist   
                    // Call Insert  Function : PriceFlag
                    #region   Insert Portion
                    string Ins_ScheduleFlag = " insert into {0}.timescheduleFlag (Inventoryid,Barcode,IsCommonUpdate)" +
                                              " values " +
                                              " (@Inventoryid,@Barcode,@IsCommonUpdate);";
                    string Ins_command = string.Format(Ins_ScheduleFlag, sdb);
                    MySqlParameter[] parameters =
                        {
                             new MySqlParameter("@Inventoryid",Inventoryid),
                             new MySqlParameter("@Barcode",Barcode),
                             new MySqlParameter("@IsCommonUpdate","0"),
                        };
                    Q = ObjMain.ExecuteQuery(Ins_command, parameters);




                    #endregion
                }


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

                string CheckA = string.Empty;

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

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

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

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

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

                    string ReadInventoryidOnScheduleFlag = "select Inventoryid from {0}.timescheduleFlag where  Inventoryid=@Inventoryid ; ";
                    string command_ReadScheduleflag = string.Format(ReadInventoryidOnScheduleFlag, sdb);
                    MySqlParameter[] parameters =
                    {
                     new MySqlParameter("@Inventoryid",Inventoryid),
                    };
                    CheckA = ObjMain.NewExecuteScalar(command_ReadScheduleflag, parameters);

                    if (CheckA != "")
                    {
                        // Record Already Exist In ScheduleFlag : Ignore for insert 
                    }
                    else
                    {
                        // Call Insert  Function : ScheduleFlag  
                        #region   Insert Portion
                        string Ins_ScheduleFlag = " insert into {0}.timescheduleFlag (Inventoryid,Barcode,IsCommonUpdate)" +
                                               " values " +
                                               " (@Inventoryid,@Barcode,@IsCommonUpdate);";
                        string Ins_command = string.Format(Ins_ScheduleFlag, sdb);
                        MySqlParameter[] parametersAA =
                            {
                             new MySqlParameter("@Inventoryid",Inventoryid),
                             new MySqlParameter("@Barcode",Barcode),
                             new MySqlParameter("@IsCommonUpdate","0"),
                        };
                        Q = ObjMain.ExecuteQuery(Ins_command, parametersAA);




                        #endregion

                    }


                }



            }
            else
            {
                // Nothing To :  Run 
            }




        }

        #region  CSV Validation  Karthik Created  on 13-07-2023

        /// <summary>
        ///  This funcatin uses to validate the Header of the csv file when import function 
        /// </summary>
        /// <param name="_path"></param>
        /// <returns></returns>
        private bool ValidateCSVHeader(string _path)
        {

            string[] expectedHeaders = { "Barcode", "InventoryName", "Description", "CategoryName", "Price", "Price2", "Price3", "Price4", "Stock", "Unitcost", "NoPriceShift", "Group1", "Group2", "Group3", "Group4", "Group5", "StockCode", "Unit", "Notes", "Imagepath", "OnHand" };
            bool Hasvalue;
            Hasvalue = File.Exists(_path);
            if (Hasvalue == false)
            {
                AlertA.Visible = true;
                Log.Info(Curr_Date + ": " + "File does not Exist.");
                sb.AppendLine(Curr_Date + ": " + "File does not Exist." + "<br/>");
                lblimportError.Text = sb.ToString();
                return Hasvalue;
            }

            string[] lines = File.ReadAllLines(_path);
            if (lines.Length < 2)
            {
                AlertA.Visible = true;
                Log.Info(Curr_Date + ": " + "CSV file must have at least 2 lines (headers and one data row)");
                sb.AppendLine(Curr_Date + ": " + "CSV file must have at least 2 lines (headers and one data row)" + "<br/>");
                lblimportError.Text = sb.ToString();
            }
            string[] headers = lines[0].Split(',');
            if (headers.Length != expectedHeaders.Length)
            {
                AlertA.Visible = true;
                sb.AppendLine(Curr_Date + ": " + "Incorrect number of headers- Expected {0} :" + expectedHeaders.Length + "<br/>");
                sb.AppendLine(Curr_Date + ": " + "Incorrect number of headers- found {1} :" + headers.Length + "<br/>");
                lblimportError.Text = sb.ToString();
                Hasvalue = false;
            }
            return Hasvalue;
        }

        // CSV Validation  Main function 
        public List<CsvDataModel> ImportAndValidateCsvData(Stream csvStream)
        {
            List<CsvDataModel> validDataList = new List<CsvDataModel>();

            using (var reader = new StreamReader(csvStream, Encoding.UTF8))
            using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
            {
                // csv.Configuration.HeaderValidated = null;
                // csv.Configuration.MissingFieldFound = null;
                while (csv.Read())
                {

                    try
                    {

                        CsvDataModel dataModel = csv.GetRecord<CsvDataModel>();

                        if (ValidateCsvRecord(dataModel))
                        {

                            // Perform additional custom validations
                            // Add the validated data to the list
                            validDataList.Add(dataModel);

                        }

                    }
                    catch (CsvHelper.ValidationException ex)
                    {
                        // Handle validation errors for the specific record
                        // You can log errors or take appropriate actions

                        Log.Info(Curr_Date + ": " + "Imported  Excel having some Data Type Issue...");
                        AlertA.Visible = true;
                        sb.AppendLine(Curr_Date + ": " + "Imported  Excel having some Data Type Issue..." + "<br/>");
                        sb.AppendLine(Curr_Date + ": " + "Error Details ->" + ex + "<br/>");
                        lblimportError.Text = sb.ToString();

                    }
                }
            }

            return validDataList;
        }

        private bool ValidateCsvRecord(CsvDataModel record)
        {
            // Perform additional custom validation if needed
            // For example, check if the string values can be converted to the desired data types

            // Use data annotations for basic validation
            var validationContext = new ValidationContext(record);
            var validationResults = new List<ValidationResult>();
            bool isValid = Validator.TryValidateObject(record, validationContext, validationResults, true);

            if (isValid == false)
            {
                AlertA.Visible = true;
                string _validate_result = JsonConvert.SerializeObject(validationResults, Formatting.Indented);
                Log.Info(Curr_Date + ": " + "Failed-Row Barcode : " + record.Barcode);
                Log.Info(Curr_Date + ": " + "Validation Errors : " + _validate_result);

                sb.AppendLine(Curr_Date + ": " + "Import Failed -Row Barcode -> " + record.Barcode + "<br/>");
                sb.AppendLine(Curr_Date + ": " + "Validation Errors Details -> " + _validate_result + "<br/>");
                lblimportError.Text = sb.ToString();
            }
            else
            {
                string _validated_record = JsonConvert.SerializeObject(record, Formatting.Indented);
                Log.Info(Curr_Date + ": " + "Barcode -> " + record.Barcode);
                Log.Info(Curr_Date + ": " + "Validation-Success -> " + _validated_record);


            }


            return isValid;
        }

        public class ListtoDataTableConverter
        {
            public DataTable ToDataTable<T>(List<T> items)
            {
                DataTable dataTable = new DataTable(typeof(T).Name);
                //Get all the properties
                PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
                foreach (PropertyInfo prop in Props)
                {
                    //Setting column names as Property names
                    dataTable.Columns.Add(prop.Name);
                }
                foreach (T item in items)
                {
                    var values = new object[Props.Length];
                    for (int i = 0; i < Props.Length; i++)
                    {
                        //inserting property values to datatable rows
                        values[i] = Props[i].GetValue(item, null);
                    }
                    dataTable.Rows.Add(values);
                }
                //put a breakpoint here and check datatable
                return dataTable;
            }
        }

        #endregion



        #region  WebMethod 


        [WebMethod]
        public static string IsEnableUnitPrice(string DB)
        {
            try
            {
                BL_SELECT objSel = new BL_SELECT();
                DataTable DT = new DataTable();
                BL_API ObjApi = new BL_API();

                string IniID = "82"; //  UnitPrice Show/Hide
                string BarereTokenVal = ObjApi.GetBarerToken();
                string JSONRetVal = ObjApi.API_GET_INIWebOrderingIniValue(BarereTokenVal, DB, IniID);
                var sObject = JsonConvert.DeserializeObject(JSONRetVal);
                return sObject.ToString();
                //string BarerTokenVal = 
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }



        #endregion




    }


}