using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections;
using System.Web;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using System.Configuration;
using MySql.Data.MySqlClient;
using MySql.Data;
using CLS_BL;
using CLS_DL;
using CLS_PL;
using System.Data.OleDb;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
using System.Web.UI.DataVisualization.Charting;
using System.Drawing.Printing;
using System.Drawing;
using System.Drawing.Text;
using Newtonsoft;
using Newtonsoft.Json;
using RestSharp;
using System.Reflection;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Net;
using System.Text.RegularExpressions;
using CsvHelper;
using System.Globalization;

namespace SUNWEB
{
    public partial class InventoryPackage : System.Web.UI.Page
    {


        BL_SELECT ObjSel = new BL_SELECT();
        BLCompany ObjBL = new BLCompany();
        PLCOMMON ObjPL = new PLCOMMON();
        BL_USER ObjUserBL = new BL_USER(); //This Object for All User and Page Related fuctions included 
        PLCUSTOMER ObjCustPL = new PLCUSTOMER();
        Int32 K = 0;
        Int32 L = 0;
        Int32 S = 0;
        string ConStr = ConfigurationManager.ConnectionStrings["ConMysql"].ConnectionString;
        string ConStr_Rds = ConfigurationManager.ConnectionStrings["ConRDS"].ConnectionString;
        string Curr_Date = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        string Curr_DateOnly = System.DateTime.Now.ToString("yyyy-MM-dd");
        DateTime MonthstartDt;
        DataSet ds = new DataSet();
        MYSQLDB ObjMain = new MYSQLDB();
        DataTable DT = new DataTable();
        DataTable Dt2 = new DataTable();
        DataTable DtLicense = new DataTable();
        DataTable DtSuperAdmin = new DataTable();
        DataTable DtMultiBranch = new DataTable();
        DataTable DtNormalUser = new DataTable();
        DataTable DTProductSale = new DataTable();
        DataTable DTInvInfo = new DataTable();
        MySqlCommand Cmdv = new MySqlCommand();
        DataTable AdjDt = new DataTable();
        DataTable fFAdjDt = new DataTable();
        DataTable FPckDt = new DataTable();
        // User Variables 
        string UserId = string.Empty;
        string UserName = string.Empty;
        string PortalTypeId = string.Empty;
        string cd_Id = string.Empty;
        string Datapath = string.Empty;
        string cd_BranchAlias = string.Empty;
        string IsMultiBranch = string.Empty;
        string IsSuperAdmin = string.Empty;
        string ActiveCallvalue = string.Empty;
        // License Variables ..
        string PID = string.Empty;
        string Page_Acess = string.Empty;
        string Read_Acess = string.Empty;
        string Write_Acess = string.Empty;
        string Isdowld_Acess = string.Empty;
        string Rcd_id = string.Empty;
        string RPortalid = string.Empty;
        string Useridvalue = string.Empty;
        string QueryCurr_Select = string.Empty;
        string L_MaxUserCnt = string.Empty;

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

        string HQ = string.Empty;
        string Cm_id = string.Empty;
        string ISHQ = string.Empty;
        DataSet DS = new DataSet();
        string BranchAlias = string.Empty;
        string Vw_Chk = string.Empty;

        Int32 InsertMultiBarcode;
        Int32 InsertInventoryPackage;
        Int32 DeleteExistingSlave;
        Int32 DeleteExistingPackageItem;
        Int32 DeletePackageItem;
        Int32 DeleteSlave;
        string sSno = string.Empty;
        int iSno = 0;
        string sCmd = string.Empty;
        Int32 U = 0;
        string sActive = string.Empty;
        string RBranchid = string.Empty;
        string Branchid = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {

            PID = "50";    // This is for InventoryPackage Page 


            if (!IsPostBack)
            {
               
            }
            MonthstartDt = new DateTime(System.DateTime.Now.Year, System.DateTime.Now.Month, 1);
            if (Session["UserName"] == null)
            {
                Response.Redirect("Login.aspx");
            }
            if (((Convert.ToBoolean(Session["IsSuperAdmin"])) == true) && (Session["PortalTypeId"].ToString() == "") && ((Convert.ToBoolean(Session["IsMultiBranch"])) == true))
            {
                if (!IsPostBack)
                {
                    LoadBranchesOnID();

                    string QueryCal = "select ActiveValue from portaldb.usermaster  where Userid=" + Session["UserId"].ToString() + " ";
                    ActiveCallvalue = ObjMain.ExecuteScalar(QueryCal);
                    if (ActiveCallvalue != " " || ActiveCallvalue != "Select Branch")
                    {
                        ActiveCall();
                    }
                }
            }
            else if (((Convert.ToBoolean(Session["IsSuperAdmin"])) == true) && (Session["PortalTypeId"].ToString() == ""))
            {
                if (!IsPostBack)
                {
                    LoadBranchesOnID();
                }
                cd_BranchAlias = cmbBranches.SelectedItem.Text;
                //LoadInventoryListGrid(cd_BranchAlias, txtStartDt.Text, txtEndDt.Text);
            }
            else if (((Convert.ToBoolean(Session["IsMultiBranch"])) == true) && (Session["PortalTypeId"].ToString() == ""))
            {
                if (!IsPostBack)
                {
                    LoadBranchesOnID();
                    ActiveCall();
                }
            }
            else if (((Session["PortalTypeId"].ToString() != "") || (Convert.ToBoolean(Session["IsSuperAdmin"])) == false) && ((Convert.ToBoolean(Session["IsMultiBranch"])) == false))
            {
                cmbBranches.Enabled = false;
                cmbBranches.Visible = false;

                Cm_id = ObjSel.GETcmid(Session["Cd_Id"].ToString());  // Get cm_id
                HQ = ObjSel.Get_HQ(Cm_id);     // Get the HQ Value
                Curr_BranchFullName = ObjSel.GetBranchFullName(HQ, Session["Branch_HQ"].ToString());
                
               

                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_InventoryPackage"].ToString() == "N") || (Session["Page_Acess"].ToString() == "N"))
                {
                    Response.Redirect("DeniedPage.aspx");
                }
                else
                {
                    // lblMsgTotalSelection.Text = "Item Sale  Between" + "&nbsp;&nbsp;&nbsp;&nbsp;" + txtStartDt.Text + "&nbsp;&nbsp;&nbsp;  and  &nbsp;&nbsp;&nbsp;" + txtEndDt.Text;
                    if (!IsPostBack)
                    {
                        if (Session["Isdowld_Acess"].ToString() == "N")
                        {
                            // btnExcel.Enabled = false;
                            Response.Write(@"<script language='javascript'>alert('No Access To download.')</script>");
                        }
                        else
                        {
                            

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

                        }


                    }

                }

            }
            else
            {

            }


        }


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

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

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

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


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


                    }


                }


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

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

        }


        public void ActiveCall()
        {
            string ReadHQ = string.Empty;
            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


               
            }


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

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

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

            }

           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=" + Microsoft.Security.Application.Encoder.HtmlEncode(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_InventoryPackage = DtLicense.Rows[0]["INVENTORYPACKAGE"].ToString();
                Session["L_InventoryPackage"] = L_InventoryPackage;


            }
            if ((Session["L_InventoryPackage"] == null) || Session["L_InventoryPackage"].ToString() == "N" || Session["Page_Acess"].ToString() == "N")
            {

                if (cmbBranches.SelectedItem.Text == "HQ")
                {
                    // btnExcel.Enabled = true;
                    // HQ Validation    02-12-21

                    #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

                    // Include the Loading Functions 
                    // Hided on 08-10-255 
                   //  LoadInventoryview();
                    // LoadPIInventoryview(BranchAlias);
                     UPDATEBRANCH(Cmb_BranchName);


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



            }
            else if (Session["Write_Acess"].ToString() == "N")
            {
                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

                // HQ Validation    02-12-21
                // Include the Load Functions
                // Hided on 08-10-255 
               //  LoadInventoryview();     
                //LoadPIInventoryview(BranchAlias);
                UPDATEBRANCH(Cmb_BranchName);

            }
        }
       public void LoadBranchName()
        {
            DtNormalUser = ObjUserBL.GetBranchOnLoginValues8(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), Session["CM_ID"].ToString());
            if (DtNormalUser.Rows.Count > 0)
            {
                cmbBranches.DataSource = DtNormalUser;
                cmbBranches.DataTextField = "branchfullname";
                cmbBranches.DataValueField = "Branchid";
                cmbBranches.DataBind();
                cmbBranches.Items.Insert(0, "Select Branch");
            }
        }
        public void LoadBranchName4SuperAdmin()
        {
            DtSuperAdmin = ObjUserBL.GetBranchOnSuperAdmin8(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), Session["CM_ID"].ToString());
            if (DtSuperAdmin.Rows.Count > 0)
            {
                cmbBranches.DataSource = DtSuperAdmin;
                cmbBranches.DataTextField = "branchfullname";
                cmbBranches.DataValueField = "Branchid";
                cmbBranches.DataBind();
                cmbBranches.Items.Insert(0, "Select Branch");
            }
        }
        public void UPDATEBRANCH(string ActiveCallvalue)
        {
            if (!string.IsNullOrEmpty(Session["UserId"] as string))
            {
                Useridvalue = Session["UserId"].ToString();
                QueryCurr_Select = "Update portaldb.usermaster set ActiveValue='" + ActiveCallvalue + "' where Userid=" + Useridvalue + "";
                S = ObjMain.ExecuteNonQuery(QueryCurr_Select);
            }
            else
            {
                Response.Redirect("Login.aspx");

            }

        }


      

        protected void btnGetReports_Click(object sender, EventArgs e)
        {

        }

        protected void cmbBranches_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbBranches.SelectedIndex == 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;
                //  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;
                // this.Page.ClientScript.RegisterStartupScript(this.GetType(), "Javascript", "javascript:GetActiveSession5();", true);
               
            }

            if (cmbBranches.SelectedIndex == 0)
            {
                Response.Write("InventoryPackage.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_InventoryPackage = DtLicense.Rows[0]["INVENTORYPACKAGE"].ToString();
                    Session["L_InventoryPackage"] = L_InventoryPackage;
                }

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

                        ClearForms();
                        // Disable Temporarily On 27-03-24 : Paging need to do 
                        // Karthik Hided on 08-10-25
                       // LoadInventoryview();
                       // LoadPIInventoryview(BranchAlias); 
                        UPDATEBRANCH(Cmb_BranchName);

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

                }

                else
                {
                    if (Session["Write_Acess"].ToString() == "N")
                    {
                      
                        //If No .. Disable the Button 

                    }
                    else if (Session["Write_Acess"].ToString() == "Y")
                    {
                        //If Yes .. Enable the Button 
                    }
                    #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
                    ClearForms();
                    // Disable temporarily on 27-03-24 
                    // Karthik Hided on 08-10-25
                   // LoadInventoryview();
                   // LoadPIInventoryview(BranchAlias);   
                    UPDATEBRANCH(Cmb_BranchName);

                }
            }
        }

        protected void txtSearchVal_TextChanged(object sender, EventArgs e)
        {

        }

        protected void cmbSearch_SelectedIndexChanged(object sender, EventArgs e)
        {
            txtSearchVal.CssClass = "form-control";
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ShowPackageModelList();", true);
        }

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

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

                }
                #endregion
            }



            if (cmbPISearch.SelectedIndex == 0)
            {

            }
           

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


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


                string Inv_Qry1 = "Select *,Round(UnitCost,3) as UCost,sum(pquantity-(CutQuantity+RetailQty))as OnHandICA,0 as Qty from {0}.inventory as I " +
                                " join {0}.inventorycategories  as c ON I.Categoryid=c.categoryid " +
                                " join {0}.inventorycostaverage ic on ic.inventoryid=i.inventoryid where I.Inventoryid=@Inventoryid  " + sActive + "  ";

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

                MySqlParameter[] parameters =
                {
                     new MySqlParameter("@Inventoryid",Microsoft.Security.Application.Encoder.HtmlEncode(txtPISearchVal.Text.ToString().Trim())),

                    };

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

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


                string Inv_Qry2 = "Select *,Round(UnitCost,3) as UCost,sum(pquantity-(CutQuantity+RetailQty))as OnHandICA,0 as Qty from {0}.inventory as I " +
                                " join {0}.inventorycategories  as c ON I.Categoryid=c.categoryid " +
                                " join {0}.inventorycostaverage ic on ic.inventoryid=i.inventoryid where   I.barcode like  CONCAT('%',@barcode,'%' )    " + sActive + " Group by I.barcode ";

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

                MySqlParameter[] parameters1 =
                    {
                     new MySqlParameter("@barcode",Microsoft.Security.Application.Encoder.HtmlEncode(txtPISearchVal.Text.ToString().Trim())),

                    };

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

            }

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



                //string Inv_Qry3 = "select * from " + BranchAlias + ".inventory as I join  " + BranchAlias + ".inventorycategories  as c ON I.Categoryid=c.categoryid where  I.InventoryName like '%" + txtSearchVal.Text.ToString().Trim() + "%' ";
                string Inv_Qry3 = "Select *,Round(UnitCost,3) as UCost,sum(pquantity-(CutQuantity+RetailQty))as OnHandICA,0 as Qty from {0}.inventory as I " +
                                "  join {0}.inventorycategories  as c ON I.Categoryid=c.categoryid " +
                                "  join {0}.inventorycostaverage ic on ic.inventoryid=i.inventoryid where  I.InventoryName like  CONCAT('%',@SearchVal,'%')   " + sActive + " group by I.inventoryid  ";

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


                MySqlParameter[] parameters =
                    {
                     new MySqlParameter("@SearchVal",Microsoft.Security.Application.Encoder.HtmlEncode(txtPISearchVal.Text.ToString().Trim())),

                    };

                DT = ObjMain.NewGetData_DT(command, parameters);

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



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



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

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

                MySqlParameter[] parameters =
                    {
                     new MySqlParameter("@SearchVal",Microsoft.Security.Application.Encoder.HtmlEncode(txtPISearchVal.Text.ToString().Trim())),

                    };
                DT = ObjMain.NewGetData_DT(command, parameters);
                grdPIInventoryView.DataSource = DT;
                grdPIInventoryView.DataBind();
            }


            if (cmbPISearch.SelectedIndex == 5)
            {
                string group1Value = "group1";
                LoadGroupDetail(group1Value, Microsoft.Security.Application.Encoder.HtmlEncode(txtPISearchVal.Text.ToString().Trim()));

            }
            else if (cmbPISearch.SelectedIndex == 6)
            {
                string group2Value = "group2";
                LoadGroupDetail(group2Value, Microsoft.Security.Application.Encoder.HtmlEncode(txtPISearchVal.Text.ToString().Trim()));

            }
            else if (cmbPISearch.SelectedIndex == 7)
            {
                string group3Value = "group3";
                LoadGroupDetail(group3Value, Microsoft.Security.Application.Encoder.HtmlEncode(txtPISearchVal.Text.ToString().Trim()));

            }

            else if (cmbPISearch.SelectedIndex == 8)
            {
                string group4Value = "group4";
                LoadGroupDetail(group4Value, Microsoft.Security.Application.Encoder.HtmlEncode(txtPISearchVal.Text.ToString().Trim()));

            }
            else if (cmbPISearch.SelectedIndex == 9)
            {
                string group5Value = "group5";
                LoadGroupDetail(group5Value, Microsoft.Security.Application.Encoder.HtmlEncode(txtPISearchVal.Text.ToString().Trim()));

            }


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



                //string Inv_Qry3 = "select * from " + BranchAlias + ".inventory as I join  " + BranchAlias + ".inventorycategories  as c ON I.Categoryid=c.categoryid where  I.InventoryName like '%" + txtSearchVal.Text.ToString().Trim() + "%' ";
                string Inv_Qry7 = "Select *,Round(UnitCost,3) as UCost,sum(pquantity-(CutQuantity+RetailQty))as OnHandICA,0 as Qty Qtyfrom {0}.inventory as I " +
                                "  join {0}.inventorycategories  as c ON I.Categoryid=c.categoryid " +
                                "  join {0}.inventorycostaverage ic on ic.inventoryid=i.inventoryid where  I.Description like CONCAT('%',@SearchVal,'%') " + sActive + " group by I.inventoryid  ";

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

                MySqlParameter[] parameters =
                   {
                      new MySqlParameter("@SearchVal",Microsoft.Security.Application.Encoder.HtmlEncode(txtPISearchVal.Text.ToString().Trim())),

                    };


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


            }


        }

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

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

                    }
                    #endregion

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




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




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

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

        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {


            string sActive = string.Empty;

            txtSearchVal.CssClass = "form-control";
            
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ShowPackageModelList();", 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)
            {

               // karthik  Hided on 08-10-25
               
                //if (chkActiveonly.Checked == true)
                //{
                //    sActive = " where I.active <> 0 and I.Class=9";
                //}
                //else
                //{
                //    sActive = " where I.active = 0 and  I.Class=9";
                //}
                //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);
                //grdInventory.DataSource = DT;
                //grdInventory.DataBind();
            }
            else if (cmbSearch.SelectedIndex == 1)
            {

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

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

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

                }


            }
            else if (cmbSearch.SelectedIndex == 2)
            {
                if (txtSearchVal.Text != "")
                {
                    if (chkActiveonly.Checked == true)
                    {
                        sActive = " and I.active <> 0 and I.Class=9";
                    }
                    else
                    {
                        sActive = " and I.active = 0 and I.Class=9";
                    }


                    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);
                    grdInventory.DataSource = DT;
                    grdInventory.DataBind();

                }
            }

            else if (cmbSearch.SelectedIndex == 3)
            {
                if (txtSearchVal.Text != "")
                {
                    if (chkActiveonly.Checked == true)
                    {
                        sActive = " and I.active <> 0 and I.Class=9";
                    }
                    else
                    {
                        sActive = " and I.active = 0 and I.Class=9";
                    }


                    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);
                    grdInventory.DataSource = DT;
                    grdInventory.DataBind();
                }

            }

            else if (cmbSearch.SelectedIndex == 4)
            {
                if (txtSearchVal.Text != "")
                {
                    if (chkActiveonly.Checked == true)
                    {
                        sActive = " and I.active <> 0 and I.Class=9";
                    }
                    else
                    {
                        sActive = " and I.active = 0 and I.Class=9";
                    }
                    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);
                    grdInventory.DataSource = DT;
                    grdInventory.DataBind();
                }

            }

            else if (cmbSearch.SelectedIndex == 5)
            {
                string sActivex = string.Empty;
                if (txtSearchVal.Text != "")
                {

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



                    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);
                    grdInventory.DataSource = DT;
                    grdInventory.DataBind();
                }
            
            }

        
        }

        public void LoadInventoryview()
        {
            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 {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  and i.class=9  group by i.inventoryid  ORDER BY I.inventoryID asc LIMIT 50000;";

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

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


        }


        protected void OnSelectedIndexChanged(object sender, EventArgs e)
        {

            string Barcode = (grdInventory.SelectedRow.FindControl("lblBarCode") as Label).Text;

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

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

            

            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

            }


            DTInvInfo = ObjSel.GetInvInfo(BranchAlias, txtPBarcode.Text.ToString().Trim());
            if (DTInvInfo.Rows.Count == 0)
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Item not found, please enter valid Barcode ')", true);

                return;
            }
            else
            {
                // Assing the values to the Package controls
                txtPInvID.Text = DTInvInfo.Rows[0]["Inventoryid"].ToString();
                txtPBarcode.Text = DTInvInfo.Rows[0]["Barcode"].ToString();
                txtPDescription.Text = DTInvInfo.Rows[0]["Description"].ToString();
                txtPInventoryName.Text = DTInvInfo.Rows[0]["InventoryName"].ToString();
                ShowPackagedItemsListUnderMaster(BranchAlias, txtPInvID.Text);    //Package Module 06-Mar-2023
                
             }

           

        }

        #region INNVENTORY PACKAGE
        //nid added for Package Item on 06-Mar-2023, Please do not add other codes in this region

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

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

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

            }

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

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

                    }
                    #endregion
                }
                else
                {
                    BranchAlias = Session["Branch_HQ"].ToString();
                }
                //LoadPIInventoryview(BranchAlias);
                ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ShowModelPackageItemList();", true);
            }
            else
            {
            }

        }

        public void btnSave_Click(object sender, System.EventArgs e) 
        {
            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();
            }


            /*
            FPckDt = (DataTable)Session["QtyPckTable"];        //session value assign to Final datatable for Submit

            if (AdjDt.Rows.Count == 0)
            {
                AdjDt.Columns.Add(new System.Data.DataColumn("SNo", typeof(String)));
                AdjDt.Columns.Add(new System.Data.DataColumn("PackageInvID", typeof(String)));
                AdjDt.Columns.Add(new System.Data.DataColumn("ItemInvID", typeof(String)));
                AdjDt.Columns.Add(new System.Data.DataColumn("Qty", typeof(String)));
                AdjDt.Columns.Add(new System.Data.DataColumn("Price", typeof(String)));
                AdjDt.Columns.Add(new System.Data.DataColumn("Action", typeof(String)));
            }

            DataRow dr;
            if (FPckDt != null)
            {
                if (FPckDt.Rows.Count > 0)
                {
                    foreach (DataRow row in FPckDt.Rows)    //load previous page session values to current datatable
                    {
                        dr = AdjDt.NewRow();
                        dr[0] = row["SNo"].ToString();
                        dr[1] = row["PackageInvID"].ToString();
                        dr[2] = row["ItemInvID"].ToString();
                        dr[3] = row["Qty"].ToString();
                        dr[4] = row["Price"].ToString();
                        dr[5] = row["Action"].ToString();
                        AdjDt.Rows.Add(dr);
                        iSno = Convert.ToInt32(dr[0]);
                    }
                }
            }

            foreach (GridViewRow row in grdPIInventoryView.Rows)    //append current page data to datatable
            {
               
              
                string PInventoryID = txtPInvID.Text.ToString();
                Label PIInventoryID = (Label)row.FindControl("lblInventoryID");
                TextBox PIQty = (TextBox)row.FindControl("txtQty");
                Label PIPrice = (Label)row.FindControl("lblPrice");



                if ((PIQty.Text != string.Empty && PIQty.Text != "0"))
                {
                    iSno = iSno + 1;
                    sSno = Convert.ToString(iSno);

                    dr = AdjDt.NewRow();
                    dr[0] = sSno;
                    dr[1] = PInventoryID.ToString();
                    dr[2] = PIInventoryID.Text;
                    if (PIQty.Text == "")
                    {
                        dr[3] = 0;
                    }
                    else
                    {
                        dr[3] = PIQty.Text;
                    }
                    dr[4] = PIPrice.Text;
                    dr[5] = "";

                    AdjDt.Rows.Add(dr);
                }
            }

            Session["QtyPckTable"] = AdjDt;

            DataTable DT101 = new DataTable();
            DT101 = (DataTable)Session["QtyPckTable"];
            GrdInvPIList.DataSource = DT101;
            GrdInvPIList.DataBind();

            // LoadPIInventoryview(BranchAlias);

            #region   Clear the Gridview  Qty Textbox value  

            foreach (GridViewRow row in grdPIInventoryView.Rows)
            {
                TextBox txtqty = (TextBox)row.FindControl("txtQty");

                if (txtqty.Text !="")
                {
                    txtqty.Text = string.Empty;
                }
                
            }
            #endregion
           */

            // New Code added ..Karthik on 30-01-24

            if (txtPInvID.Text != "" && txtPBarcode.Text != "" && txtPInventoryName.Text!="")
            {

             ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "return CloseModal2();", true);
             foreach (GridViewRow row in grdPIInventoryView.Rows)
             {
               TextBox PIQty = (TextBox)row.FindControl("txtQty");
               if ((PIQty.Text != string.Empty && PIQty.Text != "0"))     // Qty Validation 
               {
                 string PInventoryID = txtPInvID.Text.ToString();
                 Label PIInventoryID = (Label)row.FindControl("lblInventoryID");
                 Label PIPrice = (Label)row.FindControl("lblPrice");
                 string PIUpdated = "0";
                 InsertPackageItems(BranchAlias, PInventoryID.Trim(), PIInventoryID.Text.Trim(), PIQty.Text.Trim(), PIPrice.Text.Trim(), PIUpdated.Trim());
                 Session["PInventoryID"] = PInventoryID.ToString().Trim();
               }

              }

                ShowPackagedItemsListUnderMaster(BranchAlias, Session["PInventoryID"].ToString());

                #region   Clear the Gridview  Qty Textbox value  

                foreach (GridViewRow row in grdPIInventoryView.Rows)
                {
                    TextBox txtqty = (TextBox)row.FindControl("txtQty");

                    if (txtqty.Text != "")
                    {
                        txtqty.Text = string.Empty;
                    }

                }
                #endregion


                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Info_msg", "alert('Inventory Package Items added successfully.')", true);

                #region  Show the Contend after Inventory Item Added and Refreshed the Page 

                // string _Current_Pinventoryid = Session["Current_PInventoryId"].ToString();
                #endregion

            }
            else
            {

                foreach (GridViewRow row in grdPIInventoryView.Rows)
                {
                    TextBox txtqty = (TextBox)row.FindControl("txtQty");

                    if (txtqty.Text != "")
                    {
                        txtqty.Text = string.Empty;
                    }

                }
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Info_msg", "alert('Select the Master Package before Add Items..')", true);
            }

        }

        public void ClearForms()
        {
            txtFinalPackagePrice.Text = "";
            txtPInvID.Text = "";
            txtPBarcode.Text = "";
            txtPInventoryName.Text = "";
            txtPDescription.Text = "";
            lblCurrentPackageAmount.Text = "";
            txtFinalPackagePrice.Text = "";
            GrdPackagedItems.DataSource = null;
            GrdPackagedItems.DataBind();

        }
        //nid added for showing Packaged items list under Package Master on 06-Mar-2023
        private void ShowPackagedItemsListUnderMaster(string sDB, string sPInvID)
        {
            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();
            }


            // SQL Injection Prevention : 07-10-21 
            // Parameterized Approach 
            string sCmd = "Select IP.PackageID as PackageID, IP.PackageInventoryID as PackageInventoryID, I.Barcode as Barcode, I.InventoryName As InventoryName, IP.Quantity as Quantity, IP.Price as Price " +
                " From {0}.InventoryPackage IP Left Outer Join {0}.Inventory I On IP.PackageInventoryID=I.InventoryID " +
                " where IP.InventoryID={1};";
            //string command = string.Format(sCmd, sDB, sPInvID);
            //DataTable Dt = new DataTable();
            //Dt = ObjMain.GetData_DT(command);

            DataTable Dt = new DataTable();
            string command = string.Format(sCmd, sDB, sPInvID);

            MySqlParameter[] parameters =
                  {
                     new MySqlParameter("@SearchText",sPInvID),

                    };
            GrdPackagedItems.DataSource = null;
            Dt = ObjMain.NewGetData_DT(command, parameters);
            GrdPackagedItems.DataSource = Dt;
            GrdPackagedItems.DataBind();
            //nid added for getting package price on 16-Mar-2023
            string PackageValue_Query = "Select PackageValue From {0}.Inventory Where InventoryID={1};";
            string command2 = string.Format(PackageValue_Query, BranchAlias, sPInvID);
            string PackageValue = ObjMain.ExecuteScalar(command2);
            //txtFinalPackagePrice.Text = PackageValue.ToString();
            txtFinalPackagePrice.Text = String.Format("{0:0.00}", Convert.ToDecimal(PackageValue));
            lblCurrentPackageAmount.Text= String.Format("{0:0.00}", Convert.ToDecimal(PackageValue));
        }
        //nid added for Package Item Insert on 06-Mar-2023

        // This step skipped ,storing data to temp table and instead save it directly to the table 
        // NOT IN USE : Karthik modified on 02-02-24 
        protected void btnAddPackageItem_Click(object sender, EventArgs e)
        {
            #region  Validation Between HQ Branch and Normal Branch 
            BranchFullName = cmbBranches.SelectedItem.Text;       // This will Return Branch FullName 
            if (BranchFullName == "HQ")
            {
                BranchAlias = Session["Branch_HQ"].ToString();
            }
            else
            {
                BranchFullName = cmbBranches.SelectedItem.Text;     // This will Return Branch FullName 
                Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);  // This will Return BranchName( Actual Database Name )
                BranchAlias = Cmb_BranchName;

            }
            #endregion



            foreach (GridViewRow row in grdPIInventoryView.Rows)    //append current page data to datatable
            {
               

                string PInventoryID = txtPInvID.Text.ToString();
                Label PIInventoryID = (Label)row.FindControl("lblInventoryID");
                TextBox PIQty = (TextBox)row.FindControl("txtQty");
                Label PIPrice = (Label)row.FindControl("lblPrice");



            }


           foreach (GridViewRow row in GrdInvPIList.Rows)
            {
                string PInventoryID = (row.Cells[1].FindControl("lblPackageInvID") as Label).Text;
                string PIInventoryID = (row.Cells[1].FindControl("lblItemInvID") as Label).Text;
                string PIQty = (row.Cells[1].FindControl("lblQty") as Label).Text;
                string PIPrice = (row.Cells[1].FindControl("lblPrice") as Label).Text; 
                string PIUpdated = "0";
                InsertPackageItems(BranchAlias, PInventoryID.Trim(), PIInventoryID.Trim(), PIQty.Trim(), PIPrice.Trim(), PIUpdated.Trim());
            }

            ShowPackagedItemsListUnderMaster(BranchAlias, txtPInvID.Text.Trim());
            
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Info_msg", "alert('Inventory Package Items added successfully.')", true);
            ShowPackagedItemsListUnderMaster(BranchAlias, txtPInvID.Text.Trim());



            #region  Show the Contend after Inventory Item Added and Refreshed the Page 

            string _Current_Pinventoryid = Session["Current_PInventoryId"].ToString();



            #endregion

        }
        private void InsertPackageItems(string sDB, string PInventoryID, string PIInventoryID, string PIQty, string PIPrice, string PIUpdated)
        {
            // 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>");

            //For deleting existing linked items with same inventory id
            string sCmdDel = "Delete from {0}.inventorypackage where PackageInventoryID ={1} ";
            string command = string.Format(sCmdDel, sDB, PIInventoryID);
            DeleteExistingPackageItem = ObjMain.ExecuteNonQuery(command);

            //for getting Running number
            string PackageID = ObjSel.GetMax_RunningNoInvPackage(BranchAlias);

            //for inserting records into InventoryPackage
            string sCmd = "Insert into {0}.inventorypackage(PackageID, InventoryID, PackageInventoryID, Quantity, Price, Updated)values(@PackageID,@PInventoryID,@PIInventoryID,@PIQty,@PIPrice,@PIUpdated)";
            string commandA = string.Format(sCmd, sDB);

            MySqlParameter[] parameters =
                   {
                     new MySqlParameter("@PackageID",PackageID),
                     new MySqlParameter("@PInventoryID",PInventoryID),
                     new MySqlParameter("@PIInventoryID",PIInventoryID),
                     new MySqlParameter("@PIQty",PIQty),
                     new MySqlParameter("@PIPrice",PIPrice),
                     new MySqlParameter("@PIUpdated",PIUpdated),
                    };
            InsertInventoryPackage = ObjMain.ExecuteQuery(commandA, parameters);

            // Update Running No for InventoryPackage
            string QueryUPT = "Update {0}.runningnumber Set RunningNo=" + PackageID + " Where ModuleName='InventoryPackage';";
            string commandM = string.Format(QueryUPT, BranchAlias);
            U = ObjMain.ExecuteNonQuery(commandM);

            //for clearing GrdInvPIList and Session
            GrdInvPIList.DataSource = null;
            GrdInvPIList.DataBind();
            AdjDt.Clear();
            Session["QtyPckTable"] = null;
        }

        protected void GrdPackagedItems_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {

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

            }
            #endregion


            //GridViewRow row = (GridViewRow)GrdPackagedItems.Rows[e.RowIndex];
            int PackageID = Convert.ToInt32(GrdPackagedItems.DataKeys[e.RowIndex].Value);
            //For deleting existing linked items 
            string sCmdDel = "Delete from {0}.inventorypackage Where PackageID= " + PackageID + ";  ";
            string command = string.Format(sCmdDel, BranchAlias, PackageID);
            DeletePackageItem = ObjMain.ExecuteNonQuery(command);
            //for Loading grid
            ShowPackagedItemsListUnderMaster(BranchAlias, txtPInvID.Text.Trim());


        }
        protected void GrdInvPIList_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {

            DataTable dt1 = (DataTable)Session["QtyPckTable"];
            // DataTable dt = new DataTable();
            if (dt1.Rows.Count > 0)
            {
                dt1.Rows[e.RowIndex].Delete();
                GrdInvPIList.DataSource = dt1;
                GrdInvPIList.DataBind();

            }
        }

        //nid added for Set Package Price on 16-Mar-2023
        protected void btnSetPackagePrice_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

            // Update Package Value for the Package Inventory Item
            string QueryUPT = "Update {0}.Inventory SET PackageType=@PackageType,PackageValue=@PackageValue,PackageDiscount=@PackageDiscount Where InventoryID=@InventoryID;";
            string Up_Command = string.Format(QueryUPT, BranchAlias);

            MySqlParameter[] parameters =
               {
                                 new MySqlParameter("@PackageType",2),
                                 new MySqlParameter("@PackageValue",txtFinalPackagePrice.Text),
                                 new MySqlParameter("@PackageDiscount",0),
                                 new MySqlParameter("@InventoryID",txtPInvID.Text),
                                };
            K = ObjMain.ExecuteQuery(Up_Command, parameters);
            txtFinalPackagePrice.Text = String.Format("{0:0.00}", Convert.ToDecimal(txtFinalPackagePrice.Text));
            lblCurrentPackageAmount.Text= String.Format("{0:0.00}", Convert.ToDecimal(txtFinalPackagePrice.Text));
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "Info_msg", "alert('Inventory Package Price saved successfully.')", true);
        }

        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 grdPIInventoryView_SelectedIndexChanged(object sender, EventArgs e)
        {
            //Accessing TemplateField Column controls.
            string PIInventoryID = (grdPIInventoryView.SelectedRow.FindControl("lblInventoryID") as Label).Text;

            FPckDt = (DataTable)Session["QtyPckTable"];        //session value assign to Final datatable for Submit


            if (AdjDt.Rows.Count == 0)
            {
                AdjDt.Columns.Add(new System.Data.DataColumn("SNo", typeof(String)));
                AdjDt.Columns.Add(new System.Data.DataColumn("PackageInvID", typeof(String)));
                AdjDt.Columns.Add(new System.Data.DataColumn("ItemInvID", typeof(String)));
                AdjDt.Columns.Add(new System.Data.DataColumn("Qty", typeof(String)));
                AdjDt.Columns.Add(new System.Data.DataColumn("Price", typeof(String)));
                AdjDt.Columns.Add(new System.Data.DataColumn("Action", typeof(String)));
            }

            DataRow dr;
            if (FPckDt != null)
            {
                if (FPckDt.Rows.Count > 0)
                {
                    foreach (DataRow row in FPckDt.Rows)    //load previous page session values to current datatable
                    {
                        dr = AdjDt.NewRow();
                        dr[0] = row["SNo"].ToString();
                        dr[1] = row["PackageInvID"].ToString();
                        dr[2] = row["ItemInvID"].ToString();
                        dr[3] = row["Qty"].ToString();
                        dr[4] = row["Price"].ToString();
                        dr[5] = row["Action"].ToString();
                        AdjDt.Rows.Add(dr);
                        iSno = Convert.ToInt32(dr[0]);
                    }
                }
            }

            //foreach (GridViewRow row in grdPIInventoryView.Rows)    //append current page data to datatable
            //{
            //    Label PInvID = (Label)row.FindControl("lblPackageInvID");
            //    Label IInvID = (Label)row.FindControl("lblItemInvID");
            //    TextBox Qty = (TextBox)row.FindControl("lblQty");
            //    Label Price = (Label)row.FindControl("lblPrice");

            //    string PInventoryID = txtPInvID.Text.ToString ();
            //    PIInventoryID = (grdPIInventoryView.SelectedRow.FindControl("lblInventoryID") as Label).Text;
            //    string PQty = "1";
            //    string PIPrice = "0";

            //    //if ((Qty.Text != string.Empty && Qty.Text != "0") )
            //    //{
            //    //    iSno = iSno + 1;
            //    //    sSno = Convert.ToString(iSno);

            //    //    dr = AdjDt.NewRow();
            //    //    dr[0] = sSno;
            //    //    dr[1] = PInventoryID;
            //    //    dr[2] = PIInventoryID;
            //    //    if (Qty.Text == "")
            //    //    {
            //    //        dr[3] = 1;
            //    //    }
            //    //    else
            //    //    {
            //    //        //dr[3] = Qty.Text;
            //    //        dr[3] = 1;
            //    //    }
            //    //    dr[4] = PIPrice;

            //    //    AdjDt.Rows.Add(dr);
            //    //}
            //    iSno = iSno + 1;
            //    sSno = Convert.ToString(iSno);

            //    dr = AdjDt.NewRow();
            //    dr[0] = sSno;
            //    dr[1] = PInventoryID;
            //    dr[2] = PIInventoryID;
            //    dr[3] = 1;
            //    dr[4] = PIPrice;

            //    AdjDt.Rows.Add(dr);
            //}

            string PInventoryID = txtPInvID.Text.ToString();
            PIInventoryID = (grdPIInventoryView.SelectedRow.FindControl("lblInventoryID") as Label).Text;
            //string PQty = "1";
            string PIPrice = (grdPIInventoryView.SelectedRow.FindControl("lblPrice") as Label).Text;
            iSno = iSno + 1;
            sSno = Convert.ToString(iSno);

            dr = AdjDt.NewRow();
            dr[0] = sSno;
            dr[1] = PInventoryID;
            dr[2] = PIInventoryID;
            dr[3] = 1;
            dr[4] = PIPrice;
            dr[5] = "";

            AdjDt.Rows.Add(dr);


            Session["QtyPckTable"] = AdjDt;

            DataTable DT101 = new DataTable();
            DT101 = (DataTable)Session["QtyPckTable"];
            GrdInvPIList.DataSource = DT101;
            GrdInvPIList.DataBind();




        }

        public void LoadPIInventoryview(string branch)
        {


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


            string InvenQuery = "select *,Round(UnitCost,3) as UCost,sum(pquantity-(CutQuantity+RetailQty))as OnHandICA,0 as Qty from {0}.inventory as I " +
                                " join {0}.inventorycategories  as c ON I.Categoryid=c.categoryid " +
                                " join {0}.inventorycostaverage ic on ic.inventoryid=i.inventoryid " +
                                " where  " + sActive + " " +
                                " group by i.inventoryid " +
                                " order by i.inventoryid;";


            string command = string.Format(InvenQuery, branch);
            DT = ObjMain.GetData_DT(command);
            grdPIInventoryView.DataSource = DT;
            grdPIInventoryView.DataBind();



        }
        protected void grdPIInventoryView_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {

            // XSS Attack Prevention     
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ShowModelPackageItemList();", true);
            if (cmbPISearch.SelectedIndex == 0)
            {


                if (cmbBranches.Visible == false)
                {
                    grdPIInventoryView.PageIndex = e.NewPageIndex;
                    LoadPIInventoryview(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

                    grdPIInventoryView.PageIndex = e.NewPageIndex;
                    LoadPIInventoryview(BranchAlias);




                }

            }

            else if (cmbPISearch.SelectedIndex == 1)
            {

                if (cmbBranches.Visible == false)
                {
                    grdPIInventoryView.PageIndex = e.NewPageIndex;
                    LoadPIInventoryview(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


                    grdPIInventoryView.PageIndex = e.NewPageIndex;
                    LoadPIInventoryview(BranchAlias);

                }



            }

            else if (cmbPISearch.SelectedIndex == 2)
            {

                if (cmbBranches.Visible == false)
                {
                    grdPIInventoryView.PageIndex = e.NewPageIndex;
                    LoadPIInventoryview(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




                    grdPIInventoryView.PageIndex = e.NewPageIndex;
                    LoadPIInventoryview(BranchAlias);

                }



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

                if (cmbBranches.Visible == false)
                {
                    grdPIInventoryView.PageIndex = e.NewPageIndex;
                    LoadPIInventoryview(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

                    grdPIInventoryView.PageIndex = e.NewPageIndex;
                    LoadPIInventoryview(BranchAlias);

                }



            }


            else if (cmbPISearch.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


                string sActivex = string.Empty;

                if (chkActiveonly.Checked == true)
                {
                    sActivex = " and I.active <> 0 ";
                }
                else
                {
                    sActivex = " 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 c.categoryname like CONCAT('%', @SearchVal, '%')   " + sActivex + "    group by I.inventoryid";

                string command = string.Format(Inv_Qry5, BranchAlias);
                MySqlParameter[] parameters =
                {
                 new MySqlParameter("@SearchVal",txtPISearchVal.Text.ToString().Trim()),
                };

                grdPIInventoryView.PageIndex = e.NewPageIndex;
                DT = ObjMain.NewGetData_DT(command, parameters);
                grdPIInventoryView.DataSource = DT;
                grdPIInventoryView.DataBind();


            }


            if (cmbPISearch.SelectedIndex == 5)
            {
                string group1Value = "group1";
                grdPIInventoryView.PageIndex = e.NewPageIndex;
                LoadGroupDetail(group1Value, txtPISearchVal.Text.ToString().Trim());


            }
            else if (cmbPISearch.SelectedIndex == 6)
            {
                string group2Value = "group2";
                grdPIInventoryView.PageIndex = e.NewPageIndex;
                LoadGroupDetail(group2Value, txtPISearchVal.Text.ToString().Trim());
            }
            else if (cmbPISearch.SelectedIndex == 7)
            {
                string group3Value = "group3";
                grdPIInventoryView.PageIndex = e.NewPageIndex;
                LoadGroupDetail(group3Value, txtPISearchVal.Text.ToString().Trim());
            }
            else if (cmbPISearch.SelectedIndex == 8)
            {
                string group4Value = "group4";
                grdPIInventoryView.PageIndex = e.NewPageIndex;
                LoadGroupDetail(group4Value, txtPISearchVal.Text.ToString().Trim());
            }
            else if (cmbPISearch.SelectedIndex == 9)
            {
                string group5Value = "group5";
                grdPIInventoryView.PageIndex = e.NewPageIndex;
                LoadGroupDetail(group5Value, txtPISearchVal.Text.ToString().Trim());
            }


            if (cmbPISearch.SelectedIndex == 10)
            {

                #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_Qry7 = "Select *,Round(UnitCost,3) as UCost,sum(pquantity-(CutQuantity+RetailQty))as OnHandICA from {0}.inventory as I " +
                                "  join {0}.inventorycategories  as c ON I.Categoryid=c.categoryid " +
                                "  join {0}.inventorycostaverage ic on ic.inventoryid=i.inventoryid where  I.Description like CONCAT('%',@SearchVal,'%')    " + sActive + " group by I.inventoryid  ";

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

                    };
                DT = ObjMain.NewGetData_DT(command, parameters);
                grdPIInventoryView.PageIndex = e.NewPageIndex;
                grdPIInventoryView.DataSource = DT;
                grdPIInventoryView.DataBind();
            }


        }

        


        protected void btnPISearch_Click(object sender, EventArgs e)
        {
            // XSS Attack Prevention 
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ShowModelPackageItemList();", 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 (cmbPISearch.SelectedIndex == 0)
            {
                grdPIInventoryView.DataSource =null ;
                grdPIInventoryView.DataBind();
            }

            else if (cmbPISearch.SelectedIndex == 1)
            {

                

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


                if (txtPISearchVal.Text != "")
                {
                    string Inv_Qry1 = " Select *,Round(UnitCost,3) as UCost,sum(pquantity-(CutQuantity+RetailQty))as OnHandICA,0 as Qty from {0}.inventory as I " +
                                                  " join {0}.inventorycategories  as c ON I.Categoryid=c.categoryid " +
                                                  " join {0}.inventorycostaverage ic on ic.inventoryid=i.inventoryid where   I.Inventoryid=@Inventoryid   " + sActive + "  ";

                    string command = string.Format(Inv_Qry1, BranchAlias);
                    MySqlParameter[] parameters =
                       {
                    new MySqlParameter("@Inventoryid",Microsoft.Security.Application.Encoder.HtmlEncode(txtPISearchVal.Text.ToString().Trim())),
                   };
                    DT = ObjMain.NewGetData_DT(command, parameters);
                    grdPIInventoryView.DataSource = DT;
                    grdPIInventoryView.DataBind();

                }

                  

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

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


                if (txtPISearchVal.Text != "")
                {
                    string Inv_Qry2 = "Select *,Round(UnitCost,3) as UCost,sum(pquantity-(CutQuantity+RetailQty))as OnHandICA from {0}.inventory as I " +
                                " join {0}.inventorycategories  as c ON I.Categoryid=c.categoryid " +
                                " join {0}.inventorycostaverage ic on ic.inventoryid=i.inventoryid where   I.barcode like CONCAT('%',@SearchVal,'%')   " + sActive + " Group by I.barcode ";

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

                    MySqlParameter[] parameters =
                       {
                    new MySqlParameter("@SearchVal",Microsoft.Security.Application.Encoder.HtmlEncode(txtPISearchVal.Text.ToString().Trim())),
                   };
                    DT = ObjMain.NewGetData_DT(command, parameters);

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

                }


            }

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



                if (txtPISearchVal.Text != "")
                {
                    string Inv_Qry3 = "Select *,Round(UnitCost,3) as UCost,sum(pquantity-(CutQuantity+RetailQty))as OnHandICA,0 as Qty from {0}.inventory as I " +
                                "  join {0}.inventorycategories  as c ON I.Categoryid=c.categoryid " +
                                "  join {0}.inventorycostaverage ic on ic.inventoryid=i.inventoryid where  I.InventoryName like  CONCAT('%',@SearchVal,'%') " + sActive + " group by I.inventoryid  ";

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


                    MySqlParameter[] parameters =
                        {
                     new MySqlParameter("@SearchVal",Microsoft.Security.Application.Encoder.HtmlEncode(txtPISearchVal.Text.ToString().Trim())),
                    };


                    DT = ObjMain.NewGetData_DT(command, parameters);
                    grdPIInventoryView.DataSource = DT;
                    grdPIInventoryView.DataBind();
                }
            }
            else if (cmbPISearch.SelectedIndex == 4)
            {
                if (chkActiveonly.Checked == true)
                {
                    sActive = " and I.active <> 0";
                }
                else
                {
                    sActive = " and I.active = 0";
                }


                if (txtPISearchVal.Text != "")
                {

                    string Inv_Qry5 = "Select *,Round(UnitCost,3) as UCost,sum(pquantity-(CutQuantity+RetailQty))as OnHandICA,0 as Qty from {0}.inventory as I " +
                                " join {0}.inventorycategories  as c ON I.Categoryid=c.categoryid " +
                                " join {0}.inventorycostaverage ic on ic.inventoryid=i.inventoryid where  c.categoryname like  CONCAT('%', @SearchVal ,'%')   " + sActive + "   group by I.inventoryid";
                    string command = string.Format(Inv_Qry5, BranchAlias);

                    MySqlParameter[] parameters =
                        {
                     new MySqlParameter("@SearchVal",Microsoft.Security.Application.Encoder.HtmlEncode(txtPISearchVal.Text.ToString().Trim())),
                    };
                    DT = ObjMain.NewGetData_DT(command, parameters);
                    grdPIInventoryView.DataSource = DT;
                    grdPIInventoryView.DataBind();
                }
            }


            if (cmbPISearch.SelectedIndex == 5)
            {
                if (txtPISearchVal.Text != "")
                {
                    string group1Value = "group1";
                    LoadGroupDetail(group1Value, Microsoft.Security.Application.Encoder.HtmlEncode(txtPISearchVal.Text.ToString().Trim()));
                }
            }
            else if (cmbPISearch.SelectedIndex == 6)
            {
                if (txtPISearchVal.Text != "")
                {
                    string group2Value = "group2";
                    LoadGroupDetail(group2Value, Microsoft.Security.Application.Encoder.HtmlEncode(txtPISearchVal.Text.ToString().Trim()));
                }
            }
            else if (cmbPISearch.SelectedIndex == 7)
            {
                if (txtPISearchVal.Text != "")
                {
                    string group3Value = "group3";
                    LoadGroupDetail(group3Value, Microsoft.Security.Application.Encoder.HtmlEncode(txtPISearchVal.Text.ToString().Trim()));
                }
            }

            else if (cmbPISearch.SelectedIndex == 8)
            {
                if (txtPISearchVal.Text != "")
                {
                    string group4Value = "group4";
                    LoadGroupDetail(group4Value, Microsoft.Security.Application.Encoder.HtmlEncode(txtPISearchVal.Text.ToString().Trim()));
                }
            }
            else if (cmbPISearch.SelectedIndex == 9)
            {
                if (txtPISearchVal.Text != "")
                {
                    string group5Value = "group5";
                    LoadGroupDetail(group5Value, Microsoft.Security.Application.Encoder.HtmlEncode(txtPISearchVal.Text.ToString().Trim()));
                }
            }


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


                if (txtPISearchVal.Text != "")
                {
                    string Inv_Qry7 = "Select *,Round(UnitCost,3) as UCost,sum(pquantity-(CutQuantity+RetailQty))as OnHandICA,0 as Qty from {0}.inventory as I " +
                                "  join {0}.inventorycategories  as c ON I.Categoryid=c.categoryid " +
                                "  join {0}.inventorycostaverage ic on ic.inventoryid=i.inventoryid where   I.Description like CONCAT('%',@SearchVal,'%')  " + sActive + " group by I.inventoryid  ";
                    string command = string.Format(Inv_Qry7, BranchAlias);
                    MySqlParameter[] parameters =
                       {
                     new MySqlParameter("@SearchVal",Microsoft.Security.Application.Encoder.HtmlEncode(txtPISearchVal.Text.ToString().Trim())),
                    };
                    DT = ObjMain.NewGetData_DT(command, parameters);
                    grdPIInventoryView.DataSource = DT;
                    grdPIInventoryView.DataBind();
                }
            }


        }

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





        //nids Pakage Module Ends here, Please do not add other codes in this region
        #endregion

        protected void btnSearchClear_Click(object sender, EventArgs e)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ShowModelPackageItemList();", true);

            cmbPISearch.SelectedIndex = 0;
            txtPISearchVal.Text = "";
            grdPIInventoryView.DataSource = null;
            grdPIInventoryView.DataBind();


            

        }

        protected void btnPackageSearchClear_Click(object sender, EventArgs e)
        {

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

            grdInventory.DataSource = null;
            grdInventory.DataBind();
            txtSearchVal.Text = "";
            cmbSearch.SelectedIndex= 0;
            grdPIInventoryView.DataSource = null;
            grdPIInventoryView.DataBind();
            txtPInvID.Text = "";
            txtPBarcode.Text = "";
            txtPInventoryName.Text = "";
            txtPDescription.Text = "";
            lblCurrentPackageAmount.Text = "";
            txtFinalPackagePrice.Text = "";

            GrdPackagedItems.DataSource = null;
            GrdPackagedItems.DataBind();




        }
    }
    
}