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;

namespace SUNWEB
{
    public partial class InventoryPromotions : System.Web.UI.Page
    {
        BL_SELECT ObjSel = new BL_SELECT();
        BLCompany ObjBL = new BLCompany();
        PLCOMMON ObjPL = new PLCOMMON();

        MYSQLCLOUD ObjCloudMain = new MYSQLCLOUD();
        BL_USER ObjUserBL = new BL_USER(); //This Object for All User and Page Related fuctions included 
        PLCUSTOMER ObjCustPL = new PLCUSTOMER();
        Int32 K = 0;
        Int32 L = 0;
        Int32 S = 0;
        string ConStr = ConfigurationManager.ConnectionStrings["ConMysql"].ConnectionString;
        string ConStr_Rds = ConfigurationManager.ConnectionStrings["ConRDS"].ConnectionString;
        string Curr_Date = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        string Curr_DateOnly = System.DateTime.Now.ToString("yyyy-MM-dd");
        string Curr_Second = System.DateTime.Now.Second.ToString("HH:mm:ss");
        int iSno = 0;
        DateTime MonthstartDt;
        DataSet ds = new DataSet();
        MYSQLDB ObjMain = new MYSQLDB();
        DataTable DT = new DataTable();
        DataTable Dt2 = new DataTable();
        DataTable DtLicense = new DataTable();
        DataTable DtSuperAdmin = new DataTable();
        DataTable DtMultiBranch = new DataTable();
        DataTable DtNormalUser = new DataTable();
        DataTable DTProductSale = new DataTable();
        DataTable DTPro = new DataTable();
        DataTable DTProA = new DataTable();
        DataTable DTProB = new DataTable();
        DataTable DTProC = new DataTable();
        DataTable DtCateoryList = new DataTable();
        DataTable FAdjDt = new DataTable();
        DataTable AdjDt = 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 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 BranchAlias = string.Empty;
        string L_InventoryPromotions = string.Empty;
        string BraNam = string.Empty;
        string sSno = string.Empty;
        string Branchidval = string.Empty;
        string BranchFullName = string.Empty;
        string Curr_BranchFullName = string.Empty;
        string Cmb_BranchName = string.Empty;

        string MatchFixid = string.Empty;

        string HQ = string.Empty;
        string Cm_id = string.Empty;
        string ISHQ = string.Empty;
        DataSet DS = new DataSet();
        string Chk_K = string.Empty;
        string I_PriceValue = string.Empty;


        string Vw_Chk = string.Empty;
        string RName, RTimeType, RFromTime, RToTime, RPriceType, RMixed, ROddDisc, RQuantityShiftType, RQuantity1, RDiscValue1, RQuantity2, RDiscValue2, RQuantity3, RDiscValue3, RQuantity4, RDiscValue4, RQuantity5, RDiscValue5, RDescription, RActive, RNoDiscQty;
        string RBranchid = string.Empty;
        string Branchid = string.Empty;
        string ReadHQ = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {

            PID = "27";    // This is for  Inventory Promotion  Page 

            if (!IsPostBack)
            {
                txtStartDt.Text = Curr_DateOnly;
                txtEndDt.Text = Curr_DateOnly;
                CalendarExtender1.StartDate= DateTime.Today;



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

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

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

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

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

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


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

                        }


                    }

                }

            }
            else
            {

            }


        }


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

                #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

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

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

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


                L_InventoryPromotions = DtLicense.Rows[0]["INVENTORYPROMOTIONS"].ToString();
                Session["L_InventoryPromotions"] = L_InventoryPromotions;
            }
             if ((Session["L_InventoryPromotions"] == null) || Session["L_InventoryPromotions"].ToString() == "N" || Session["Page_Acess"].ToString() == "N")
                {

                if (cmbBranches.SelectedItem.Text == "HQ")
                {

                    #region  Validation Between HQ Branch and Normal Branch 
                    BranchFullName = cmbBranches.SelectedItem.Text;      // This will Return Branch FullName 
                    if (BranchFullName == "HQ")
                    {
                        BranchAlias = Session["Branch_HQ"].ToString();
                        lblSelctedBranchCaption1.Text = BranchFullName;
                    }
                    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;
                        lblSelctedBranchCaption1.Text= BranchFullName;

                    }
                    #endregion

                    UPDATEBRANCH(BranchAlias);


                    LoadPromoList(Microsoft.Security.Application.Encoder.HtmlEncode(BranchAlias));
                    LoadInventoryview(BranchAlias);

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

                
                }
            else
            {

                //btnExcel.Enabled = true;
                //lblMsgTotalSelection.Text = "Total Sale Selection Between" + "&nbsp;&nbsp;&nbsp;" + txtStartDt.Text + "&nbsp;&nbsp;&nbsp;  And &nbsp;&nbsp;&nbsp;" + txtEndDt.Text;
              

                #region  Validation Between HQ Branch and Normal Branch 
                BranchFullName = cmbBranches.SelectedItem.Text;          // This will Return Branch FullName 
                lblSelctedBranchCaption1.Text = BranchFullName;
                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;
                    lblSelctedBranchCaption1.Text = BranchFullName;
                }
                #endregion

                LoadPromoList(BranchAlias);
                LoadInventoryview(BranchAlias);
                System.Threading.Thread.Sleep(2000);

            }

        }

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

        /// <summary>
        ///  This function Uses to Update the Current Database Selection 
        /// </summary>
        /// <param name="ActiveCallvalue"></param>
        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");
            }

        }


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

        }

        protected void btnGetReports_Click(object sender, EventArgs e)
        {
        }

        public void LoadTime()
        {


            // Loaing Acive Buttons 


            btnSave.Visible = true;
            btnSave.CssClass = "btn btn-primary";
            btnUpdate1.Visible = false;
            btnUpdate1.Enabled = false;
            btnUpdate1.CssClass = "btn btn-primary";

            // T1
            var hours = Enumerable.Range(00, 24).Select(i => i.ToString("D2"));
            var minutes = Enumerable.Range(00, 60).Select(i => i.ToString("D2"));

            cmbHours.DataSource = hours;
            cmbHours.DataBind();
            cmbMinutes.DataSource = minutes;
            cmbMinutes.DataBind();

            // T2

            var hours1 = Enumerable.Range(00, 24).Select(i => i.ToString("D2"));
            var minutes1 = Enumerable.Range(00, 60).Select(i => i.ToString("D2"));

            cmbHours1.DataSource = hours;
            cmbHours1.DataBind();
            CmbMinutes1.DataSource = minutes;
            CmbMinutes1.DataBind();

            if (chkPercentage.Checked == true)
            {
                lblLableValue1.Text = "QTY ( > = )  ";
                lblLableValue2.Text = "DISC(%)";
                chkPackageAmount.Checked = false;
                chkSellingPrice.Checked = false;
                lblNoDiscountLable.Visible = false;
                chkNodiscQty.Visible = false;
            }

            if (chkEver.Checked == true)
            {
                txtStartDt.Enabled = false;
                txtEndDt.Enabled = false;
                cmbHours.Enabled = false;
                cmbHours1.Enabled = false;
                cmbMinutes.Enabled = false;
                CmbMinutes1.Enabled = false;

                Ds1.Visible = false;
                ds2.Visible = false;


            }


        }


        protected void btnApplySearchPromotion_Click(object sender, EventArgs e)
        { 
        
        
        }


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

            string _isActive = string.Empty;
            if (cmbSearch.SelectedIndex == 1)
            {

                // Prevents SQL Injections 
                // Parameterized Approach 

              

                string Inv_QryAllInnven = "Select * from {0}.inventory as I " +
                              " join {0}.inventorycategories  as c ON I.Categoryid=c.categoryid " +
                              " join {0}.inventorycostaverage ic on ic.inventoryid=i.inventoryid left   join  {0}.inventorypromotiondetail as IP ON I.Barcode=IP.Barcode  where IP.Barcode IS NULL  group by I.inventoryid ";

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

                DT = ObjMain.GetData_DT(command);
                GrdInventory.DataSource = DT;
                GrdInventory.DataBind();



            }
            else if (cmbSearch.SelectedIndex == 2)      // By Inventoryid
            {
                if (txtSearchVal.Text != "")
                {

                    // string Inv_Qry1 = "select * from {0}.inventory as I join  {0}.inventorycategories  as c ON I.Categoryid=c.categoryid where I.Inventoryid=@Inventoryid ";

                    string Inv_Qry1 = "Select * from {0}.inventory as I " +
                              " join {0}.inventorycategories  as c ON I.Categoryid=c.categoryid " +
                              " join {0}.inventorycostaverage ic on ic.inventoryid=i.inventoryid  left   join  {0}.inventorypromotiondetail as IP ON I.Barcode=IP.Barcode  where IP.Barcode IS NULL AND  I.Inventoryid=@Inventoryid ";
                    string command = string.Format(Inv_Qry1, BranchAlias);
                    MySqlParameter[] parameters =
                    {
                     new MySqlParameter("@Inventoryid",Microsoft.Security.Application.Encoder.HtmlEncode(txtSearchVal.Text.ToString().Trim())),

                 };

                    DT = ObjMain.NewGetData_DT(command, parameters);

                    GrdInventory.DataSource = DT;
                    GrdInventory.DataBind();
                }
                else
                {
                    GrdInventory.DataSource = null;
                    GrdInventory.DataBind();
                }



            }
            else if (cmbSearch.SelectedIndex == 3)    // By Barcode 
            {
                if (txtSearchVal.Text != "")
                {

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

                    string Inv_Qry2 = "Select *  from {0}.inventory as I " +
                               " join {0}.inventorycategories  as c ON I.Categoryid=c.categoryid " +
                               " join {0}.inventorycostaverage ic on ic.inventoryid=i.inventoryid left   join  {0}.inventorypromotiondetail as IP ON I.Barcode=IP.Barcode  where IP.Barcode IS NULL AND  I.barcode like  CONCAT('%',@SearchVal, '%')  ";


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

                 };

                    DT = ObjMain.NewGetData_DT(command, parameters);

                    GrdInventory.DataSource = DT;
                    GrdInventory.DataBind();
                }
                else
                {
                    GrdInventory.DataSource =null;
                    GrdInventory.DataBind();

                }


            }

            else if (cmbSearch.SelectedIndex == 4)
            {
                if (txtSearchVal.Text != "")
                {

                    //string Inv_Qry3 = "select * from {0}.inventory as I join  {0}.inventorycategories  as c ON I.Categoryid=c.categoryid where  I.InventoryName like  CONCAT('%',@SearchVal, '%'); ";
                    string Inv_Qry3 = "Select * from {0}.inventory as I " +
                               " join {0}.inventorycategories  as c ON I.Categoryid=c.categoryid " +
                              " join {0}.inventorycostaverage ic on ic.inventoryid=i.inventoryid left   join  {0}.inventorypromotiondetail as IP ON I.Barcode=IP.Barcode  where IP.Barcode IS NULL AND  I.InventoryName like CONCAT('%',@SearchVal, '%') ";

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

                 };

                    DT = ObjMain.NewGetData_DT(command, parameters);
                    GrdInventory.DataSource = DT;
                    GrdInventory.DataBind();
                }
                else
                {
                    GrdInventory.DataSource =null;
                    GrdInventory.DataBind();
                }


            }

            else if (cmbSearch.SelectedIndex == 5)
            {

                if (txtSearchVal.Text != "")
                {

                    // string Inv_Qry3 = "select * from {0}.inventory as I join  {0}.inventorycategories  as c ON I.Categoryid=c.categoryid where  I.Description like CONCAT('%',@SearchVal, '%'); ";
                    string Inv_Qry3 = "Select * from {0}.inventory as I " +
                              " join {0}.inventorycategories  as c ON I.Categoryid=c.categoryid " +
                             " join {0}.inventorycostaverage ic on ic.inventoryid=i.inventoryid left   join  {0}.inventorypromotiondetail as IP ON I.Barcode=IP.Barcode  where IP.Barcode IS NULL AND  I.Description like CONCAT('%',@SearchVal, '%') ";

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

                 };

                    DT = ObjMain.NewGetData_DT(command, parameters);
                    GrdInventory.DataSource = DT;
                    GrdInventory.DataBind();
                }
                else
                {
                    GrdInventory.DataSource = null;
                    GrdInventory.DataBind();
                }


            }
            else if (cmbSearch.SelectedIndex == 6)     // Category 
            {

                if (txtSearchVal.Text != "")
                {
                    // string Inv_Qry4 = "select * from {0}.inventory as I join  {0}.inventorycategories  as c ON I.Categoryid=c.categoryid where   c.CategoryName like CONCAT('%',@SearchVal, '%') ";
                    string Inv_Qry4 = " Select * from {0}.inventory as I " +
                               " join {0}.inventorycategories  as c ON I.Categoryid=c.categoryid " +
                               " join {0}.inventorycostaverage ic on ic.inventoryid=i.inventoryid left   join  {0}.inventorypromotiondetail as IP ON I.Barcode=IP.Barcode  where IP.Barcode IS NULL AND  c.CategoryName like CONCAT('%',@SearchVal, '%')  ";
                    string command = string.Format(Inv_Qry4, BranchAlias);
                    MySqlParameter[] parameters =
                    {
                     new MySqlParameter("@SearchVal",Microsoft.Security.Application.Encoder.HtmlEncode(txtSearchVal.Text.ToString().Trim())),

                 };

                    DT = ObjMain.NewGetData_DT(command, parameters);
                    GrdInventory.DataSource = DT;
                    GrdInventory.DataBind();
                }
                else
                {
                    GrdInventory.DataSource = null ;
                    GrdInventory.DataBind();

                }



            }
            else if (cmbSearch.SelectedIndex == 7)     // StockCode 
            {

                if (txtSearchVal.Text != "")
                {

                    // string Inv_Qry4 = "select * from {0}.inventory as I join  {0}.inventorycategories  as c ON I.Categoryid=c.categoryid where   c.CategoryName like CONCAT('%',@SearchVal, '%') ";
                    string Inv_Qry4 = " Select * from {0}.inventory as I " +
                                    " join {0}.inventorycategories  as c ON I.Categoryid=c.categoryid " +
                                    " join {0}.inventorycostaverage ic on ic.inventoryid=i.inventoryid left   join  {0}.inventorypromotiondetail as IP ON I.Barcode=IP.Barcode  where IP.Barcode IS NULL AND  I.Stockcode like CONCAT('%',@SearchVal, '%')  ";
                    string command = string.Format(Inv_Qry4, BranchAlias);
                    MySqlParameter[] parameters =
                    {
                     new MySqlParameter("@SearchVal",Microsoft.Security.Application.Encoder.HtmlEncode(txtSearchVal.Text.ToString().Trim())),
                    };

                    DT = ObjMain.NewGetData_DT(command, parameters);
                    GrdInventory.DataSource = DT;
                    GrdInventory.DataBind();
                }
                else
                {
                    GrdInventory.DataSource =null;
                    GrdInventory.DataBind();

                }


                

            }



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


        protected void cmbBranches_SelectedIndexChanged(object sender, EventArgs e)
        {

            if (cmbBranches.SelectedIndex == 0)
            {
                Response.Write("Inventory.aspx");
            }
            else
            {
                DT = ObjUserBL.GetPageRightsDetailsPIDNew(Session["UserId"].ToString(), PID, cmbBranches.SelectedItem.Value);
                if (DT.Rows.Count > 0)
                {
                    Page_Acess = DT.Rows[0]["Acess_status"].ToString();
                    Read_Acess = DT.Rows[0]["Read_Access"].ToString();
                    Write_Acess = DT.Rows[0]["Write_Access"].ToString();
                    Isdowld_Acess = DT.Rows[0]["IDwld_Access"].ToString();
                    Session["Page_Acess"] = Page_Acess;
                    Session["Read_Acess"] = Read_Acess;
                    Session["Write_Acess"] = Write_Acess;
                    Session["Isdowld_Acess"] = Isdowld_Acess;
                }

                if (cmbBranches.SelectedIndex == 1)
                {

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

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

                }
                if (DtLicense.Rows.Count > 0)
                {

                    L_InventoryPromotions = DtLicense.Rows[0]["INVENTORYPROMOTIONS"].ToString();
                    Session["INVENTORYPROMOTIONS"] = L_InventoryPromotions;
                }

                if ((Session["INVENTORYPROMOTIONS"] == null) || Session["INVENTORYPROMOTIONS"].ToString() == "N" || Session["Page_Acess"].ToString() == "N")
                {
                    if (cmbBranches.SelectedIndex == 1)
                    {
                        // btnExcel.Enabled = true;
                        BranchAlias = Cmb_BranchName;
                        LoadPromoList(BranchAlias);
                        LoadInventoryview(BranchAlias);
                        
                    }
                    else
                    {
                        Response.Redirect("DeniedPage.aspx");
                    }



                }
                else if (Session["Write_Acess"].ToString() == "N")
                {
                    Response.Redirect("DeniedPage.aspx");
                }
                else
                {
                    // btnExcel.Enabled = true;
                    BranchAlias = Cmb_BranchName;

                    LoadPromoList(BranchAlias);
                    LoadInventoryview(BranchAlias);




                }
            }
            UPDATEBRANCH(BranchAlias);
            Page.Response.Redirect(Page.Request.Url.ToString(), true);




        }

        protected void chkPercentage_CheckedChanged(object sender, EventArgs e)
        {

            if (chkPercentage.Checked == true)
            {
                lblLableValue1.Text = "QTY ( > = )  ";
                lblLableValue2.Text = "DISC(%)";
                chkPackageAmount.Checked = false;
                chkSellingPrice.Checked = false;
                chkNodiscQty.Visible = false;
                lblNoDiscountLable.Visible = false;

            }

        }

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

                }
                #endregion
            }
            else
            {

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

            }



            if (chkRActive.Checked == true)
            {
                string _activevalue = "-1";
                LoadPromoListByActiveValue(BranchAlias, _activevalue);
             }
            else
            {
                string _inactivevalue = "0";
                LoadPromoListByActiveValue(BranchAlias, _inactivevalue);
            }

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

        }

        protected void chkPackageAmount_CheckedChanged(object sender, EventArgs e)
        {

            if (chkPackageAmount.Checked == true)
            {
                lblLableValue1.Text = "QTY ( > = )";
                lblLableValue2.Text = "DISC($)";
                chkSellingPrice.Checked = false;
                chkPercentage.Checked = false;
                chkNodiscQty.Visible = false;
                lblNoDiscountLable.Visible = false;
            }

        }

        protected void chkSellingPrice_CheckedChanged(object sender, EventArgs e)
        {
            if (chkSellingPrice.Checked == true)
            {
                lblLableValue1.Text = "QTY ( > = )";
                lblLableValue2.Text = "Selling Price ($)";
                chkPackageAmount.Checked = false;
                chkPercentage.Checked = false;
                chkNodiscQty.Visible = true;
                lblNoDiscountLable.Visible = true;
                lblNoDiscountLable.Text = " No Disc Qty ";

            }


        }

        protected void chkEver_CheckedChanged(object sender, EventArgs e)
        {

            if (chkEver.Checked == true)
            {
                chkdatetime.Checked = false;
                chkTime.Checked = false;
                txtStartDt.Enabled = false;
                txtEndDt.Enabled = false;

                cmbHours.Enabled = false;
                cmbHours1.Enabled = false;
                cmbMinutes.Enabled = false;
                CmbMinutes1.Enabled = false;

                Ds1.Visible = false;
                ds2.Visible = false;



            }




        }

        protected void chkdatetime_CheckedChanged(object sender, EventArgs e)
        {


            if (chkdatetime.Checked == true)
            {
                chkEver.Checked = false;
                chkTime.Checked = false;

                txtStartDt.Enabled = true;
                txtEndDt.Enabled = true;


                cmbHours.Enabled = true;
                cmbHours1.Enabled = true;
                cmbMinutes.Enabled = true;
                CmbMinutes1.Enabled = true;

                Ds1.Visible = true;
                ds2.Visible = true;


            }



        }

        protected void chkTime_CheckedChanged(object sender, EventArgs e)
        {
            if (chkTime.Checked == true)
            {
                chkdatetime.Checked = false;
                chkEver.Checked = false;

                txtStartDt.Enabled = false;
                txtEndDt.Enabled = false;


                cmbHours.Enabled = true;
                cmbHours1.Enabled = true;
                cmbMinutes.Enabled = true;
                CmbMinutes1.Enabled = true;

                Ds1.Visible = false;
                ds2.Visible = true;


            }


        }

        public void LoadPromoList(string Dbname)
        {
            ObjPL.IsActive = "-1";
            string QUERY = "SELECT * FROM {0}.inventorypromix   where Active=" + ObjPL.IsActive + " ; ";
            string Command = string.Format(QUERY, Dbname);

            DTPro = ObjMain.GetData_DT(Command);
            GrdPromo.DataSource = DTPro;
            GrdPromo.DataBind();

            // Other Fun use
            //if (cmbBranches.Visible == true)
            //{
            //    Curr_BranchFullName = cmbBranches.SelectedItem.Text;
            //    cd_BranchAlias = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), Curr_BranchFullName);  // This will Return BranchName( Actual Database Name )
            //    BraNam = cd_BranchAlias;
            //}
            //else
            //{

            //    BraNam = Session["Branch_HQ"].ToString();

            //}

        }


        public void LoadPromoListByActiveValue(string Dbname, string active_Status)
        {
            
            string QUERY = "SELECT * FROM {0}.inventorypromix   where  Name like CONCAT('%', @SearchVal, '%') and    Active=" + active_Status + " ; ";

            MySqlParameter[] parameters =
                {
                     new MySqlParameter("@SearchVal",txtInputPromotion.Text.ToString().Trim()),
                };
            string Command = string.Format(QUERY, Dbname);

            DTPro = ObjMain.NewGetData_DT(Command,parameters);
            GrdPromo.DataSource = DTPro;
            GrdPromo.DataBind();

            // Other Fun use
            //if (cmbBranches.Visible == true)
            //{
            //    Curr_BranchFullName = cmbBranches.SelectedItem.Text;
            //    cd_BranchAlias = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), Curr_BranchFullName);  // This will Return BranchName( Actual Database Name )
            //    BraNam = cd_BranchAlias;
            //}
            //else
            //{

            //    BraNam = Session["Branch_HQ"].ToString();

            //}

        }

        public void btnSave_Click(object sender, System.EventArgs e)
        {
            SavePromo();
        }

        public void SavePromo()
        {
            // XSS Attack Prevention 

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

                }
                #endregion
            }
            else
            {

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

            }



            // Checking TimeType
            if (chkEver.Checked == true)
            {
                ObjPL.TimeType = "1";
                //ObjPL.FromDt = Convert.ToDateTime(Curr_Date);
                //ObjPL.ToDt = Convert.ToDateTime(Curr_Date);

                ObjPL.StrFromDt = Curr_Date;
                ObjPL.strToDt = Curr_Date;

            }
            else if (chkdatetime.Checked == true)
            {
                ObjPL.TimeType = "2";

                string STH1 = Microsoft.Security.Application.Encoder.HtmlEncode(cmbHours.SelectedItem.Text);
                string STM1 = Microsoft.Security.Application.Encoder.HtmlEncode(cmbMinutes.SelectedItem.Text);

                int Sec = System.DateTime.Now.Second;
                string Added = STH1 + ":" + STM1 + ":" + Convert.ToString(Sec);
                string NewStartDt = string.Concat(txtStartDt.Text, " ", Added);
                //ObjPL.FromDt = Convert.ToDateTime(NewStartDt);
                ObjPL.StrFromDt = NewStartDt;

                string STH2 = Microsoft.Security.Application.Encoder.HtmlEncode(cmbHours1.SelectedItem.Text);
                string STM2 = Microsoft.Security.Application.Encoder.HtmlEncode(CmbMinutes1.SelectedItem.Text);

                int Sec1 = System.DateTime.Now.Second;
                string Added1 = STH2 + ":" + STM2 + ":" + Convert.ToString(Sec1);
                string NewEndtDt = string.Concat(txtEndDt.Text, " ", Added1);
                //ObjPL.ToDt = Convert.ToDateTime(NewEndtDt);
                ObjPL.strToDt = NewEndtDt;



            }
            else if (chkTime.Checked == true)
            {
                ObjPL.TimeType = "3";


                string STH1 = Microsoft.Security.Application.Encoder.HtmlEncode(cmbHours.SelectedItem.Text);
                string STM1 = Microsoft.Security.Application.Encoder.HtmlEncode(cmbMinutes.SelectedItem.Text);

                int Sec = System.DateTime.Now.Second;
                string Added = STH1 + ":" + STM1 + ":" + Convert.ToString(Sec);
                string NewStartDt = string.Concat(Microsoft.Security.Application.Encoder.HtmlEncode(Curr_DateOnly), " ", Added);
                //ObjPL.FromDt = Convert.ToDateTime(NewStartDt);
                ObjPL.StrFromDt = NewStartDt;


                string STH2 = Microsoft.Security.Application.Encoder.HtmlEncode(cmbHours1.SelectedItem.Text);
                string STM2 = Microsoft.Security.Application.Encoder.HtmlEncode(CmbMinutes1.SelectedItem.Text);

                int Sec1 = System.DateTime.Now.Second;
                string Added1 = STH2 + ":" + STM2 + ":" + Convert.ToString(Sec1);
                string NewEndtDt = string.Concat(Microsoft.Security.Application.Encoder.HtmlEncode(Curr_DateOnly), " ", Added1);
                //ObjPL.ToDt = Convert.ToDateTime(NewEndtDt);
                ObjPL.strToDt = NewEndtDt;



            }


            // Chcking PriceType 

            if (chkPercentage.Checked == true)
            {

                ObjPL.PriceType = "1";
            }
            else if (chkPackageAmount.Checked == true)
            {
                ObjPL.PriceType = "2";
            }
            else if (chkSellingPrice.Checked == true)
            {
                ObjPL.PriceType = "3";
            }



            if (chkMix.Checked == true)
            {
                ObjPL.IsMixed = "-1";
            }
            else
            {
                ObjPL.IsMixed = "0";
            }

            if (chkActive.Checked == true)
            {
                ObjPL.IsActive = "-1";
            }
            else
            {
                ObjPL.IsActive = "0";
            }



            if (chkNodiscQty.Checked == true)
            {
                ObjPL.IsNoQty = "-1";
            }
            else
            {
                ObjPL.IsNoQty = "0";
            }



            ObjPL.QtyShiftType = "1";
            ObjPL.PromoName = Microsoft.Security.Application.Encoder.HtmlEncode(txtProName.Text);


            if (txtQty1.Text != "")
            {
                ObjPL.QTY1 = Convert.ToDouble(Microsoft.Security.Application.Encoder.HtmlEncode(txtQty1.Text));
            }
            else
            {
                ObjPL.QTY1 = Convert.ToDouble("0");
            }

            if (txtAmtorPercentage1.Text != "")
            {
                ObjPL.DiscValue1 = Convert.ToDouble(Microsoft.Security.Application.Encoder.HtmlEncode(txtAmtorPercentage1.Text));
            }
            else
            {
                ObjPL.DiscValue1 = Convert.ToDouble("0");
            }

            if (txtQty2.Text != "")
            {
                ObjPL.QTY2 = Convert.ToDouble(Microsoft.Security.Application.Encoder.HtmlEncode(txtQty2.Text));
            }
            else
            {
                ObjPL.QTY2 = Convert.ToDouble("0");
            }

            if (txtAmtorPercentage2.Text != "")
            {
                ObjPL.DiscValue2 = Convert.ToDouble(Microsoft.Security.Application.Encoder.HtmlEncode(txtAmtorPercentage2.Text));
            }
            else
            {
                ObjPL.DiscValue2 = Convert.ToDouble("0");
            }
            if (txtQty3.Text != "")
            {
                ObjPL.QTY3 = Convert.ToDouble(txtQty3.Text);
            }
            else
            {
                ObjPL.QTY3 = Convert.ToDouble("0");
            }
            if (txtAmtorPercentage3.Text != "")
            {
                ObjPL.DiscValue3 = Convert.ToDouble(Microsoft.Security.Application.Encoder.HtmlEncode(txtAmtorPercentage3.Text));
            }
            else
            {
                ObjPL.DiscValue3 = Convert.ToDouble("0");
            }
            if (txtQty4.Text != "")
            {
                ObjPL.QTY4 = Convert.ToDouble(txtQty4.Text);
            }
            else
            {
                ObjPL.QTY4 = Convert.ToDouble("0");
            }
            if (txtAmtorPercentage4.Text != "")
            {
                ObjPL.DiscValue4 = Convert.ToDouble(Microsoft.Security.Application.Encoder.HtmlEncode(txtAmtorPercentage4.Text));
            }
            else
            {
                ObjPL.DiscValue4 = Convert.ToDouble("0");
            }

            if (txtQty5.Text != "")
            {
                ObjPL.QTY5 = Convert.ToDouble(Microsoft.Security.Application.Encoder.HtmlEncode(txtQty5.Text));
            }
            else
            {
                ObjPL.QTY5 = Convert.ToDouble("0");
            }

            if (txtAmtorPercentage5.Text != "")
            {
                ObjPL.DiscValue5 = Convert.ToDouble(Microsoft.Security.Application.Encoder.HtmlEncode(txtAmtorPercentage5.Text));
            }
            else
            {
                ObjPL.DiscValue5 = Convert.ToDouble("0");
            }

            ObjPL.PromoNameDesc = txtProDescription.Text;
            string QueryPromo = "Insert into  {0}.inventorypromix(Name ,TimeType, FromTime ,ToTime, PriceType , Mixed ,OddDisc ,QuantityShiftType, Quantity1, DiscValue1, "
                                + " Quantity2, DiscValue2, Quantity3, DiscValue3 ,Quantity4 ,DiscValue4 ,Quantity5 ,DiscValue5 ,Description ,Active ,NoDiscQty)"
                                + " Values(@Name,@TimeType,@FromTime,@ToTime,@PriceType,@Mixed,@OddDisc,@QuantityShiftType,  "
                                + " @Quantity1,@DiscValue1,@Quantity2,@DiscValue2,@Quantity3,@DiscValue3,@Quantity4,DiscValue4,  "
                                + " @Quantity5, @DiscValue5,@Description,@Active,@NoDiscQty ) ";



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

            MySqlParameter[] parameters =
                {
                     new MySqlParameter("@Name",ObjPL.PromoName),
                     new MySqlParameter("@TimeType",ObjPL.TimeType),
                     new MySqlParameter("@FromTime", ObjPL.StrFromDt),
                     new MySqlParameter("@ToTime",ObjPL.strToDt),
                     new MySqlParameter("@PriceType",ObjPL.PriceType),
                     new MySqlParameter("@Mixed",ObjPL.IsMixed),
                     new MySqlParameter("@OddDisc",0),
                     new MySqlParameter("@QuantityShiftType",ObjPL.QtyShiftType),
                     new MySqlParameter("@Quantity1",ObjPL.QTY1),
                     new MySqlParameter("@DiscValue1",ObjPL.DiscValue1),
                     new MySqlParameter("@Quantity2",ObjPL.QTY2),
                     new MySqlParameter("@DiscValue2",ObjPL.DiscValue2),
                     new MySqlParameter("@Quantity3",ObjPL.QTY3),
                     new MySqlParameter("@DiscValue3",ObjPL.DiscValue3),
                     new MySqlParameter("@Quantity4",ObjPL.QTY4),
                     new MySqlParameter("@DiscValue4",ObjPL.DiscValue4),
                     new MySqlParameter("@Quantity5",ObjPL.QTY5),
                     new MySqlParameter("@DiscValue5",ObjPL.DiscValue5),
                     new MySqlParameter("@Description",ObjPL.PromoNameDesc),
                     new MySqlParameter("@Active",ObjPL.IsActive),
                     new MySqlParameter("@NoDiscQty",ObjPL.IsNoQty),

            };

            K = ObjMain.ExecuteQuery(command, parameters);

            if (K > 0)
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('Inventory Promotion Added Successfully.');location.href='InventoryPromotions.aspx' ", true);
            }

        }


        protected void GrdPromo_SelectedIndexChanged(object sender, EventArgs e)
        {

            // XSS Attack Prevention 

            //shome.Attributes.Add("class", "nav-link"); //John hide on 03-July Layout change
            //home.Attributes.Add("class", "tab-pane fade");

            //sprofile.Attributes.Add("class", "nav-link active border-left-0");
            //profile.Attributes.Add("class", "tab-pane fade show active");


            if (cmbBranches.Visible == false)
            {

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

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

                    }
                    #endregion

                }
                #endregion
            }
            btnSave.Visible = false;
            btnSave.CssClass = "btn btn-primary";
            btnUpdate1.Visible = true;
            btnUpdate1.Enabled = true;
            btnUpdate1.CssClass = "btn btn-primary";
            MatchFixid = (GrdPromo.SelectedRow.FindControl("lblMixMatchID") as Label).Text;
            HidMixmatchid.Value = MatchFixid;     // Assign MixmatchID To Hidden Variable For Update
            DTProA = ObjSel.ReadPromoByID(BranchAlias, MatchFixid);
            RName = DTProA.Rows[0]["Name"].ToString();
            txtProName.Text = RName;
            RTimeType = DTProA.Rows[0]["TimeType"].ToString();
            RFromTime = DTProA.Rows[0]["FromTime"].ToString();

            // Getting Date Only From Date  (RFromTime) Variable 
            var TXDATE = Convert.ToDateTime(RFromTime);
            string RNewD1 = Convert.ToString(TXDATE.Date.ToString("yyyy-MM-dd"));

            // Getting From Time and Hour : FromTime
            var TTime = Convert.ToDateTime(RFromTime);
            string TFH1 = Convert.ToString(TTime.Hour);
            string TFM1 = Convert.ToString(TTime.Minute);
            RToTime = DTProA.Rows[0]["ToTime"].ToString();
            // Getting Date Only From Date  (RFromTime) Variable 
            var TXDATE1 = Convert.ToDateTime(RToTime);
            string RNewD2 = Convert.ToString(TXDATE1.Date.ToString("yyyy-MM-dd"));


            // Getting From Time and Hour : ToTime
            var RTTime = Convert.ToDateTime(RToTime);
            string TTH1 = Convert.ToString(RTTime.Hour);
            string TTM1 = Convert.ToString(RTTime.Minute);



            if (RTimeType.Equals("1"))
            {
                chkEver.Checked = true;
                chkdatetime.Checked = false;
                chkTime.Checked = false;


                // Enable and disable Date Control 

                chkdatetime.Checked = false;
                chkTime.Checked = false;
                txtStartDt.Enabled = false;
                txtEndDt.Enabled = false;

                cmbHours.Enabled = false;
                cmbHours1.Enabled = false;
                cmbMinutes.Enabled = false;
                CmbMinutes1.Enabled = false;

                Ds1.Visible = false;
                ds2.Visible = false;





            }
            else if (RTimeType.Equals("2"))
            {
                chkdatetime.Checked = true;
                chkEver.Checked = false;
                chkTime.Checked = false;
                // Enable and disable DateControl 

                chkEver.Checked = false;
                chkTime.Checked = false;

                txtStartDt.Enabled = true;
                txtEndDt.Enabled = true;


                cmbHours.Enabled = true;
                cmbHours1.Enabled = true;
                cmbMinutes.Enabled = true;
                CmbMinutes1.Enabled = true;

                Ds1.Visible = true;
                ds2.Visible = true;

                // Loading Time Values 

                txtStartDt.Text = RNewD1;
                txtEndDt.Text = RNewD2;

                cmbHours.SelectedItem.Text = TFH1;
                cmbMinutes.SelectedItem.Text = TFM1;

                cmbHours1.SelectedItem.Text = TTH1;
                CmbMinutes1.SelectedItem.Text = TTM1;




            }
            else if (RTimeType.Equals("3"))
            {
                chkTime.Checked = true;

                chkdatetime.Checked = false;
                chkEver.Checked = false;


                // Enable and disable Date Control 
                chkdatetime.Checked = false;
                chkEver.Checked = false;

                txtStartDt.Enabled = false;
                txtEndDt.Enabled = false;


                cmbHours.Enabled = true;
                cmbHours1.Enabled = true;
                cmbMinutes.Enabled = true;
                CmbMinutes1.Enabled = true;

                Ds1.Visible = false;
                ds2.Visible = true;


                // Loading Time Values 
                cmbHours.SelectedItem.Text = TFH1;
                cmbMinutes.SelectedItem.Text = TFM1;

                cmbHours1.SelectedItem.Text = TTH1;
                CmbMinutes1.SelectedItem.Text = TTM1;






            }



            RPriceType = DTProA.Rows[0]["PriceType"].ToString();
            if (RPriceType.Equals("1"))
            {
                chkPercentage.Checked = true;
                chkPackageAmount.Checked = false;
                chkSellingPrice.Checked = false;
                chkNodiscQty.Visible = false;
                lblNoDiscountLable.Visible = false;
            }
            else if (RPriceType.Equals("2"))
            {
                chkPercentage.Checked = false;
                chkPackageAmount.Checked = true;
                chkSellingPrice.Checked = false;
                chkNodiscQty.Visible = false;
                lblNoDiscountLable.Visible = false;
            }
            else if (RPriceType.Equals("3"))
            {

                chkNodiscQty.Visible = true;
                chkPercentage.Checked = false;
                chkPackageAmount.Checked = false;
                chkSellingPrice.Checked = true;
                lblNoDiscountLable.Visible = true;
                lblNoDiscountLable.Text = " No Disc Qty ";
            }

            RMixed = DTProA.Rows[0]["Mixed"].ToString();
            if (RMixed.Equals("-1"))
            {
                chkMix.Checked = true;
            }
            else if (RMixed.Equals("0"))
            {
                chkMix.Checked = false;
            }

            ROddDisc = DTProA.Rows[0]["OddDisc"].ToString();
            RQuantityShiftType = DTProA.Rows[0]["QuantityShiftType"].ToString();

            // Checking Qty & Discount Value 

            RQuantity1 = DTProA.Rows[0]["Quantity1"].ToString();
            if (RQuantity1.Equals("0"))
            {
                txtQty1.Text = "";
            }
            else
            {
                txtQty1.Text = RQuantity1;
            }

            RDiscValue1 = DTProA.Rows[0]["DiscValue1"].ToString();
            if (RDiscValue1.Equals("0"))
            {
                txtAmtorPercentage1.Text = "";
            }
            else
            {
                txtAmtorPercentage1.Text = RDiscValue1;
            }


            RQuantity2 = DTProA.Rows[0]["Quantity2"].ToString();
            if (RQuantity2.Equals("0"))
            {
                txtQty2.Text = "";
            }
            else
            {
                txtQty2.Text = RQuantity2;
            }


            RDiscValue2 = DTProA.Rows[0]["DiscValue2"].ToString();

            if (RDiscValue2.Equals("0"))
            {
                txtAmtorPercentage2.Text = "";
            }
            else
            {
                txtAmtorPercentage2.Text = RDiscValue2;
            }


            RQuantity3 = DTProA.Rows[0]["Quantity3"].ToString();


            if (RQuantity3.Equals("0"))
            {
                txtQty3.Text = "";
            }
            else
            {
                txtQty3.Text = RQuantity3;
            }




            RDiscValue3 = DTProA.Rows[0]["DiscValue3"].ToString();


            if (RDiscValue3.Equals("0"))
            {
                txtAmtorPercentage3.Text = "";
            }
            else
            {
                txtAmtorPercentage3.Text = RDiscValue3;
            }

            RQuantity4 = DTProA.Rows[0]["Quantity4"].ToString();
            if (RQuantity4.Equals("0"))
            {
                txtQty4.Text = "";
            }
            else
            {
                txtQty4.Text = RQuantity4;
            }



            RDiscValue4 = DTProA.Rows[0]["DiscValue4"].ToString();

            if (RDiscValue4.Equals("0"))
            {
                txtAmtorPercentage4.Text = "";
            }
            else
            {
                txtAmtorPercentage4.Text = RDiscValue4;
            }

            RQuantity5 = DTProA.Rows[0]["Quantity5"].ToString();

            if (RQuantity5.Equals("0"))
            {
                txtQty5.Text = "";
            }
            else
            {
                txtQty5.Text = RQuantity5;
            }
            RDiscValue5 = DTProA.Rows[0]["DiscValue5"].ToString();

            if (RDiscValue5.Equals("0"))
            {
                txtAmtorPercentage5.Text = "";
            }
            else
            {
                txtAmtorPercentage5.Text = RDiscValue5;
            }



            RDescription = DTProA.Rows[0]["Description"].ToString();
            if (RDescription != "")
            {
                txtProDescription.Text = RDescription;
            }

            RActive = DTProA.Rows[0]["Active"].ToString();
            if (RActive.Equals("-1"))
            {
                chkActive.Checked = true;
            }
            else if (RActive.Equals("0"))
            {
                chkActive.Checked = false;
            }


            RNoDiscQty = DTProA.Rows[0]["NoDiscQty"].ToString();

            if (RNoDiscQty.Equals("-1"))
            {
                chkNodiscQty.Checked = true;
            }
            else if (RNoDiscQty.Equals("0"))
            {
                chkNodiscQty.Checked = false;
            }


            // Load linked Barcode 


            string querychk = "select Barcode from  {0}.inventorypromotiondetail  where MixMatchID=@MixMatchID ";
            string command = string.Format(querychk, BranchAlias);

            MySqlParameter[] parameters =
                 {
                     new MySqlParameter("@MixMatchID",Microsoft.Security.Application.Encoder.HtmlEncode(HidMixmatchid.Value)),
                  };
            string ChkValue = ObjMain.NewExecuteScalar(command, parameters);

            if (ChkValue != "")
            {
                string queryDB = "select IP.Barcode,I.Description , IP.MixMatchID from {0}.inventorypromotiondetail as IP  inner join {0}.Inventory as I ON I.Barcode=IP.Barcode   where IP.MixMatchID=@MixMatchID ";
                string command1 = string.Format(queryDB, BranchAlias);

                MySqlParameter[] parameters1 =
                  {
                     new MySqlParameter("@MixMatchID",Microsoft.Security.Application.Encoder.HtmlEncode(HidMixmatchid.Value)),
                  };


                DTProB = ObjMain.NewGetData_DT(command1, parameters1);
                GrdDblinked.DataSource = DTProB;
                GrdDblinked.DataBind();
            }
            else

            {
                GrdDblinked.DataSource = null;
                GrdDblinked.DataBind();
            }



        }


        public void LoadLinkedBarcode()
        {
            if (cmbBranches.Visible == false)
            {

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

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

                    }
                    #endregion

                }
                #endregion
            }

            // XSS Attack Prevention 
            // Prevents SQL Injections
            // Parameterized Approach 

            GrdDblinked.DataSource = null;
            GrdDblinked.DataBind();
            string queryDBLinked = "select IP.Barcode,I.Description , IP.MixMatchID from {0}.inventorypromotiondetail as IP  inner join {0}.Inventory as I ON I.Barcode=IP.Barcode   where IP.MixMatchID=@MixMatchID ";
            string command = string.Format(queryDBLinked, BranchAlias);
            MySqlParameter[] parameters =
                 {
                     new MySqlParameter("@MixMatchID",Microsoft.Security.Application.Encoder.HtmlEncode(HidMixmatchid.Value)),
                  };
            DTProC = ObjMain.NewGetData_DT(command, parameters);
            GrdDblinked.DataSource = DTProC;
            GrdDblinked.DataBind();
        }

        protected void GrdDblinked_RowCommand(object sender, GridViewCommandEventArgs e)
        {

            // Prevents SQL Injections 
            // Parameterized Approach 

            if (cmbBranches.Visible == false)
            {

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

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

                }
                #endregion
            }

            string Name = e.CommandName;
            if (Name == "DeletePromo")
            {
                string rowIndex = Convert.ToString(e.CommandArgument);

                //GridViewRow row = this.GrdDblinked.Rows[rowIndex];
                // string sbarcode = ((Label)(row.FindControl("lblBarCode"))).Text;

                string DEL_Qry = "Delete from  {0}.inventorypromotiondetail  where  BarCode=@BarCode and MixMatchID=@MixMatchID  ";

                string command = string.Format(DEL_Qry, BranchAlias);
                MySqlParameter[] parameters =
                {
                     new MySqlParameter("@BarCode",rowIndex),
                     new MySqlParameter("@MixMatchID",Microsoft.Security.Application.Encoder.HtmlEncode(HidMixmatchid.Value)),
                  };



                K = ObjMain.ExecuteQuery(command, parameters);

                LoadLinkedBarcode(); // Not Refresh after Delete . 
                                     // Response.Redirect("InventoryPromotions.aspx");
                if (K > 0)
                {
                    LoadInventoryview(BranchAlias);
                    //ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('Barcode Removed from   Promotion ! ');location.href='InventoryPromotions.aspx'", true);                  
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('Barcode Removed from   Promotion ! ');location.href='InventoryPromotions.aspx'", true);


                }

            }

            //shome.Attributes.Add("class", "nav-link"); //John hide on 03-July-2021 Layout Change
            //home.Attributes.Add("class", "tab-pane fade");

            //sprofile.Attributes.Add("class", "nav-link");
            //profile.Attributes.Add("class", "tab-pane fade");




            sLinkedbarcode.Attributes.Add("class", "nav-link active border-left-0");
            Linkedbarcode.Attributes.Add("class", "tab-pane fade show active");



        }

        protected void GrdPromo_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            // Prevents SQL Injection 
            // Parameter Approach 

            if (cmbBranches.Visible == false)
            {

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

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

                }
                #endregion
            }

            string Name = e.CommandName;
            if (Name == "Delete")        
            {

                // Deleting Master Table of Promotion :  inventorypromix
                int rowIndex = Convert.ToInt32(e.CommandArgument);
                string DEL_Qry = " delete from  {0}.inventorypromix  where  Mixmatchid=@MixMatchID;  ";
                string command = string.Format(DEL_Qry, BranchAlias);


                MySqlParameter[] parameters =
                 {
                     new MySqlParameter("@MixMatchID",rowIndex),
                 };

                K = ObjMain.ExecuteQuery(command, parameters);

                // Deleting Subtable of the Promotion Table :  inventorypromotiondetail

                string Delete_Promotiondetails = "Delete from {0}.inventorypromotiondetail where Mixmatchid=@MixMatchID; ";
                string command_IPD = string.Format(Delete_Promotiondetails, BranchAlias);
                MySqlParameter[] parameters_IPD =
                 {
                     new MySqlParameter("@MixMatchID",rowIndex),
                 };

                S = ObjMain.ExecuteQuery(command_IPD, parameters_IPD);


                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Promotion  Name Deleted  ! ');location.href='InventoryPromotions.aspx'", true);
                Response.Redirect("InventoryPromotions.aspx");
            }

        }

        protected void btnUpdate1_Click(object sender, EventArgs e)
        {

            UpdatePromo();

        }



        protected void GrdInventory_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {
            // XSS Attack Prevention 

            if (cmbBranches.Visible == false)
            {

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

                }
                #endregion

            }


            if (cmbSearch.SelectedIndex == 0)
            {

                GrdInventory.PageIndex = e.NewPageIndex;

                string Inv_QryAllInnven = "Select *,sum(pquantity-(CutQuantity+RetailQty))as OnHandICA from " + BranchAlias + ".inventory as I " +
                              " join " + BranchAlias + ".inventorycategories  as c ON I.Categoryid=c.categoryid " +
                              " join " + BranchAlias + ".inventorycostaverage ic on ic.inventoryid=i.inventoryid  left   join  " + BranchAlias + ".inventorypromotiondetail as IP ON I.Barcode=IP.Barcode  where IP.Barcode IS NULL group by I.inventoryid ";
                DT = ObjMain.GetData_DT(Inv_QryAllInnven);




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



            }

            else if (cmbSearch.SelectedIndex == 1)
            {

                GrdInventory.PageIndex = e.NewPageIndex;

                string Inv_QryAllInnven = "Select *,sum(pquantity-(CutQuantity+RetailQty))as OnHandICA from {0}.inventory as I " +
                              " join {0}.inventorycategories  as c ON I.Categoryid=c.categoryid " +
                              " join {0}.inventorycostaverage ic on ic.inventoryid=i.inventoryid left   join  {0}.inventorypromotiondetail as IP ON I.Barcode=IP.Barcode  where IP.Barcode IS NULL  group by I.inventoryid ";

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

                DT = ObjMain.GetData_DT(command);
                GrdInventory.DataSource = DT;
                GrdInventory.DataBind();



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



                //string Inv_Qry1 = "Select *,sum(pquantity-(CutQuantity+RetailQty))as OnHandICA from {0}.inventory as I " +
                //                " join {0}.inventorycategories  as c ON I.Categoryid=c.categoryid " +
                //                " join {0}.inventorycostaverage ic on ic.inventoryid=i.inventoryid left   join  {0}.inventorypromotiondetail as IP ON I.Barcode=IP.Barcode  where IP.Barcode IS NULL AND  I.Inventoryid=@Inventoryid ";
                string Inv_Qry1 = "select * from {0}.inventory as I join  {0}.inventorycategories  as c ON I.Categoryid=c.categoryid where I.Inventoryid=@Inventoryid ";


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

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

                DT = ObjMain.NewGetData_DT(command, parameters);




                // DT = ObjMain.GetData_DT(Inv_Qry1);
                GrdInventory.DataSource = DT;
                GrdInventory.DataBind();


            }
            else if (cmbSearch.SelectedIndex == 3)
            {
                //string Inv_Qry2 = "select * from " + BranchAlias + ".inventory as I join  " + BranchAlias + ".inventorycategories  as c ON I.Categoryid=c.categoryid where  I.barcode like '%" + txtSearchVal.Text.ToString().Trim() + "%' ";
                GrdInventory.PageIndex = e.NewPageIndex;
                //string Inv_Qry2 = "Select *,sum(pquantity-(CutQuantity+RetailQty))as OnHandICA from {0}.inventory as I " +
                //                " join {0}.inventorycategories  as c ON I.Categoryid=c.categoryid " +
                //                " join {0}.inventorycostaverage ic on ic.inventoryid=i.inventoryid left   join  {0}.inventorypromotiondetail as IP ON I.Barcode=IP.Barcode  where IP.Barcode IS NULL AND  I.barcode like  CONCAT('%',@SearchVal,'%') ";


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

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

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

            }

            else if (cmbSearch.SelectedIndex == 4)
            {

                GrdInventory.PageIndex = e.NewPageIndex;
                //string Inv_Qry3 = "select * from " + BranchAlias + ".inventory as I join  " + BranchAlias + ".inventorycategories  as c ON I.Categoryid=c.categoryid where  I.InventoryName like '%" + txtSearchVal.Text.ToString().Trim() + "%' ";

                //string Inv_Qry3 = "Select *,sum(pquantity-(CutQuantity+RetailQty))as OnHandICA from {0}.inventory as I " +
                //                " join {0}.inventorycategories  as c ON I.Categoryid=c.categoryid " +
                //                " join {0}.inventorycostaverage ic on ic.inventoryid=i.inventoryid left   join  {0}.inventorypromotiondetail as IP ON I.Barcode=IP.Barcode  where IP.Barcode IS NULL AND  I.InventoryName like CONCAT('%',@SearchVal,'%') ";

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


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

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

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


            }

            else if (cmbSearch.SelectedIndex == 5)
            {

                GrdInventory.PageIndex = e.NewPageIndex;
                //string Inv_Qry3 = "select * from " + BranchAlias + ".inventory as I join  " + BranchAlias + ".inventorycategories  as c ON I.Categoryid=c.categoryid where  I.InventoryName like '%" + txtSearchVal.Text.ToString().Trim() + "%' ";

                //string Inv_Qry3 = "Select *,sum(pquantity-(CutQuantity+RetailQty))as OnHandICA from {0}.inventory as I " +
                //                " join {0}.inventorycategories  as c ON I.Categoryid=c.categoryid " +
                //                " join {0}.inventorycostaverage ic on ic.inventoryid=i.inventoryid left   join  {0}.inventorypromotiondetail as IP ON I.Barcode=IP.Barcode  where IP.Barcode IS NULL AND  I.InventoryName like CONCAT('%',@SearchVal,'%') ";

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


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

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

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


            }

            else if (cmbSearch.SelectedIndex == 6)
            {

                GrdInventory.PageIndex = e.NewPageIndex;
                //string Inv_Qry3 = "select * from " + BranchAlias + ".inventory as I join  " + BranchAlias + ".inventorycategories  as c ON I.Categoryid=c.categoryid where  I.InventoryName like '%" + txtSearchVal.Text.ToString().Trim() + "%' ";

                //string Inv_Qry3 = "Select *,sum(pquantity-(CutQuantity+RetailQty))as OnHandICA from {0}.inventory as I " +
                //                " join {0}.inventorycategories  as c ON I.Categoryid=c.categoryid " +
                //                " join {0}.inventorycostaverage ic on ic.inventoryid=i.inventoryid left   join  {0}.inventorypromotiondetail as IP ON I.Barcode=IP.Barcode  where IP.Barcode IS NULL AND  I.InventoryName like CONCAT('%',@SearchVal,'%') ";

                string Inv_Qry3 = "select * from {0}.inventory as I join  {0}.inventorycategories  as c ON I.Categoryid=c.categoryid where  Price =@SearchVal  OR price2 =@SearchVal OR price3 =@SearchVal OR  price4 =@SearchVal ;";


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

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

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


            }

            else if (cmbSearch.SelectedIndex == 7)
            {
                GrdInventory.PageIndex = e.NewPageIndex;
                //string Inv_Qry4 = "select * from " + BranchAlias + ".inventory as I join  " + BranchAlias + ".inventorycategories  as c ON I.Categoryid=c.categoryid where  c.CategoryName like '%" + txtSearchVal.Text.ToString().Trim() + "%' ";
                //string Inv_Qry4 = "Select *,sum(pquantity-(CutQuantity+RetailQty))as OnHandICA from {0}.inventory as I " +
                //                " join {0}.inventorycategories  as c ON I.Categoryid=c.categoryid " +
                //                " join {0}.inventorycostaverage ic on ic.inventoryid=i.inventoryid left   join  {0}.inventorypromotiondetail as IP ON I.Barcode=IP.Barcode  where IP.Barcode IS NULL AND  c.Categoryid=@Categoryid  group by I.inventoryid";

                string Inv_Qry4 = "select * from {0}.inventory as I join  {0}.inventorycategories  as c ON I.Categoryid=c.categoryid where   c.CategoryName like CONCAT('%',@SearchVal, '%') ";
                string command = string.Format(Inv_Qry4, BranchAlias);
                MySqlParameter[] parameters =
                    {
                     new MySqlParameter("@SearchVal",Microsoft.Security.Application.Encoder.HtmlEncode(txtSearchVal.Text.ToString().Trim())),
                    };

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

            }


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

        }
        protected void btnLink_Click(object sender, EventArgs e)
        {

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

                }
                #endregion

            }

            if (GrdInventory.Rows.Count > 0)
            {

                foreach (GridViewRow row in GrdInventory.Rows)    //append current page data to datatable
                {
                    Label InvID = (Label)row.FindControl("lblInventoryID");
                    Label Barcode = (Label)row.FindControl("lblBarCode");
                    Label PriceVal = (Label)row.FindControl("lblPrice");


                    CheckBox chk = (CheckBox)row.FindControl("chkSelect");

                    if (chk.Checked == true)
                    {


                        if (HidMixmatchid.Value != "")
                        {


                            // Chk_K = ObjMain.ExecuteScalar();
                            string QuryA = "Select  Barcode from  {0}.inventorypromotiondetail  where  MixMatchID=@MixMatchID ";
                            string commandA = string.Format(QuryA, BranchAlias);
                            MySqlParameter[] parametersA =
                            {
                                 new MySqlParameter("@MixMatchID",Microsoft.Security.Application.Encoder.HtmlEncode(HidMixmatchid.Value)),
                             };

                            Chk_K = ObjMain.NewExecuteScalar(commandA, parametersA);


                            if (Chk_K != "")
                            {
                                if (chkMix.Checked == true)
                                {
                                    string QR1 = "select Round(Price,2) from  {0}.inventory where Barcode='" + Chk_K + "' ";
                                    string Commandx = string.Format(QR1, BranchAlias);
                                    I_PriceValue = ObjMain.ExecuteScalar(Commandx);

                                    if (I_PriceValue == PriceVal.Text)
                                    {

                                        string QryChild = "Insert into  {0}.inventorypromotiondetail(MixMatchID,BarCode)values(@MixMatchID,@BarCode)";
                                        string commandB = string.Format(QryChild, BranchAlias);

                                        MySqlParameter[] parametersB =
                                          {
                                                 new MySqlParameter("@MixMatchID",Microsoft.Security.Application.Encoder.HtmlEncode(HidMixmatchid.Value)),
                                                 new MySqlParameter("@BarCode",Microsoft.Security.Application.Encoder.HtmlEncode(Barcode.Text)),
                                             };
                                        L = ObjMain.ExecuteQuery(commandB, parametersB);

                                        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Barcode Linked to Promotion !');location.href='InventoryPromotions.aspx'", true);
                                        GrdDblinked.DataSource = null;
                                        GrdDblinked.DataBind();

                                        // Get Updated LIST
                                        string queryDB = "select IP.Barcode,I.Description  , IP.MixMatchID from {0}.inventorypromotiondetail as IP  inner join {0}.Inventory as I ON I.Barcode=IP.Barcode   where IP.MixMatchID=@MixMatchID ";
                                        string commandc = string.Format(queryDB, BranchAlias);
                                        MySqlParameter[] parametersC =
                                            {
                                                 new MySqlParameter("@MixMatchID",Microsoft.Security.Application.Encoder.HtmlEncode(HidMixmatchid.Value)),

                                             };


                                        DTProB = ObjMain.NewGetData_DT(commandc, parametersC);
                                        GrdDblinked.DataSource = DTProB;
                                        GrdDblinked.DataBind();

                                    }
                                    else
                                    {
                                        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Promotion Price Should be Same in Mixed Promotion ! ')", true);
                                    }

                                }
                                else
                                {


                                    string QryChild = "Insert into  {0}.inventorypromotiondetail(MixMatchID,BarCode)values(@MixMatchID,@BarCode)";

                                    string commandD = string.Format(QryChild, BranchAlias);

                                    MySqlParameter[] parametersD =
                                             {
                                                 new MySqlParameter("@MixMatchID",Microsoft.Security.Application.Encoder.HtmlEncode(HidMixmatchid.Value)),
                                                 new MySqlParameter("@BarCode",Microsoft.Security.Application.Encoder.HtmlEncode(Barcode.Text)),
                                             };
                                    L = ObjMain.ExecuteQuery(commandD, parametersD);



                                    // ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Barcode Linked to Promotion !');location.href='InventoryPromotions.aspx'", true);
                                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Barcode Linked to Promotion !');location.reload();", true);
                                    GrdDblinked.DataSource = null;
                                    GrdDblinked.DataBind();

                                    // Get Updated LIST
                                    string queryDB = "select IP.Barcode,I.Description  , IP.MixMatchID from {0}.inventorypromotiondetail as IP  inner join {0}.Inventory as I ON I.Barcode=IP.Barcode   where IP.MixMatchID=@MixMatchID ";
                                    string commandE = string.Format(queryDB, BranchAlias);


                                    MySqlParameter[] parametersE =
                                             {
                                                 new MySqlParameter("@MixMatchID",Microsoft.Security.Application.Encoder.HtmlEncode(HidMixmatchid.Value)),

                                             };

                                    DTProB = ObjMain.NewGetData_DT(commandE, parametersE);
                                    GrdDblinked.DataSource = DTProB;
                                    GrdDblinked.DataBind();



                                }





                            }
                            else
                            {
                                string QryChild = "Insert into  {0}.inventorypromotiondetail(MixMatchID,BarCode)values(@MixMatchID,@BarCode);";

                                string CommandF = string.Format(QryChild, BranchAlias);


                                MySqlParameter[] parametersF =
                                            {
                                                 new MySqlParameter("@MixMatchID",Microsoft.Security.Application.Encoder.HtmlEncode(HidMixmatchid.Value)),
                                                 new MySqlParameter("@BarCode",Microsoft.Security.Application.Encoder.HtmlEncode(Barcode.Text)),
                                             };
                                L = ObjMain.ExecuteQuery(CommandF, parametersF);

                                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Barcode Linked to Promotion !');location.href='InventoryPromotions.aspx'", true);
                                GrdDblinked.DataSource = null;
                                GrdDblinked.DataBind();

                                // Get Updated LIST
                                string queryDB = "select IP.Barcode,I.Description  , IP.MixMatchID from {0}.inventorypromotiondetail as IP  inner join {0}.Inventory as I ON I.Barcode=IP.Barcode   where IP.MixMatchID=@MixMatchID; ";
                                string commandG = string.Format(queryDB, BranchAlias);

                                MySqlParameter[] parametersG =
                                            {
                                                 new MySqlParameter("@MixMatchID",Microsoft.Security.Application.Encoder.HtmlEncode(HidMixmatchid.Value)),

                                             };


                                DTProB = ObjMain.NewGetData_DT(commandG, parametersG);
                                GrdDblinked.DataSource = DTProB;
                                GrdDblinked.DataBind();


                            }






                        }
                        else
                        {
                            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Select Promotion In  PromtionList ! ')", true);

                        }



                    }
                }





                //foreach (GridViewRow row in gridLinked.Rows)
                //{
                //    Label SNo = (Label)row.FindControl("lblSNo");
                //    Label InvID = (Label)row.FindControl("lblInventoryID");
                //    Label Barcode = (Label)row.FindControl("lblBarCode");

                //    if (HidMixmatchid.Value != "")
                //    {

                //        string QryChild = "Insert into  " + BranchAlias + ".inventorypromotiondetail(MixMatchID,BarCode)values(" + HidMixmatchid.Value + ",'" + Barcode.Text + "')";
                //        L = ObjMain.ExecuteNonQuery(QryChild);
                //        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Barcode Linked to Promotion !')", true);
                //        gridLinked.DataSource = null;
                //        gridLinked.DataBind();

                //    }
                //    else
                //    {
                //        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Select Promotion In  PromtionList ! ')", true);

                //    }


                //}

            }

            Session.Remove("QtyTable");
            AdjDt.Clear();
            FAdjDt.Clear();
            LoadLinkedBarcode();

        }

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

        //    // New Temporary datatable 


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


        //    if (AdjDt.Rows.Count == 0)
        //    {
        //        AdjDt.Columns.Add(new System.Data.DataColumn("SNo", typeof(String)));
        //        AdjDt.Columns.Add(new System.Data.DataColumn("InventoryID", typeof(String)));
        //        AdjDt.Columns.Add(new System.Data.DataColumn("Barcode", typeof(String)));

        //    }

        //    DataRow dr;
        //    if (FAdjDt != null)
        //    {
        //        if (FAdjDt.Rows.Count > 0)
        //        {
        //            foreach (DataRow row in FAdjDt.Rows)    //load previous page session values to current datatable
        //            {
        //                dr = AdjDt.NewRow();
        //                dr[0] = row["SNo"].ToString();
        //                dr[1] = row["InventoryID"].ToString();
        //                dr[2] = row["Barcode"].ToString();
        //                AdjDt.Rows.Add(dr);
        //                iSno = Convert.ToInt32(dr[0]);
        //            }
        //        }
        //    }

        //    foreach (GridViewRow row in GrdInventory.Rows)    //append current page data to datatable
        //    {
        //        Label InvID = (Label)row.FindControl("lblInventoryID");
        //        Label Barcode = (Label)row.FindControl("lblBarCode");

        //        CheckBox chk = (CheckBox)row.FindControl("chkSelect");

        //        if (chk.Checked==true)
        //        {
        //            iSno = iSno + 1;
        //            sSno = Convert.ToString(iSno);

        //            dr = AdjDt.NewRow();
        //            dr[0] = sSno;
        //            dr[1] = InvID.Text;
        //            dr[2] = Barcode.Text;
        //            AdjDt.Rows.Add(dr);
        //        }
        //    }

        //    Session["QtyTable"] = AdjDt;

        //    DataTable DT101 = new DataTable();
        //    DT101 = (DataTable)Session["QtyTable"];



        //    gridLinked.DataSource = DT101;
        //    gridLinked.DataBind();

        //    if (AdjDt.Rows.Count > 0)
        //    {

        //        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Items Added to Promo Linked  Section '); ", true);
        //    }





        //}


        protected void cmbSearch_SelectedIndexChanged(object sender, EventArgs e)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ShowModalItemList();", true);
            if (cmbSearch.SelectedIndex == 5)
            {
                cmbCategory.Enabled = true;

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

                    }
                    #endregion

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

                LoadCategoriesDataList();

            }
            else
            {
                cmbCategory.Enabled = false;
            }
            //shome.Attributes.Add("class", "nav-link"); //John hide on 03-July-2021 Layout Change
            //home.Attributes.Add("class", "tab-pane fade");

            //sprofile.Attributes.Add("class", "nav-link active border-left-0");
            //profile.Attributes.Add("class", "tab-pane fade show active");

            //shome.Attributes.Add("class", "nav-link active border-left-0");
            //home.Attributes.Add("class", "tab-pane fade show active");
            // ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "();", true);
        }


        public void LoadCategoriesDataList()
        {

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

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

        }


        protected void cmbCategory_SelectedIndexChanged(object sender, EventArgs e)
        {

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

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

            if (cmbCategory.SelectedIndex != 0)
            {


                //string Inv_Qry5 = "select * from " + BranchAlias + ".inventory as I join  " + BranchAlias + ".inventorycategories  as c ON I.Categoryid=c.categoryid ORDER BY I.inventoryID asc LIMIT " + txtTop.Text.ToString().Trim() + "";
                string Inv_Qry5 = "Select *,sum(pquantity-(CutQuantity+RetailQty))as OnHandICA from {0}.inventory as I " +
                                " join {0}.inventorycategories  as c ON I.Categoryid=c.categoryid " +
                                " join {0}.inventorycostaverage ic on ic.inventoryid=i.inventoryid left   join  {0}.inventorypromotiondetail as IP ON I.Barcode=IP.Barcode  where IP.Barcode IS NULL AND  c.Categoryid=@Categoryid group by I.inventoryid";


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

                MySqlParameter[] parameters =
                  {
                     new MySqlParameter("@Categoryid",cmbCategory.SelectedItem.Value),

                    };



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

            }


        }

        /// <summary>
        ///  This Function uses to Update Promo Details 
        ///<para> Using MixMatchId</para>
        /// </summary>
        public void UpdatePromo()
        {
            // XSS Attack Prevention 

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

                    }
                    #endregion

                }
                #endregion
            }
            else
            {

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

            }



            // Checking TimeType
            if (chkEver.Checked == true)
            {
                ObjPL.TimeType = "1";
                //ObjPL.FromDt = Convert.ToDateTime(Curr_Date);
                //ObjPL.ToDt = Convert.ToDateTime(Curr_Date);
                ObjPL.StrFromDt = Curr_Date;
                ObjPL.strToDt = Curr_Date;

            }
            else if (chkdatetime.Checked == true)
            {
                ObjPL.TimeType = "2";

                string STH1 = Microsoft.Security.Application.Encoder.HtmlEncode(cmbHours.SelectedItem.Text);
                string STM1 = Microsoft.Security.Application.Encoder.HtmlEncode(cmbMinutes.SelectedItem.Text);

                int Sec = System.DateTime.Now.Second;
                string Added = STH1 + ":" + STM1 + ":" + Convert.ToString(Sec);
                string NewStartDt = string.Concat(Microsoft.Security.Application.Encoder.HtmlEncode(txtStartDt.Text), " ", Added);
                //ObjPL.FromDt = Convert.ToDateTime(NewStartDt);
                ObjPL.StrFromDt = NewStartDt;

                string STH2 = cmbHours1.SelectedItem.Text;
                string STM2 = CmbMinutes1.SelectedItem.Text;

                int Sec1 = System.DateTime.Now.Second;
                string Added1 = STH2 + ":" + STM2 + ":" + Convert.ToString(Sec1);
                string NewEndtDt = string.Concat(Microsoft.Security.Application.Encoder.HtmlEncode(txtEndDt.Text), " ", Added1);
                //ObjPL.ToDt = Convert.ToDateTime(NewEndtDt);
                ObjPL.strToDt = NewEndtDt;


            }
            else if (chkTime.Checked == true)
            {
                ObjPL.TimeType = "3";


                string STH1 = Microsoft.Security.Application.Encoder.HtmlEncode(cmbHours.SelectedItem.Text);
                string STM1 = Microsoft.Security.Application.Encoder.HtmlEncode(cmbMinutes.SelectedItem.Text);

                int Sec = System.DateTime.Now.Second;
                string Added = STH1 + ":" + STM1 + ":" + Convert.ToString(Sec);
                string NewStartDt = string.Concat(Microsoft.Security.Application.Encoder.HtmlEncode(Curr_DateOnly), " ", Added);
                //ObjPL.FromDt = Convert.ToDateTime(NewStartDt);
                ObjPL.StrFromDt = NewStartDt;


                string STH2 = Microsoft.Security.Application.Encoder.HtmlEncode(cmbHours1.SelectedItem.Text);
                string STM2 = Microsoft.Security.Application.Encoder.HtmlEncode(CmbMinutes1.SelectedItem.Text);

                int Sec1 = System.DateTime.Now.Second;
                string Added1 = STH2 + ":" + STM2 + ":" + Convert.ToString(Sec1);
                string NewEndtDt = string.Concat(Microsoft.Security.Application.Encoder.HtmlEncode(Curr_DateOnly), " ", Added1);
                //ObjPL.ToDt = Convert.ToDateTime(NewEndtDt);
                ObjPL.strToDt = NewEndtDt;




            }


            // Chcking PriceType 

            if (chkPercentage.Checked == true)
            {

                ObjPL.PriceType = "1";
            }
            else if (chkPackageAmount.Checked == true)
            {
                ObjPL.PriceType = "2";
            }
            else if (chkSellingPrice.Checked == true)
            {
                ObjPL.PriceType = "3";
            }



            if (chkMix.Checked == true)
            {
                ObjPL.IsMixed = "-1";
            }
            else
            {
                ObjPL.IsMixed = "0";
            }

            if (chkActive.Checked == true)
            {
                ObjPL.IsActive = "-1";
            }
            else
            {
                ObjPL.IsActive = "0";
            }



            if (chkNodiscQty.Checked == true)
            {
                ObjPL.IsNoQty = "-1";
            }
            else
            {
                ObjPL.IsNoQty = "0";
            }



            ObjPL.QtyShiftType = "1";
            ObjPL.PromoName = Microsoft.Security.Application.Encoder.HtmlEncode(txtProName.Text);


            if (txtQty1.Text != "")
            {
                ObjPL.QTY1 = Convert.ToDouble(Microsoft.Security.Application.Encoder.HtmlEncode(txtQty1.Text));
            }
            else
            {
                ObjPL.QTY1 = Convert.ToDouble("0");
            }

            if (txtAmtorPercentage1.Text != "")
            {
                ObjPL.DiscValue1 = Convert.ToDouble(Microsoft.Security.Application.Encoder.HtmlEncode(txtAmtorPercentage1.Text));
            }
            else
            {
                ObjPL.DiscValue1 = Convert.ToDouble("0");
            }

            if (txtQty2.Text != "")
            {
                ObjPL.QTY2 = Convert.ToDouble(Microsoft.Security.Application.Encoder.HtmlEncode(txtQty2.Text));
            }
            else
            {
                ObjPL.QTY2 = Convert.ToDouble("0");
            }

            if (txtAmtorPercentage2.Text != "")
            {
                ObjPL.DiscValue2 = Convert.ToDouble(Microsoft.Security.Application.Encoder.HtmlEncode(txtAmtorPercentage2.Text));
            }
            else
            {
                ObjPL.DiscValue2 = Convert.ToDouble("0");
            }
            if (txtQty3.Text != "")
            {
                ObjPL.QTY3 = Convert.ToDouble(Microsoft.Security.Application.Encoder.HtmlEncode(txtQty3.Text));
            }
            else
            {
                ObjPL.QTY3 = Convert.ToDouble("0");
            }
            if (txtAmtorPercentage3.Text != "")
            {
                ObjPL.DiscValue3 = Convert.ToDouble(Microsoft.Security.Application.Encoder.HtmlEncode(txtAmtorPercentage3.Text));
            }
            else
            {
                ObjPL.DiscValue3 = Convert.ToDouble("0");
            }
            if (txtQty4.Text != "")
            {
                ObjPL.QTY4 = Convert.ToDouble(Microsoft.Security.Application.Encoder.HtmlEncode(txtQty4.Text));
            }
            else
            {
                ObjPL.QTY4 = Convert.ToDouble("0");
            }
            if (txtAmtorPercentage4.Text != "")
            {
                ObjPL.DiscValue4 = Convert.ToDouble(Microsoft.Security.Application.Encoder.HtmlEncode(txtAmtorPercentage4.Text));
            }
            else
            {
                ObjPL.DiscValue4 = Convert.ToDouble("0");
            }

            if (txtQty5.Text != "")
            {
                ObjPL.QTY5 = Convert.ToDouble(Microsoft.Security.Application.Encoder.HtmlEncode(txtQty5.Text));
            }
            else
            {
                ObjPL.QTY5 = Convert.ToDouble("0");
            }

            if (txtAmtorPercentage5.Text != "")
            {
                ObjPL.DiscValue5 = Convert.ToDouble(Microsoft.Security.Application.Encoder.HtmlEncode(txtAmtorPercentage5.Text));
            }
            else
            {
                ObjPL.DiscValue5 = Convert.ToDouble("0");
            }

            ObjPL.PromoNameDesc = Microsoft.Security.Application.Encoder.HtmlEncode(txtProDescription.Text);

            string QueryUPT = "Update  {0}.inventorypromix set Name=@Name ,TimeType=@TimeType,FromTime=@FromTime , "
            + " ToTime=@ToTime,PriceType=@PriceType,Mixed=@Mixed,Quantity1=@Quantity1,DiscValue1=@DiscValue1 ,  "
            + " Quantity2=@Quantity2,DiscValue2=@DiscValue2,Quantity3=@Quantity3,DiscValue3=@DiscValue3,Quantity4=@Quantity4,DiscValue4=@DiscValue4, "
            + " Quantity5=@Quantity5,DiscValue5=@DiscValue5,Description=@Description, "
            + " Active=@Active,NoDiscQty=@NoDiscQty  where MixMatchID=@MixMatchID ";

            // Prevents SQL Injections 
            // Parameterized approach 

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

            MySqlParameter[] parameters =
                  {
                     new MySqlParameter("@Name",Microsoft.Security.Application.Encoder.HtmlEncode(txtProName.Text)),
                     new MySqlParameter("@TimeType",ObjPL.TimeType),
                     new MySqlParameter("@FromTime",ObjPL.StrFromDt),
                     new MySqlParameter("@ToTime",ObjPL.strToDt),
                     new MySqlParameter("@PriceType",ObjPL.PriceType),
                     new MySqlParameter("@Mixed",ObjPL.IsMixed),
                     new MySqlParameter("@Quantity1",ObjPL.QTY1),
                     new MySqlParameter("@DiscValue1",ObjPL.DiscValue1),
                     new MySqlParameter("@Quantity2",ObjPL.QTY2),
                     new MySqlParameter("@DiscValue2",ObjPL.DiscValue2),
                     new MySqlParameter("@Quantity3",ObjPL.QTY3),
                     new MySqlParameter("@DiscValue3",ObjPL.DiscValue3),
                     new MySqlParameter("@Quantity4",ObjPL.QTY4),
                     new MySqlParameter("@DiscValue4",ObjPL.DiscValue4),
                     new MySqlParameter("@Quantity5",ObjPL.QTY5),
                     new MySqlParameter("@DiscValue5",ObjPL.DiscValue5),
                     new MySqlParameter("@Description",ObjPL.PromoNameDesc),
                     new MySqlParameter("@Active",ObjPL.IsActive),
                     new MySqlParameter("@NoDiscQty",ObjPL.IsNoQty),
                     new MySqlParameter("@MixMatchID",HidMixmatchid.Value),

                    };

            L = ObjMain.ExecuteQuery(command, parameters);

            if (L > 0)
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('Inventory Promotion Updated Successfully.');location.href='InventoryPromotions.aspx' ", true);

            }





        }

        public void LoadInventoryview(string branch)
        {
            GrdInventory.DataSource = null;
            


            string InvenQuery = " select *,sum(pquantity-(CutQuantity+RetailQty))as OnHandICA from {0}.inventory as I " +
                                " join {0}.inventorycategories  as c ON I.Categoryid=c.categoryid " +
                                " join {0}.inventorycostaverage ic on ic.inventoryid=i.inventoryid " +
                                " left   join  {0}.inventorypromotiondetail as IP ON I.Barcode=IP.Barcode  where IP.Barcode IS NULL  group by i.inventoryid " +
                                " order by i.inventoryid;";

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

        }


    }
}