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

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

        string Curr_DateOnly = System.DateTime.Now.ToString("yyyy-MM-dd");
        DateTime MonthstartDt;
        DataSet ds = new DataSet();
        MYSQLDB ObjMain = new MYSQLDB();
        DataTable DT = new DataTable();
        DataTable Dt2 = new DataTable();
        DataTable DtLicense = new DataTable();
        DataTable DtSuperAdmin = new DataTable();
        DataTable DtMultiBranch = new DataTable();
        DataTable DtNormalUser = new DataTable();
        DataTable DTProductSale = new DataTable();
        MySqlCommand Cmdv = new MySqlCommand();
        // User Variables 
        string UserId = string.Empty;
        string UserName = string.Empty;
        string PortalTypeId = string.Empty;
        string cd_Id = string.Empty;
        string Datapath = string.Empty;
        string cd_BranchAlias = string.Empty;
        string IsMultiBranch = string.Empty;
        string IsSuperAdmin = string.Empty;
        string ActiveCallvalue = string.Empty;
        // License Variables ..

        string Curr_BranchFullName = string.Empty;



        string ISHQ = string.Empty;
        string InAdjId = string.Empty;

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

        string ChkAdjTal = string.Empty;
        //added by MANJU U
        DataTable DtInventoryList = new DataTable();
        DataTable DtCategoryList = new DataTable();
        DataSet DS = new DataSet();
        
        string Vw_Chk = string.Empty;

        string PID = string.Empty;
        string Page_Acess = string.Empty;
        string Read_Acess = string.Empty;
        string Write_Acess = string.Empty;
        string Isdowld_Acess = string.Empty;
        string Rcd_id = string.Empty;
        string RPortalid = string.Empty;
        string Useridvalue = string.Empty;
        string QueryCurr_Select = string.Empty;
        string L_MaxUserCnt = string.Empty;
       
        string L_StockCollector = string.Empty;
        string Branchidval = string.Empty;
        string BranchFullName = string.Empty;

        string Cmb_BranchName = string.Empty;

        string HQ = string.Empty;
        string Cm_id = string.Empty;
        string JSno = string.Empty;
        string JInvenID = string.Empty;
        string BranchAlias = string.Empty;
        // Variables : 19-12-19

        string StockChkNo = string.Empty;

        string StockChkNoNew = string.Empty;
        string BranchPrefix = string.Empty;
        DataTable DtStchkMaster = new DataTable();
        DataTable DtStchkDetail = new DataTable();
        DataTable DtStchkDetailExist = new DataTable();
        string RInventoryId = string.Empty;
        string Unitcost = string.Empty;
        string sStockChkID = string.Empty;

        // ReInsert : Variables 
        string TBarcode = string.Empty;
        string TStockCheckId = string.Empty;
        string TStockCheckDetailId = string.Empty;
        string TStockCheckNO = string.Empty;
        string TInventoryid = string.Empty;
        string TOldQty = string.Empty;
        string TCheckQty = string.Empty;
        string TUnitCost = string.Empty;
        string TChkUnitCost = string.Empty;
        DataTable DJ1 = new DataTable();
        DataTable DJ2 = new DataTable();
        DataTable DtTempStchkDetail = new DataTable();
        Int32 IUpdateSTCVoid;
        Int32 IDeleteSTCItem;
        string RBranchid = string.Empty;
        string Branchid = string.Empty;
        // Added On 02-12-2021
        string ReadHQ = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Session["UserName"] == null)
            {
                Response.Redirect("Login.aspx");
            }

            if (!IsPostBack)
            {
                txtStartDt.Text = DateTime.Now.ToString("yyyy-MM-dd");
                txtEndDt.Text = DateTime.Now.ToString("yyyy-MM-dd");
                txtSTCNo.Enabled = false;
                txtSTCID.Enabled = false;
                txtSTCID.CssClass = "form-control";
                txtSTCNo.CssClass = "form-control";
            }

            if (lblStockCheckNo.Text != "" || txtSTCNo.Text != "")
            {
                btnCheckListSave.Enabled = true;
                btnVoid.Enabled = true;
                btnConfirm.Enabled = true;

            }
            else
            {
                btnCheckListSave.Enabled = false;
                btnVoid.Enabled = false;
                btnConfirm.Enabled = false;

            }



            PID = "22";    // This is for STOCKCOLLECTOR  PageAccess

            if (((Convert.ToBoolean(Session["IsSuperAdmin"])) == true) && (Session["PortalTypeId"].ToString() == "") && ((Convert.ToBoolean(Session["IsMultiBranch"])) == true))
            {
                if (!IsPostBack)
                {
                    LoadBranchesOnID();
                    // LoadBranchName4SuperAdmin();
                    string QueryCal = "select ActiveValue from portaldb.usermaster  where Userid=" + Session["UserId"].ToString() + " ";
                    ActiveCallvalue = ObjMain.ExecuteScalar(QueryCal);
                    if (ActiveCallvalue != " " || ActiveCallvalue != "Select Branch")
                    {
                        ActiveCall();

                        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;
                        loadChecklist(BranchAlias, Microsoft.Security.Application.Encoder.HtmlEncode(txtStartDt.Text), Microsoft.Security.Application.Encoder.HtmlEncode(txtEndDt.Text));

                    }

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


                    ActiveCall();

                    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;
                    loadChecklist(BranchAlias, Microsoft.Security.Application.Encoder.HtmlEncode(txtStartDt.Text), Microsoft.Security.Application.Encoder.HtmlEncode(txtEndDt.Text));


                }



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

                    ActiveCall();

                    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;
                    loadChecklist(BranchAlias, txtStartDt.Text, txtEndDt.Text);


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

                    }
                }
            }
            else if (((Session["PortalTypeId"].ToString() != "") || (Convert.ToBoolean(Session["IsSuperAdmin"])) == false) && ((Convert.ToBoolean(Session["IsMultiBranch"])) == false))
            {
                cmbBranches.Enabled = false;
                cmbBranches.Visible = false;

                Cm_id = ObjSel.GETcmid(Session["Cd_Id"].ToString());  // Get cm_id
                HQ = ObjSel.Get_HQ(Cm_id);     // Get the HQ Value
                Curr_BranchFullName = ObjSel.GetBranchFullName(HQ, Session["Branch_HQ"].ToString());
                lblBranchAliasName.ForeColor = System.Drawing.Color.DodgerBlue;
                lblBranchAliasName.Text = "&nbsp;" + "-" + "&nbsp;" + Curr_BranchFullName + "&nbsp; ";

                cd_BranchAlias = Session["Branch_HQ"].ToString();
                Datapath = Session["DataPath"].ToString();
                PortalTypeId = Session["PortalTypeId"].ToString();

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

                    Session["Page_Acess"] = Page_Acess;
                    Session["Read_Acess"] = Read_Acess;
                    Session["Write_Acess"] = Write_Acess;
                    Session["Isdowld_Acess"] = Isdowld_Acess;
                }
                if ((Session["L_StockCollector"].ToString() == "N") || (Session["Page_Acess"].ToString() == "N"))
                {
                    Response.Redirect("DeniedPage.aspx");
                }
                else
                {

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

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

                        }

                        if (Session["Write_Acess"].ToString() == "N")
                        {
                            btnAddToCheckList.Enabled = false;
                            btnCheckListSave.Enabled = false;
                            btnClearSess.Enabled = false;
                            btnConfirm.Enabled = false;
                            btnVoid.Enabled = false;
                            BranchAlias = Session["Branch_HQ"].ToString();

                        }
                        else
                        {

                            btnAddToCheckList.Enabled = true;
                            btnCheckListSave.Enabled = true;
                            btnClearSess.Enabled = true;
                            btnConfirm.Enabled = true;
                            btnVoid.Enabled = true;
                            BranchAlias = Session["Branch_HQ"].ToString();

                        }


                        if (cmbBranches.Visible == false)
                        {
                            BranchAlias = Session["Branch_HQ"].ToString();

                            loadChecklist(BranchAlias, txtStartDt.Text, txtEndDt.Text);

                            if (lblStockCheckNo.Text != "" || txtSTCNo.Text != "")
                            {
                                btnCheckListSave.Enabled = true;
                                btnVoid.Enabled = true;
                                btnConfirm.Enabled = true;

                            }
                            else
                            {
                                btnCheckListSave.Enabled = false;
                                btnVoid.Enabled = false;
                                btnConfirm.Enabled = false;

                            }

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

                                loadChecklist(BranchAlias, Microsoft.Security.Application.Encoder.HtmlEncode(txtStartDt.Text), Microsoft.Security.Application.Encoder.HtmlEncode(txtEndDt.Text));
                                DT = (DataTable)Session["DtStchkDetail"];
                                grdStockCheck.DataSource = DT;
                                grdStockCheck.DataBind();

                            }

                        }




                    }

                }

            }
            else
            {

            }


        }

        protected void cmbBranches_SelectedIndexChanged(object sender, EventArgs e)
        {
            // XSS Attack Prevention 

            if (cmbBranches.SelectedIndex == 0)
            {
                Response.Write("InventoryStockCollector.aspx");
            }
            else
            {
                if (Branchidval != "")
                {
                    DT = ObjUserBL.GetPageRightsDetailsPIDNew(Session["UserId"].ToString(), PID, Branchidval);
                }
                else
                {
                    DT = ObjUserBL.GetPageRightsDetailsPIDNew(Session["UserId"].ToString(), PID, Session["Fistbranch"].ToString());

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

                if (cmbBranches.SelectedIndex == 1)
                {

                    BranchFullName = Microsoft.Security.Application.Encoder.HtmlEncode(cmbBranches.SelectedItem.Text);    // This will Return Branch FullName 
                    Cmb_BranchName = ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), BranchFullName);
                    UPDATEBRANCH(Cmb_BranchName);
                }
                else
                {

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



                if (DtLicense.Rows.Count > 0)
                {


                    L_StockCollector = DtLicense.Rows[0]["STOCKCOLLECTOR"].ToString();
                    // Create Session for License Variables 
                    Session["L_StockCollector"] = L_StockCollector;
                }

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

                    UPDATEBRANCH(BranchAlias);
                    if (cmbBranches.SelectedIndex == 1)
                    {

                        BranchAlias = Cmb_BranchName;

                    }
                    else
                    {
                        if (cmbBranches.SelectedItem.Text == "HQ")
                        {
                            BranchAlias = Cmb_BranchName;
                        }
                        else
                        {
                            Response.Redirect("DeniedPage.aspx");
                        }
                            
                    }


                }
                else if (Session["Write_Acess"].ToString() == "N")
                {
                    Response.Redirect("DeniedPage.aspx");
                }

                else
                {
                    // btnExcel.Enabled = true;
                    BranchAlias = Cmb_BranchName;

                }
            }
            UPDATEBRANCH(BranchAlias);
        }

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

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

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

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


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


                    }


                }


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

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

        }


        public void LoadBranchName4SuperAdmin()
        {
            //DtSuperAdmin = ObjUserBL.GetBranchOnSuperAdmin(Session["Branch_HQ"].ToString(), Session["UserId"].ToString());
            DtNormalUser = ObjUserBL.GetBranchOnSuperAdminWithHQ8(Session["Branch_HQ"].ToString(), Session["CM_ID"].ToString());
            if (DtNormalUser.Rows.Count > 0)
            {
                cmbBranches.DataSource = DtNormalUser;
                cmbBranches.DataTextField = "branchfullname";
                cmbBranches.DataValueField = "Branchid";
                cmbBranches.DataBind();
                cmbBranches.Items.Insert(0, "Select Branch");
            }
        }
        public void ActiveCall()
        {
            string QueryCal = "select ActiveValue from portaldb.usermaster  where Userid=" + Session["UserId"].ToString() + " ";
            ActiveCallvalue = ObjMain.ExecuteScalar(QueryCal);
            if (ActiveCallvalue == "")
            {
                

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

                }
                else if (_Is_HQ_Enabled == "0")
                {
                    ActiveCallvalue = ObjSel.GetFirstBranch(Session["Branch_HQ"].ToString());
                }

                #endregion


            }

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

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

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

            }

            #endregion

            DT = ObjUserBL.GetPageRightsDetailsPIDNew(Session["UserId"].ToString(), PID, Branchidval);
            if (DT.Rows.Count > 0)
            {
                Page_Acess = DT.Rows[0]["Acess_status"].ToString();
                Read_Acess = DT.Rows[0]["Read_Access"].ToString();
                Write_Acess = DT.Rows[0]["Write_Access"].ToString();
                Isdowld_Acess = DT.Rows[0]["IDwld_Access"].ToString();

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

                L_StockCollector = DtLicense.Rows[0]["STOCKCOLLECTOR"].ToString();

                Session["L_StockCollector"] = L_StockCollector;

            }
            if ((Session["L_StockCollector"] == null) || Session["L_StockCollector"].ToString() == "N" || Session["Page_Acess"].ToString() == "N")
            {
                if (cmbBranches.SelectedItem.Text == "HQ")
                {

                    if (Session["DtStchkDetail"] != null)
                    {
                        btnSave.Enabled = true;
                        BranchAlias = cd_BranchAlias;
                        loadChecklist(BranchAlias, txtStartDt.Text, txtEndDt.Text);
                        DT = (DataTable)Session["DtStchkDetail"];
                        grdStockCheck.DataSource = DT;
                        grdStockCheck.DataBind();


                    }

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


                
            }
            else
            {

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

                }
                else
                {
                    if (Session["DtStchkDetail"] != null)
                    {
                        btnSave.Enabled = true;
                        BranchAlias = Cmb_BranchName;
                        loadChecklist(BranchAlias, txtStartDt.Text, txtEndDt.Text);
                        DT = (DataTable)Session["DtStchkDetail"];
                        grdStockCheck.DataSource = DT;
                        grdStockCheck.DataBind();


                    }




                }




            }

        }
        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 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 btnSearch_Click(object sender, EventArgs e)
        {

            //UPC-A: 0088300106516
            //EAN-13: 8906065540074
            //if 
            txtDesc.Text = "Dunhill Blue Lights 20 Hp";
            txtOnHand.Text = "10.6";

        }

        protected void btnAddToCheckList_Click(object sender, EventArgs e)
        {

            if (cmbBranches.Visible == false)
            {
                BranchAlias = Session["Branch_HQ"].ToString();
                Temp_CheckListItems();
                Temp_StkMasterRecord();

            }
            else 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
                Temp_CheckListItems();
                Temp_StkMasterRecord();
                btnConfirm.Enabled = false;

            }




            if (lblStockCheckNo.Text != "" || txtSTCNo.Text != "")
            {
                btnCheckListSave.Enabled = true;
                btnVoid.Enabled = true;
                //  btnConfirm.Enabled = true;

            }
            else
            {
                btnCheckListSave.Enabled = false;
                btnVoid.Enabled = false;
                btnConfirm.Enabled = false;

            }







        }

        /// <summary>
        ///  This Function If The StockCheckno Exists 
        /// </summary>
        public void Temp_CheckListItems_Exists()
        {
            // XSS Attack Prevention 
            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;



            // StockCheckNo ( Like BR1C00001)

            TStockCheckId = Microsoft.Security.Application.Encoder.HtmlEncode(txtSTCID.Text.Trim());
            TStockCheckNO = Microsoft.Security.Application.Encoder.HtmlEncode(txtSTCNo.Text.Trim());

            // Adding Items TO Temporary DataTable -  Details 

            DataTable RDt_Exist = new DataTable();

            RDt_Exist = (DataTable)Session["DtStchkDetailExist"];

            string queryA = "Select B.InventoryID,A.StockCheckDetailId,B.Barcode,B.InventoryName,oldqty as oldqty,CheckedQTY as CheckedQty ,sum(oldqty-CheckedQTY) as Diffs  from {0}.stockcheckDetail A " +
                                   " join {0}.Inventory B on A.InventoryID = B.InventoryID " +
                                   " join {0}.InventoryCostAverage C on C.InventoryID = B.InventoryID " +
                                   " where stockcheckid = stockcheckid " +
                                   " group by C.InventoryID;";


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

            MySqlParameter[] parameters =
                    {

                     new MySqlParameter("@stockcheckid",TStockCheckId),
                     };
            DJ1 = ObjMain.NewGetData_DT(command, parameters);


            if (RDt_Exist != null)
            {
                DtStchkDetailExist = (DataTable)Session["DtStchkDetailExist"];
                if (DtStchkDetailExist.Rows.Count > 0)
                {
                    DataRow Dr = DtStchkDetailExist.NewRow();
                    string QRC1 = "SELECT Inventoryid from {0}.Inventory where Barcode=@Barcode ";
                    string Command1 = string.Format(QRC1, BranchAlias);

                    MySqlParameter[] parameters1 =
                    {
                     new MySqlParameter("@Barcode",Microsoft.Security.Application.Encoder.HtmlEncode(txtBarcodesearch.Text.Trim())),
                     
                    };
                    TInventoryid = ObjMain.NewExecuteScalar(Command1, parameters1);
                    Dr["InventoryId"] = TInventoryid;
                    Dr["StockCheckDetailId"] = 0;
                    Dr["Barcode"] = Microsoft.Security.Application.Encoder.HtmlEncode(txtBarcodesearch.Text);
                    Dr["InventoryName"] = Microsoft.Security.Application.Encoder.HtmlEncode(txtDesc.Text);
                    Dr["OldQty"] = Microsoft.Security.Application.Encoder.HtmlEncode(txtOnHand.Text);
                    Dr["CheckedQty"] = Microsoft.Security.Application.Encoder.HtmlEncode(txtCheckqty.Text);
                    Dr["Diffs"] = Convert.ToInt32(Microsoft.Security.Application.Encoder.HtmlEncode(txtOnHand.Text)) - Convert.ToInt32(Microsoft.Security.Application.Encoder.HtmlEncode(txtCheckqty.Text));
                    DtStchkDetailExist.Rows.Add(Dr);

                    Session["DtStchkDetailExist"] = DtStchkDetailExist;
                    // Merging Two DataTables 
                    //DJ1.Merge(DtStchkDetailExist);

                    DtStchkDetailExist.Merge(DJ1, true, MissingSchemaAction.Ignore);
                    DtStchkDetailExist.AcceptChanges();
                    // Load Grids
                    grdStockCheck.DataSource = DtStchkDetailExist;
                    grdStockCheck.DataBind();
                    ClearFunc();

                }
                else
                {
                    string QRC1 = "SELECT Inventoryid from {0}.Inventory where Barcode=@Barcode ";
                    string Command1 = string.Format(QRC1, BranchAlias);

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

                    };
                    TInventoryid = ObjMain.NewExecuteScalar(Command1, parameters1);


                    DtStchkDetailExist.Columns.Add("InventoryId", typeof(Int32));
                    DtStchkDetailExist.Columns.Add("StockCheckDetailId", typeof(Int32));
                    DtStchkDetailExist.Columns.Add("Barcode", typeof(string));
                    DtStchkDetailExist.Columns.Add("InventoryName", typeof(string));
                    DtStchkDetailExist.Columns.Add("OldQty", typeof(decimal));
                    DtStchkDetailExist.Columns.Add("CheckedQty", typeof(decimal));
                    DtStchkDetailExist.Columns.Add("Diffs", typeof(int));

                    DataRow Dr = DtStchkDetailExist.NewRow();
                    Dr["InventoryId"] = RInventoryId;
                    Dr["StockCheckDetailId"] = 0;
                    Dr["Barcode"] = Microsoft.Security.Application.Encoder.HtmlEncode(txtBarcodesearch.Text);
                    Dr["InventoryName"] = Microsoft.Security.Application.Encoder.HtmlEncode(txtDesc.Text);
                    Dr["OldQty"] = Microsoft.Security.Application.Encoder.HtmlEncode(txtOnHand.Text);
                    Dr["CheckedQty"] = Microsoft.Security.Application.Encoder.HtmlEncode(txtCheckqty.Text);
                    Dr["Diffs"] = Convert.ToDecimal(Microsoft.Security.Application.Encoder.HtmlEncode(txtOnHand.Text)) - Convert.ToDecimal(Microsoft.Security.Application.Encoder.HtmlEncode(txtCheckqty.Text));
                    DtStchkDetailExist.Rows.Add(Dr);
                    Session["DtStchkDetailExist"] = DtStchkDetailExist;
                    // Merging Two DataTables 
                    //DJ1.Merge(DtStchkDetailExist);
                    DtStchkDetailExist.Merge(DJ1, true, MissingSchemaAction.Ignore);
                    DtStchkDetailExist.AcceptChanges();
                    // Load The Grid 
                    grdStockCheck.DataSource = DtStchkDetailExist;
                    grdStockCheck.DataBind();
                    ClearFunc();

                }
            }
            else
            {
                // Existing Code 
                //  RInventoryId = ObjMain.ExecuteScalar("SELECT Inventoryid from " + BranchAlias + ".Inventory where Barcode='" + Microsoft.Security.Application.Encoder.HtmlEncode(txtBarcodesearch.Text.Trim()) + " '");

                string QueryB = "SELECT Inventoryid from {0}.Inventory where Barcode=@Barcode ";
                string command1 = string.Format(QueryB, BranchAlias);

                MySqlParameter[] parameters1 =
                  {
                     new MySqlParameter("@Barcode",Microsoft.Security.Application.Encoder.HtmlEncode(txtBarcodesearch.Text.Trim())),
                  };

                RInventoryId = ObjMain.NewExecuteScalar(command1, parameters1);


                DtStchkDetailExist.Columns.Add("InventoryId", typeof(Int32));
                DtStchkDetailExist.Columns.Add("StockCheckDetailId", typeof(Int32));
                DtStchkDetailExist.Columns.Add("Barcode", typeof(string));
                DtStchkDetailExist.Columns.Add("InventoryName", typeof(string));
                DtStchkDetailExist.Columns.Add("OldQty", typeof(decimal));
                DtStchkDetailExist.Columns.Add("CheckedQty", typeof(decimal));
                DtStchkDetailExist.Columns.Add("Diffs", typeof(int));

                DataRow Dr = DtStchkDetailExist.NewRow();
                Dr["InventoryId"] = RInventoryId;
                Dr["StockCheckDetailId"] = 0;
                Dr["Barcode"] = Microsoft.Security.Application.Encoder.HtmlEncode(txtBarcodesearch.Text);
                Dr["InventoryName"] = Microsoft.Security.Application.Encoder.HtmlEncode(txtDesc.Text);
                Dr["OldQty"] = Microsoft.Security.Application.Encoder.HtmlEncode(txtOnHand.Text);
                Dr["CheckedQty"] = Microsoft.Security.Application.Encoder.HtmlEncode(txtCheckqty.Text);
                Dr["Diffs"] = Convert.ToInt32(Microsoft.Security.Application.Encoder.HtmlEncode(txtOnHand.Text)) - Convert.ToInt32(Microsoft.Security.Application.Encoder.HtmlEncode(txtCheckqty.Text));
                DtStchkDetailExist.Rows.Add(Dr);
                Session["DtStchkDetailExist"] = DtStchkDetailExist;
                // Merging 
                // DJ1.Merge(DtStchkDetailExist);
                DtStchkDetailExist.Merge(DJ1, true, MissingSchemaAction.Ignore);
                DtStchkDetailExist.AcceptChanges();
                // Load The Grid 
                grdStockCheck.DataSource = DtStchkDetailExist;
                grdStockCheck.DataBind();
                ClearFunc();

            }


        }

        /// <summary>
        ///   Function For CheckList items
        /// </summary>
        public void Temp_CheckListItems()
        {
            // XSS Attack Prevention 

            //John Modify 2019-Dec-23 ***************************//
            if (grdStockCheck.Rows.Count == 0)
            {
                Session["DtStchkDetail"] = null;
                LoadNewStockList();
            }
            else
            {
                StoreGVDatatoDT(); //John added on 2019-Dec-24
                DtStchkDetail.Columns.Add("StockCheckDetailId", typeof(Int32));
                DtStchkDetail.Columns.Add("Barcode", typeof(string));
                DtStchkDetail.Columns.Add("InventoryName", typeof(string));

                // Prevents SQL Injection
                // Parameterized Approach 

                //RInventoryId = ObjMain.ExecuteScalar("SELECT Inventoryid from " + BranchAlias + ".Inventory where Barcode='" + Microsoft.Security.Application.Encoder.HtmlEncode(txtBarcodesearch.Text) + " '");
                string QueryC = "SELECT Inventoryid from {0}.Inventory where Barcode=@Barcode ";
                string command = string.Format(QueryC, BranchAlias);

                MySqlParameter[] parameters3 =
                  {
                     new MySqlParameter("@Barcode", Microsoft.Security.Application.Encoder.HtmlEncode(txtBarcodesearch.Text)),
                  };

                RInventoryId = ObjMain.NewExecuteScalar(command, parameters3);


                DtStchkDetail.Columns.Add("InventoryId", typeof(Int32));
                DtStchkDetail.Columns.Add("OldQty", typeof(decimal));
                DtStchkDetail.Columns.Add("CheckedQty", typeof(decimal));
                DtStchkDetail.Columns.Add("Diffs", typeof(decimal));

                DataTable RDt = new DataTable();
                RDt = (DataTable)Session["DtStchkDetail"];
                DataRow Dr = RDt.NewRow();
                Dr["StockCheckDetailId"] = 0;
                Dr["Barcode"] = txtBarcodesearch.Text;
                Dr["InventoryName"] = txtDesc.Text;
                // RInventoryId = ObjMain.ExecuteScalar("SELECT Inventoryid from " + BranchAlias + ".Inventory where Barcode='" + Microsoft.Security.Application.Encoder.HtmlEncode(txtBarcodesearch.Text) + " '");
                string QueryD = "SELECT Inventoryid from {0}.Inventory where Barcode=@Barcode ";
                string command4 = string.Format(QueryD, BranchAlias);

                MySqlParameter[] parameters4 =
                  {
                     new MySqlParameter("@Barcode", Microsoft.Security.Application.Encoder.HtmlEncode(txtBarcodesearch.Text)),
                  };

                RInventoryId = ObjMain.NewExecuteScalar(command4, parameters4);


                Dr["InventoryId"] = RInventoryId;
                Dr["OldQty"] = txtOnHand.Text;
                Dr["CheckedQty"] = txtCheckqty.Text;

                // Dr["Diffs"] = (Math.Abs(Convert.ToDecimal(txtOnHand.Text))) - (Math.Abs(Convert.ToDecimal(txtCheckqty.Text)));  Existing Code 
                if (Convert.ToInt32(txtOnHand.Text) > 0)
                {
                    Dr["Diffs"] = (Convert.ToDecimal(Microsoft.Security.Application.Encoder.HtmlEncode(txtOnHand.Text))) + (Convert.ToDecimal(Microsoft.Security.Application.Encoder.HtmlEncode(txtCheckqty.Text)));
                }
                else
                {

                    Dr["Diffs"] = (Convert.ToDecimal(Microsoft.Security.Application.Encoder.HtmlEncode(txtOnHand.Text))) + (Convert.ToDecimal(Microsoft.Security.Application.Encoder.HtmlEncode(txtCheckqty.Text)));
                }




                RDt.Rows.Add(Dr);
                Session["DtStchkDetail"] = RDt;

                ClearFunc();
                grdStockCheck.DataSource = RDt;
                grdStockCheck.DataBind();

                btnConfirm.Enabled = false;

            }
            //***************************//


            if (txtSTCID.Text != "" || txtSTCNo.Text != "")
            {
                btnCheckListSave.Enabled = true;
                btnVoid.Enabled = true;
                btnConfirm.Enabled = true;



            }
            else
            {
                btnCheckListSave.Enabled = false;
                btnVoid.Enabled = false;
                btnConfirm.Enabled = false;

            }



        }


        public void LoadNewStockList()
        {
            // XSS Attack Prevention 

            if (cmbBranches.Visible == false)
            {
                BranchAlias = Session["Branch_HQ"].ToString();

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


            // StockCheckNo ( Like BR1C00001)
            StockChkNo = ObjSel.GetMaxSTCID(BranchAlias);
            StockChkNoNew = String.Format("{0:D5}", int.Parse(StockChkNo));
            // BranchPrefix 
            BranchPrefix = ObjSel.GetBranchPrefix(BranchAlias);
            string StkNo = string.Empty;
            StkNo = BranchPrefix + "C" + StockChkNoNew;
            lblStockCheckNo.Text = StkNo;

            // Adding Items TO Temporary DataTable -  Details 

            DataTable RDt = new DataTable();

            RDt = (DataTable)Session["DtStchkDetail"];


            if (RDt != null)
            {
                DtStchkDetail = (DataTable)Session["DtStchkDetail"];
                if (DtStchkDetail.Rows.Count > 0)
                {
                    DataRow Dr = DtStchkDetail.NewRow();
                    Dr["StockCheckDetailId"] = 0;
                    Dr["Barcode"] = Microsoft.Security.Application.Encoder.HtmlEncode(txtBarcodesearch.Text);
                    Dr["InventoryName"] = Microsoft.Security.Application.Encoder.HtmlEncode(txtDesc.Text);

                    // Existing Code 
                    // RInventoryId = ObjMain.ExecuteScalar("SELECT Inventoryid from " + BranchAlias + ".Inventory where Barcode='" + Microsoft.Security.Application.Encoder.HtmlEncode(txtBarcodesearch.Text )+ " '");
                    string QueryC = "SELECT Inventoryid from {0}.Inventory where Barcode=@Barcode ";
                    string command = string.Format(QueryC, BranchAlias);

                    MySqlParameter[] parameters3 =
                      {
                     new MySqlParameter("@Barcode", Microsoft.Security.Application.Encoder.HtmlEncode(txtBarcodesearch.Text)),
                     };

                    RInventoryId = ObjMain.NewExecuteScalar(command, parameters3);

                    Dr["InventoryId"] = RInventoryId;
                    Dr["OldQty"] = Microsoft.Security.Application.Encoder.HtmlEncode(txtOnHand.Text);
                    Dr["CheckedQty"] = Microsoft.Security.Application.Encoder.HtmlEncode(txtCheckqty.Text);
                    //Dr["Diffs"] = (Math.Abs(Convert.ToDecimal(txtOnHand.Text))) - (Math.Abs(Convert.ToDecimal(txtCheckqty.Text)));

                    if (Convert.ToInt32(txtOnHand.Text) > 0)
                    {
                        Dr["Diffs"] = (Convert.ToDecimal(Microsoft.Security.Application.Encoder.HtmlEncode(txtOnHand.Text))) + (Convert.ToDecimal(Microsoft.Security.Application.Encoder.HtmlEncode(txtCheckqty.Text)));
                    }
                    else
                    {

                        Dr["Diffs"] = (Convert.ToDecimal(Microsoft.Security.Application.Encoder.HtmlEncode(txtOnHand.Text))) + (Convert.ToDecimal(Microsoft.Security.Application.Encoder.HtmlEncode(txtCheckqty.Text)));
                    }

                    DtStchkDetail.Rows.Add(Dr);

                    Session["DtStchkDetail"] = DtStchkDetail;
                    grdStockCheck.DataSource = DtStchkDetail;
                    grdStockCheck.DataBind();
                    ClearFunc();
                    btnConfirm.Enabled = false;
                    btnVoid.Enabled = false;
                }
                else
                {

                    DtStchkDetail.Columns.Add("StockCheckDetailId", typeof(Int32));
                    DtStchkDetail.Columns.Add("Barcode", typeof(string));
                    DtStchkDetail.Columns.Add("InventoryName", typeof(string));

                    string QueryC = "SELECT Inventoryid from {0}.Inventory where Barcode=@Barcode ";
                    string command = string.Format(QueryC, BranchAlias);

                    MySqlParameter[] parameters3 =
                      {
                     new MySqlParameter("@Barcode", Microsoft.Security.Application.Encoder.HtmlEncode(txtBarcodesearch.Text)),
                     };

                    RInventoryId = ObjMain.NewExecuteScalar(command, parameters3);

                    // Prevents SQL Injections 
                    // Parameterized Approach 

                    // Existing Code 
                    // RInventoryId = ObjMain.ExecuteScalar("SELECT Inventoryid from " + BranchAlias + ".Inventory where Barcode='" + Microsoft.Security.Application.Encoder.HtmlEncode(txtBarcodesearch.Text) + " '");
                    DtStchkDetail.Columns.Add("InventoryId", typeof(Int32));
                    DtStchkDetail.Columns.Add("OldQty", typeof(decimal));
                    DtStchkDetail.Columns.Add("CheckedQty", typeof(decimal));
                    DtStchkDetail.Columns.Add("Diffs", typeof(decimal));

                    DataRow Dr = DtStchkDetail.NewRow();
                    Dr["StockCheckDetailId"] = 0;
                    Dr["Barcode"] = Microsoft.Security.Application.Encoder.HtmlEncode(txtBarcodesearch.Text);
                    Dr["InventoryName"] = Microsoft.Security.Application.Encoder.HtmlEncode(txtDesc.Text);
                    Dr["InventoryId"] = RInventoryId;
                    Dr["OldQty"] = Microsoft.Security.Application.Encoder.HtmlEncode(txtOnHand.Text);
                    Dr["CheckedQty"] = Microsoft.Security.Application.Encoder.HtmlEncode(txtCheckqty.Text);
                    //Dr["Diffs"] = (Math.Abs(Convert.ToDecimal(txtOnHand.Text)) - (Convert.ToDecimal(txtCheckqty.Text)));

                    if (Convert.ToInt32(Microsoft.Security.Application.Encoder.HtmlEncode(txtOnHand.Text)) > 0)
                    {
                        Dr["Diffs"] = (Convert.ToDecimal(Microsoft.Security.Application.Encoder.HtmlEncode(txtOnHand.Text))) + (Convert.ToDecimal(Microsoft.Security.Application.Encoder.HtmlEncode(txtCheckqty.Text)));
                    }
                    else
                    {

                        Dr["Diffs"] = (Convert.ToDecimal(Microsoft.Security.Application.Encoder.HtmlEncode(txtOnHand.Text))) + (Convert.ToDecimal(Microsoft.Security.Application.Encoder.HtmlEncode(txtCheckqty.Text)));
                    }
                    DtStchkDetail.Rows.Add(Dr);

                    // Load The Grid 

                    Session["DtStchkDetail"] = DtStchkDetail;
                    grdStockCheck.DataSource = DtStchkDetail;
                    grdStockCheck.DataBind();
                    ClearFunc();
                    btnConfirm.Enabled = false;
                    btnVoid.Enabled = false;
                }
            }
            else
            {
                DtStchkDetail.Columns.Add("StockCheckDetailId", typeof(Int32));
                DtStchkDetail.Columns.Add("Barcode", typeof(string));
                DtStchkDetail.Columns.Add("InventoryName", typeof(string));


                string QueryC = "SELECT Inventoryid from {0}.Inventory where Barcode=@Barcode ";
                string command = string.Format(QueryC, BranchAlias);

                MySqlParameter[] parameters3 =
                  {
                     new MySqlParameter("@Barcode", Microsoft.Security.Application.Encoder.HtmlEncode(txtBarcodesearch.Text)),
                     };

                RInventoryId = ObjMain.NewExecuteScalar(command, parameters3);


                //RInventoryId = ObjMain.ExecuteScalar("SELECT Inventoryid from " + BranchAlias + ".Inventory where Barcode='" + Microsoft.Security.Application.Encoder.HtmlEncode(txtBarcodesearch.Text.Trim()) + " '");
                DtStchkDetail.Columns.Add("InventoryId", typeof(Int32));
                DtStchkDetail.Columns.Add("OldQty", typeof(decimal));
                DtStchkDetail.Columns.Add("CheckedQty", typeof(decimal));
                DtStchkDetail.Columns.Add("Diffs", typeof(decimal));

                DataRow Dr = DtStchkDetail.NewRow();
                Dr["StockCheckDetailId"] = 0;
                Dr["Barcode"] = txtBarcodesearch.Text;
                Dr["InventoryName"] = txtDesc.Text;
                Dr["InventoryId"] = RInventoryId;
                Dr["OldQty"] = txtOnHand.Text;
                Dr["CheckedQty"] = txtCheckqty.Text;
                //Dr["Diffs"] = (Math.Abs(Convert.ToDecimal(txtOnHand.Text)) - (Convert.ToDecimal(txtCheckqty.Text)));
                if (Convert.ToInt32(Microsoft.Security.Application.Encoder.HtmlEncode(txtOnHand.Text)) > 0)
                {
                    Dr["Diffs"] = (Convert.ToDecimal(Microsoft.Security.Application.Encoder.HtmlEncode(txtOnHand.Text))) + (Convert.ToDecimal(Microsoft.Security.Application.Encoder.HtmlEncode(txtCheckqty.Text)));
                }
                else
                {

                    Dr["Diffs"] = (Convert.ToDecimal(Microsoft.Security.Application.Encoder.HtmlEncode(txtOnHand.Text))) + (Convert.ToDecimal(Microsoft.Security.Application.Encoder.HtmlEncode(txtCheckqty.Text)));
                }
                DtStchkDetail.Rows.Add(Dr);

                // Load The Grid 

                Session["DtStchkDetail"] = DtStchkDetail;
                grdStockCheck.DataSource = DtStchkDetail;
                grdStockCheck.DataBind();
                ClearFunc();
                btnConfirm.Enabled = false;
                btnVoid.Enabled = false;
            }
        }

        protected void btnStockCheckSearch_Click(object sender, EventArgs e)
        {

            // XSS Attack  Prevention 
            if (cmbBranches.Visible == false)
            {
                BranchAlias = Session["Branch_HQ"].ToString();

                LoadCheckListbySTCHKNO(BranchAlias, Microsoft.Security.Application.Encoder.HtmlEncode(txtStkchkSearch.Text));

            }
            else 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
                LoadCheckListbySTCHKNO(BranchAlias, Microsoft.Security.Application.Encoder.HtmlEncode(txtStkchkSearch.Text));
            }
            txtStkchkSearch.Text = "";


        }
        protected void btnClearSess_Click(object sender, EventArgs e)
        {
            Session["DtStchkDetail"] = null;
            Response.Redirect("InventoryStockCollector.aspx");
        }
        //nid added for Process StockCheck on 19-Dec-2019
        protected void btnConfirm_Click(object sender, EventArgs e)
        {
            // XSS Attack Prevention 


            if (cmbBranches.Visible == false)
            {
                BranchAlias = Session["Branch_HQ"].ToString();


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

            }


            string sCmd;
            double dDQty;
            MySqlConnection Cn = new MySqlConnection(ConStr_Rds);
            Cn.Open();
            MySqlTransaction myTrans;
            myTrans = Cn.BeginTransaction();

            sStockChkID = Microsoft.Security.Application.Encoder.HtmlEncode(txtSTCID.Text);

            try
            {
                sCmd = "Update {0}.StockCheckDetail SD Left Outer Join {0}.InventoryCostAverage ICA On SD.InventoryID=ICA.InventoryID Set SD.OldQty=ICA.PQuantity-ICA.CutQuantity-ICA.RetailQty" +
                " Where SD.StockCheckID=" + sStockChkID + " ";

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

                K = ObjCloudMain.ExecuteNonQuery(command5);

                sCmd = "Select SM.TransDate As TransDate, SD.InventoryId, Sum(SD.CheckedQty) As SCheckedQty, Avg(SD.OldQty) As SOldQty, Avg(SD.UnitCost) As UCost  " +
                    " From {0}.StockCheckMaster SM Left Outer Join {0}.StockCheckDetail SD On SM.StockCheckID=SD.StockCheckID Where SM.StockCheckId=@StockCheckId And SM.Confirmed=0 Group By SD.InventoryId";

                string Command6 = string.Format(sCmd, BranchAlias);
                MySqlParameter[] parameters6 =
                  {
                     new MySqlParameter("@StockCheckId",sStockChkID),

                  };
                DT = ObjMain.NewGetData_DT(Command6, parameters6);


                foreach (DataRow dr in DT.Rows)
                {
                    dDQty = Convert.ToDouble(dr["SCheckedQty"]) - Convert.ToDouble(dr["SOldQty"]);
                    if (dDQty != 0)
                    {

                        string dates = Convert.ToDateTime(dr["TransDate"]).ToString("yyyy-MM-dd");


                        //for updating InventoryCostAverage
                        sCmd = "Update {0}.InventoryCostAverage Set PQuantity=PQuantity+" + dDQty + ", PAmount=PAmount+(" + dDQty * Convert.ToDouble(dr["UCost"]) + ") " +
                            " Where InventoryID= " + dr["InventoryId"] + " ";
                        string Command7 = string.Format(sCmd, BranchAlias);

                        K = ObjCloudMain.ExecuteNonQuery(Command7);

                        //for updating InventoryAdjust
                        sCmd = "INSERT INTO {0}.InventoryAdjust (InventoryID,AdjustQuantity,UnitCost,Notes,DateAdjusted) VALUES (" +
                            dr["InventoryId"] + "," + dDQty + "," + dr["UCost"] + ", '*STOCKCHECK*' ,'" + dates + "')";

                        string Command8 = string.Format(sCmd, BranchAlias);

                        K = ObjCloudMain.ExecuteNonQuery(Command8);
                    }
                }
                //for Updating StockCheck Status
                sCmd = "Update {0}.StockCheckMaster Set Confirmed=1 Where StockCheckId=" + sStockChkID + " ";
                string command9 = string.Format(sCmd, BranchAlias);

                K = ObjCloudMain.ExecuteNonQuery(command9);

                myTrans.Commit();
                Cn.Close();
                Session["DtStchkDetail"] = null;


            }
            catch (System.IO.IOException)
            {
                myTrans.Rollback();
                Cn.Close();
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' StockCheck Error Occurred ');location.href='InventoryStockCollector.aspx' ", true);
            }
            finally
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' StockCheck Process Completed Successfully ');location.href='InventoryStockCollector.aspx' ", true);
            }
        }
        public void Temp_StkMasterRecord()
        {

            if (txtSTCID.Text == "")
            {


                if (DtStchkMaster.Rows.Count > 0)
                {

                    DataRow Dr = DtStchkMaster.NewRow();
                    Dr["TransDate"] = Microsoft.Security.Application.Encoder.HtmlEncode(Curr_Date);
                    Dr["StockcheckNo"] = Microsoft.Security.Application.Encoder.HtmlEncode(lblStockCheckNo.Text);
                    Dr["Status"] = "Pending";
                    DtStchkMaster.Rows.Add(Dr);
                    Session["DtStchkMaster"] = DtStchkMaster;
                }
                else
                {
                    DtStchkMaster.Columns.Add("TransDate", typeof(DateTime));
                    DtStchkMaster.Columns.Add("StockcheckNo", typeof(string));
                    DtStchkMaster.Columns.Add("Status", typeof(string));
                    DataRow Dr = DtStchkMaster.NewRow();
                    Dr["TransDate"] = Microsoft.Security.Application.Encoder.HtmlEncode(Curr_Date);
                    Dr["StockcheckNo"] = Microsoft.Security.Application.Encoder.HtmlEncode(lblStockCheckNo.Text);
                    Dr["Status"] = "Pending";
                    DtStchkMaster.Rows.Add(Dr);
                    Session["DtStchkMaster"] = DtStchkMaster;

                }

            }
        }
        public void ClearFunc()
        {
            txtBarcodesearch.Text = "";
            txtDesc.Text = "";
            txtOnHand.Text = "";
            txtCheckqty.Text = "";

        }
        private void loadStockCheckgrid()
        {
            DataTable Dt = new DataTable();
            string Query = "Select I.Inventoryid,I.Inventoryname,I.BARCODE,I.STOCKCODE,I.DESCRIPTION,I.CLASS,I.UNIT,I.PRICE,(IC.PQuantity - (IC.CutQuantity + IC.RetailQty)) as OnHand ,SC.StcQty, ((IC.PQuantity - (IC.CutQuantity + IC.RetailQty))-SC.StcQty) as Diff,CASE WHEN M.STCflag=1 THEN 'Confirmed' WHEN M.STCflag = 2 THEN 'Void' ELSE 'Pending' END as status  from {0}.inventory AS I inner join testbr.inventorycostaverage  AS IC ON I.InventoryID=IC.InventoryID inner join {0}.STCDetail as SC On I.InventoryId=SC.InventoryID inner join {0}.StcMaster as M On I.Inventoryid=M.stcid;";
            string command = string.Format(Query, BranchAlias);

            Dt = ObjMain.GetData_DT(command);
            grdStockCheck.DataSource = Dt;
            grdStockCheck.DataBind();
        }

        protected void btnCheckListSave_Click(object sender, EventArgs e)
        {

            string message = "Do you want to submit?";
            ClientScript.RegisterOnSubmitStatement(this.GetType(), "confirm", "return confirm('" + message + "');");


            string sDB = string.Empty;

            if (cmbBranches.Visible == false)
            {

                Cmb_BranchName = Session["Branch_HQ"].ToString();
            }
            else 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

            }

            sDB = Cmb_BranchName;
            //John Modify 2019-Dec-23 ***************************//
            if (txtSTCID.Text.Trim() == "")
            {

                if (grdStockCheck.Rows.Count == 0)
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('You Must Add Items For Stock Check');location.href='InventoryStockCollector.aspx'", true);
                }
                else
                {
                    InsertCheckList();
                }



            }
            else
            {

                for (int i = 0; i < grdStockCheck.Rows.Count; i++)
                {
                    //Label lblBarcode = (Label)grdStockCheck.Rows[i].Cells[0].FindControl("lblBarCode");
                    Label lblID = (Label)grdStockCheck.Rows[i].Cells[0].FindControl("lblInventoryid");
                    TextBox lblSTCQty = (TextBox)grdStockCheck.Rows[i].Cells[0].FindControl("txtChkQty");
                    Label LblQOH = (Label)grdStockCheck.Rows[i].Cells[0].FindControl("lblonhand");
                    Label LblItemID = (Label)grdStockCheck.Rows[i].Cells[0].FindControl("lblItemID");
                    TStockCheckId = txtSTCID.Text.Trim();
                    // TUnitCost = ObjMain.ExecuteScalar("select   unitcost from " + sDB + ".inventorycostaverage where inventoryid=" + Microsoft.Security.Application.Encoder.HtmlEncode(lblID.Text.Trim()) + ";");
                    string QueryM = "select   unitcost from {0}.inventorycostaverage where inventoryid=@inventoryid;";
                    string command = string.Format(QueryM, sDB);

                    MySqlParameter[] parameters =
                     {
                      new MySqlParameter("@inventoryid",Microsoft.Security.Application.Encoder.HtmlEncode(lblID.Text.Trim())),
                     };
                    TUnitCost = ObjMain.NewExecuteScalar(command, parameters);

                    if (ObjSel.STCCheckInventoryIDExistBySTCID(sDB, int.Parse(Microsoft.Security.Application.Encoder.HtmlEncode(txtSTCID.Text.Trim())), int.Parse(lblID.Text)) == "True")
                    {


                        UpdateSTCCHECKLIST(sDB, int.Parse(Microsoft.Security.Application.Encoder.HtmlEncode(txtSTCID.Text)), int.Parse(Microsoft.Security.Application.Encoder.HtmlEncode(lblID.Text.Trim())), double.Parse(Microsoft.Security.Application.Encoder.HtmlEncode(lblSTCQty.Text.Trim())), double.Parse(Microsoft.Security.Application.Encoder.HtmlEncode(LblQOH.Text.Trim())), int.Parse(Microsoft.Security.Application.Encoder.HtmlEncode(LblItemID.Text)));
                    }
                    else
                    {
                        string SCDQ = " Insert Into  {0}.stockcheckdetail(StockCheckId,InventoryId, OldQty, CheckedQty,UnitCost)values " +
                            " (@StockCheckId,@InventoryId,@OldQty, @CheckedQty,@UnitCost ) ";

                        string command1 = string.Format(SCDQ, sDB);

                        MySqlParameter[] parameters1 =
                         {
                             new MySqlParameter("@StockCheckId",Convert.ToInt32(TStockCheckId)),
                             new MySqlParameter("@InventoryId",Convert.ToInt32(Microsoft.Security.Application.Encoder.HtmlEncode(lblID.Text))),
                             new MySqlParameter("@OldQty",Convert.ToDecimal(Microsoft.Security.Application.Encoder.HtmlEncode(LblQOH.Text))),
                             new MySqlParameter("@CheckedQty",Convert.ToDecimal(Microsoft.Security.Application.Encoder.HtmlEncode(lblSTCQty.Text))),
                             new MySqlParameter("@UnitCost",Convert.ToDecimal(TUnitCost)),

                         };


                        K = ObjMain.ExecuteQuery(command1, parameters1);





                    }
                }
                //}
            }
            //***************************//

            Session["DtStchkDetail"] = null;

        }

        private void InsertCheckList()
        {
            // XSS Attack Prevention
            if (cmbBranches.Visible == false)
            {
                BranchAlias = Session["Branch_HQ"].ToString();


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

            }


            // StockCheckNo ( Like BR1C00001)
            StockChkNo = ObjSel.GetMaxSTCID(BranchAlias);
            StockChkNoNew = String.Format("{0:D5}", int.Parse(StockChkNo));
            // BranchPrefix 
            BranchPrefix = ObjSel.GetBranchPrefix(BranchAlias);
            string StkNo = string.Empty;
            StkNo = BranchPrefix + "C" + StockChkNoNew;
            lblStockCheckNo.Text = StkNo;

            // Insert Part : StockCheck Details 
            foreach (GridViewRow row in grdStockCheck.Rows)
            {
                Label GInvenId = (Label)row.FindControl("lblInventoryid");
                Label GInVenName = (Label)row.FindControl("lblInvName");
                Label GBarCode = (Label)row.FindControl("lblBarCode");

                Label GOnHandQty = (Label)row.FindControl("lblonhand");
                TextBox GChkQty = (TextBox)row.FindControl("txtChkQty");
                Label GDiffQty = (Label)row.FindControl("lblDiffs");

                // Prevents SQL Injections

                // Existing Code 
                //Unitcost = ObjMain.ExecuteScalar("select   unitcost from " + BranchAlias + ".inventorycostaverage where inventoryid=" + Microsoft.Security.Application.Encoder.HtmlEncode(GInvenId.Text) + ";");
                string QR1 = "select   unitcost from {0}.inventorycostaverage where inventoryid=@inventoryid;";
                string command = string.Format(QR1, BranchAlias);

                MySqlParameter[] parameters =
                  {
                     new MySqlParameter("@inventoryid", Microsoft.Security.Application.Encoder.HtmlEncode(GInvenId.Text)),
                  };
                Unitcost = ObjMain.NewExecuteScalar(command, parameters);


                // Ins- StockCheckDetail 
                string SCDQ = " Insert Into  {0}.stockcheckdetail(StockCheckId,InventoryId, OldQty, CheckedQty,UnitCost)values(@StockCheckId,@InventoryId,@OldQty, @CheckedQty,@UnitCost ) ";
                string command1 = string.Format(SCDQ, BranchAlias);

                MySqlParameter[] parameters1 =
                 {
                     new MySqlParameter("@StockCheckId",Convert.ToInt32(Microsoft.Security.Application.Encoder.HtmlEncode(StockChkNo)) ),
                     new MySqlParameter("@InventoryId",Convert.ToInt32(Microsoft.Security.Application.Encoder.HtmlEncode(GInvenId.Text)) ),
                     new MySqlParameter("@OldQty", Convert.ToDecimal(Microsoft.Security.Application.Encoder.HtmlEncode(GOnHandQty.Text))),
                     new MySqlParameter("@CheckedQty",Convert.ToDecimal(Microsoft.Security.Application.Encoder.HtmlEncode(GChkQty.Text)) ),
                     new MySqlParameter("@UnitCost",Convert.ToDecimal(Unitcost) ),

                  };



                K = ObjMain.ExecuteQuery(command1, parameters1);

            }
            // Ins - StockcheckMaster
            string SCMQ = " Insert Into  {0}.stockcheckmaster(StockCheckNo,TransDate,FromDate,ToDate , StockCheckType," +
                " DeptId,DeptType,GroupId,ClassType,ActiveType,Updated,Confirmed)values(@StockCheckNo,@TransDate,@FromDate,@ToDate,@StockCheckType," +
                " @DeptId,@DeptType,@GroupId,@ClassType,@ActiveType ,@ActiveType ,@Confirmed ) ";

            string command2 = string.Format(SCMQ, BranchAlias);

            MySqlParameter[] parameters2 =
                  {
                     new MySqlParameter("@StockCheckNo",lblStockCheckNo.Text),
                     new MySqlParameter("@TransDate",Curr_DateOnly),
                     new MySqlParameter("@FromDate",Curr_Date),
                     new MySqlParameter("@ToDate",Curr_Date),
                     new MySqlParameter("@StockCheckType","M"),
                     new MySqlParameter("@DeptId",0),
                     new MySqlParameter("@DeptType","0"),
                     new MySqlParameter("@GroupId","0"),
                     new MySqlParameter("@ClassType","0"),
                     new MySqlParameter("@ActiveType","0"),
                     new MySqlParameter("@Updated","0"),
                     new MySqlParameter("@Confirmed","0"),

                    };


            L = ObjMain.ExecuteQuery(command2, parameters2);

            Session["DtStchkDetail"] = null;
            Session["DtStchkMaster"] = null;
            if (L > 0)
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('StockCheck Items Saved Successfully');location.href='InventoryStockCollector.aspx'", true);
            }
            else
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('StockCheck Items Not  Saved');location.href='InventoryStockCollector.aspx'", true);
            }

        }

        //John
        private void UpdateSTCCHECKLIST(string sDB, int iSTCID, int iInventoryID, double dQTY, double dQOH, int iLblItemID)
        {

            if (cmbBranches.Visible == false)
            {
                BranchAlias = Session["Branch_HQ"].ToString();


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


            string sCmd = "Update {0}.stockcheckDetail set checkedQTY = @checkedQTY where StockCheckID = @StockCheckID and inventoryid =@inventoryid and StockCheckDetailId = @StockCheckDetailId;";
            string command = string.Format(sCmd, BranchAlias);
            MySqlParameter[] parameters =
                   {
                     new MySqlParameter("@checkedQTY",dQTY),
                     new MySqlParameter("@StockCheckID",iSTCID),
                     new MySqlParameter("@inventoryid",iInventoryID),
                     new MySqlParameter("@StockCheckDetailId",iLblItemID),

                    };




            IUpdateSTCDetails = ObjMain.ExecuteQuery(command, parameters);
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('StockCheck Items Update Successfully');location.href='InventoryStockCollector.aspx'", true);
        }

        private void StoreGVDatatoDT() //John added on 24-Dec-2019
        {
            DataTable DT = new DataTable();
            Session["DtStchkDetail"] = null;
            if (grdStockCheck.Rows.Count > 0)
            {
                foreach (GridViewRow row in grdStockCheck.Rows)
                {
                    if (DtTempStchkDetail.Rows.Count == 0)
                    {
                        DtTempStchkDetail.Columns.Add("StockCheckDetailId", typeof(Int32));
                        DtTempStchkDetail.Columns.Add("Barcode", typeof(string));
                        DtTempStchkDetail.Columns.Add("InventoryName", typeof(string));
                        DtTempStchkDetail.Columns.Add("InventoryId", typeof(Int32));
                        DtTempStchkDetail.Columns.Add("OldQty", typeof(decimal));
                        DtTempStchkDetail.Columns.Add("CheckedQty", typeof(decimal));
                        DtTempStchkDetail.Columns.Add("Diffs", typeof(decimal));
                    }
                    DataRow Dr = DtTempStchkDetail.NewRow();
                    Label lblInvId = row.FindControl("lblInventoryid") as Label;
                    Label lblBarcode = row.FindControl("lblBarcode") as Label;
                    Label lblItemID = row.FindControl("lblitemID") as Label;
                    Label lblInventoryName = row.FindControl("lblInvName") as Label;

                    Label lblOnhand = row.FindControl("lblOnhand") as Label;
                    TextBox txtChkQty = row.FindControl("txtChkQty") as TextBox;
                    Label lblDiffs = row.FindControl("lblDiffs") as Label;

                    Dr["InventoryId"] = Convert.ToInt32(lblInvId.Text.Trim());
                    Dr["Barcode"] = lblBarcode.Text.Trim();
                    Dr["StockCheckDetailId"] = Convert.ToInt32(lblItemID.Text.Trim());
                    Dr["InventoryName"] = lblInventoryName.Text.Trim();
                    Dr["OldQty"] = Convert.ToDecimal(lblOnhand.Text.Trim());
                    Dr["CheckedQty"] = Convert.ToDecimal(txtChkQty.Text.Trim());
                    Dr["Diffs"] = Convert.ToDecimal(lblOnhand.Text) - Convert.ToDecimal(txtChkQty.Text);
                    DtTempStchkDetail.Rows.Add(Dr);


                }
                Session["DtStchkDetail"] = DtTempStchkDetail;
                grdStockCheck.DataSource = DtTempStchkDetail;
                grdStockCheck.DataBind();
            }
        }


        protected void grdStockCheck_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            // XSS Attack Prevention 

            //John added on 24-Dec-2019 PM
            string sDB = string.Empty;

            if (cmbBranches.Visible == false)
            {
                Cmb_BranchName = Session["Branch_HQ"].ToString();


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



            sDB = Cmb_BranchName;
            if (e.CommandName == "Delete")
            {
                int index = Convert.ToInt32(e.CommandArgument);

                int i = index;
                Label lblID = (Label)grdStockCheck.Rows[i].Cells[0].FindControl("lblInventoryid");
                Label LblItemID = (Label)grdStockCheck.Rows[i].Cells[0].FindControl("lblItemID");
                Label lblSTCDetailItemID = (Label)grdStockCheck.Rows[i].Cells[0].FindControl("lblItemID");
                if (txtSTCID.Text.Trim() == "")
                {
                    DataTable dt1 = (DataTable)Session["DtStchkDetail"];
                    if (dt1.Rows.Count > 0)
                    {
                        dt1.Rows[index].Delete();
                        Session["DtStchkMaster"] = dt1;
                        grdStockCheck.DataSource = dt1;
                        grdStockCheck.DataBind();
                    }
                }
                else
                {

                    //if (ObjSel.STCCheckInventoryIDExistBySTCID(sDB, int.Parse(txtSTCID.Text.Trim()), int.Parse(lblID.Text)) == "True")
                    if (int.Parse(lblSTCDetailItemID.Text) != 0)
                    {
                        //StoreGVDatatoDT();
                        string STCIDCnt = ObjSel.GetTotalRowCountbySTCID(sDB, int.Parse(Microsoft.Security.Application.Encoder.HtmlEncode(txtSTCID.Text)));

                        if (int.Parse(STCIDCnt) == grdStockCheck.Rows.Count)
                        {

                            DeleteSTCItems(sDB, int.Parse(Microsoft.Security.Application.Encoder.HtmlEncode(txtSTCID.Text)), int.Parse(Microsoft.Security.Application.Encoder.HtmlEncode(lblID.Text)), int.Parse(Microsoft.Security.Application.Encoder.HtmlEncode(LblItemID.Text)));
                        }
                        else
                        {
                            //Pop up Alert Box
                            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('Please Save New Added Items');", true);

                        }

                    }
                    else
                    {
                        DataTable dt1 = (DataTable)Session["DtStchkDetail"];
                        if (dt1.Rows.Count > 0)
                        {
                            dt1.Rows[index].Delete();
                            Session["DtStchkMaster"] = dt1;
                            grdStockCheck.DataSource = dt1;
                            grdStockCheck.DataBind();
                        }
                    }
                }
            }
        }


        protected void grdStockCheck_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            // No Code          
        }
        private void DeleteSTCItems(string sDB, int iSTCID, int iInventoryID, int iLblItemID)
        {


            string sCmd = "Delete from {0}.stockcheckdetail where stockcheckid = @stockcheckid and inventoryid=@inventoryid and Stockcheckdetailid=@Stockcheckdetailid ";
            string command = string.Format(sCmd, sDB);

            MySqlParameter[] parameters =
                   {
                     new MySqlParameter("@stockcheckid",iSTCID),
                     new MySqlParameter("@inventoryid",iInventoryID),
                     new MySqlParameter("@Stockcheckdetailid",iLblItemID),
                    };


            IDeleteSTCItem = ObjMain.ExecuteQuery(command, parameters);
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('Item Successfully Deleted');", true);
        }


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

            }
            #endregion
            sDB = Cmb_BranchName;
            VoidSTCCheckList(sDB, int.Parse(txtSTCID.Text.Trim()));
            Session["DtStchkDetail"] = null;

        }
        private void VoidSTCCheckList(string sDB, int iSTCID)
        {
            string sCmd = "Update {0}.StockCheckMaster set confirmed =@confirmed  where stockcheckid=@stockcheckid ";

            string command = string.Format(sCmd, sDB);
            MySqlParameter[] parameters =
                   {
                     new MySqlParameter("@confirmed","2"),
                     new MySqlParameter("@stockcheckid",iSTCID),
                    };

            IUpdateSTCVoid = ObjMain.ExecuteQuery(command, parameters);
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('Void Check list Successfully');location.href='InventoryStockCollector.aspx'", true);

        }
        protected void btnSave_Click(object sender, EventArgs e)
        {
            // XSS Attack Prevention

            #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
            loadChecklist(BranchAlias, Microsoft.Security.Application.Encoder.HtmlEncode(txtStartDt.Text), Microsoft.Security.Application.Encoder.HtmlEncode(txtEndDt.Text));
        }

        protected void txtBarcodesearch_TextChanged(object sender, EventArgs e)
        {
            // XSS Attack Prevention 

            // Prevents SQL Injections 
            // Parameterized Approach 

            if (cmbBranches.Visible == false)
            {
                BranchAlias = Session["Branch_HQ"].ToString();


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

            if (txtBarcodesearch.Text.Trim() != "")
            {


                string cmd = "select I.inventoryid, sum(pquantity-(CutQuantity+RetailQty))as OnHand, I.Description,I.Unit 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  barcode= @barcode ;";
                DataSet ds = new DataSet();
                string command = string.Format(cmd, BranchAlias);
                MySqlParameter[] parameters =
                   {
                     new MySqlParameter("@barcode",Microsoft.Security.Application.Encoder.HtmlEncode(txtBarcodesearch.Text.Trim())),
                   };
                DataTable dtknew = new DataTable();

                dtknew = ObjMain.NewGetData_DT(command, parameters);
                // assign here 
                txtDesc.Text = dtknew.Rows[0]["Description"].ToString();
                txtOnHand.Text = dtknew.Rows[0]["OnHand"].ToString();
                hdnfldInventoryId.Text =  dtknew.Rows[0] ["inventoryid"].ToString();
                txtUOM.Text = dtknew.Rows[0]["Unit"].ToString();
                txtCheckqty.Focus();
                btnConfirm.Enabled = false;

            }
        }

        //John
        private void loadChecklist(string sDB, string sFromDate, string sToDate)
        {
            // XSS Attack Prevention
            // Prevents SQL Injections 
            // Paramerterized Approach 

            DataTable Dt = new DataTable();

            string cmd = "Select StockCheckID as STCID,date(Transdate) as Transdate,StockCheckNo, " +
                              " Case " +
                              " When Confirmed = 0 then 'Pending' " +
                              " When Confirmed = 1 then 'Confirmed' " +
                              " When Confirmed = 2 then 'Void' END as STCSTATUS,'' as Edit " +
                              " from {0}.stockcheckmaster where Transdate between @FromDate and @ToDate ;";

            string command = string.Format(cmd, sDB);
            MySqlParameter[] parameters =
                   {
                     new MySqlParameter("@FromDate",Microsoft.Security.Application.Encoder.HtmlEncode(sFromDate)),
                     new MySqlParameter("@ToDate",Microsoft.Security.Application.Encoder.HtmlEncode(sToDate)),
                    };

            Dt = ObjMain.NewGetData_DT(command, parameters);
            grdChkList.DataSource = Dt;
            grdChkList.DataBind();
        }

        public void LoadCheckListbySTCHKNO(string sDB, string StockChkNo)
        {
            DataTable Dt = new DataTable();
            string cmd = "Select StockCheckID as STCID,date(Transdate) as Transdate,StockCheckNo, " +
                                    " Case " +
                                    " When Confirmed = 0 then 'Pending' " +
                                    " When Confirmed = 1 then 'Confirmed' " +
                                    " When Confirmed = 2 then 'Void' END as STCSTATUS,'' as Edit " +
                                    " from {0}.stockcheckmaster where StockCheckNo =@StockCheckNo ;";

            string command = string.Format(cmd, sDB);
            MySqlParameter[] parameters =
                   {
                     new MySqlParameter("@StockCheckNo",StockChkNo),

                    };
            Dt = ObjMain.NewGetData_DT(command, parameters);
            grdChkList.DataSource = Dt;
            grdChkList.DataBind();

        }

        //John
        protected void grdChkList_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            // XSS Attack Prevention

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

            }




            if (e.CommandName == "EditSTC")
            {
                int index = Convert.ToInt32(e.CommandArgument);
                Label lblSTCStatus = (Label)grdChkList.Rows[index].Cells[0].FindControl("lblSTCStatus");


                Label lblID = (Label)grdChkList.Rows[index].Cells[0].FindControl("lblSTCPID");
                Label lblSTCNo = (Label)grdChkList.Rows[index].Cells[0].FindControl("lblSTCNo");
                ViewSTCDetails(BranchAlias, lblID.Text, lblSTCNo.Text.Trim());



                if (txtSTCNo.Text != "")
                {
                    btnCheckListSave.Enabled = false;

                }


                //if (lblSTCStatus.Text == "Pending")
                //{
                //    Label lblID = (Label)grdChkList.Rows[index].Cells[0].FindControl("lblSTCPID");
                //    Label lblSTCNo = (Label)grdChkList.Rows[index].Cells[0].FindControl("lblSTCNo");
                //    ViewSTCDetails(BranchAlias, lblID.Text, lblSTCNo.Text.Trim());

                //}
                //else
                //{
                //    ClientScript.RegisterStartupScript(GetType(), "Message", "Unable to Edit", true);
                //}

            }
        }



        //John
        private void ViewSTCDetails(string sDB, string sSTCPID, string sSTCNO)
        {

            DataTable Dt = new DataTable();
            string cmd = " Select B.InventoryID,A.StockCheckDetailId,B.Barcode,B.InventoryName,oldqty as oldqty,CheckedQTY as CheckedQty,if(oldqty>0,sum(oldqty-CheckedQTY),sum(oldqty+CheckedQTY)) as Diffs from {0}.stockcheckDetail A " +
                                 " join {0}.Inventory B on A.InventoryID = B.InventoryID " +
                                 " join {0}.InventoryCostAverage C on C.InventoryID = B.InventoryID " +
                                 " where stockcheckid = @stockcheckid " +
                                 " group by A.stockcheckdetailid;";

            string command = string.Format(cmd, sDB);

            MySqlParameter[] parameters =
                   {
                     new MySqlParameter("@stockcheckid",sSTCPID),
                   };

            Dt = ObjMain.NewGetData_DT(command, parameters);
            grdStockCheck.DataSource = Dt;
            grdStockCheck.DataBind();
            txtSTCID.Text = sSTCPID;
            txtSTCNo.Text = sSTCNO;

            Session["DtStchkDetail"] = Dt;

            if (ObjSel.GetStockCheckStatus(sDB, Convert.ToInt32(sSTCPID)) != "0")
            {
                btnCheckListSave.Enabled = false;
                btnVoid.Enabled = false;
                btnConfirm.Enabled = false;
                grdStockCheck.Enabled = false;
                btnAddToCheckList.Enabled = false;

            }
            else
            {
                btnCheckListSave.Enabled = true;
                btnVoid.Enabled = true;
                btnConfirm.Enabled = true;
                grdStockCheck.Enabled = true;
                btnAddToCheckList.Enabled = true;


            }






        }
    }
}