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

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



        BL_SELECT ObjSel = new BL_SELECT();
        BLCompany ObjBL = new BLCompany();
        PLCOMMON ObjPL = new PLCOMMON();
        BL_USER ObjUserBL = new BL_USER(); //This Object for All User and Page Related fuctions included 
        MYSQLCLOUD ObjCloudMain = new MYSQLCLOUD();
        PLCUSTOMER ObjCustPL = new PLCUSTOMER();
        Int32 K = 0;
        Int32 L = 0;
        Int32 S = 0;
        Int32 iUpdatePromoPosition = 0;
        Int32 iUpdatePromoColumn = 0;
        Int32 iInsertWebOrderPromo = 0;
        Int32 iDeleteWebOrderPromo = 0;
        string ConStr = ConfigurationManager.ConnectionStrings["ConMysql"].ConnectionString;
        string ConStr_Rds = ConfigurationManager.ConnectionStrings["ConRDS"].ConnectionString;
        string Curr_Date = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        string Curr_DateOnly = System.DateTime.Now.ToString("yyyy-MM-dd");
        DateTime MonthstartDt;
        DataSet ds = new DataSet();
        MYSQLDB ObjMain = new MYSQLDB();
        DataTable DT = new DataTable();
        DataTable Dt2 = new DataTable();
        DataTable DtLicense = new DataTable();
        DataTable DtSuperAdmin = new DataTable();
        DataTable DtMultiBranch = new DataTable();
        DataTable DtNormalUser = new DataTable();
        DataTable DTProductSale = new DataTable();
        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 L_UpsellingSetting = string.Empty;
        string Branchidval = string.Empty;
        string BranchFullName = string.Empty;
        string Curr_BranchFullName = string.Empty;
        string Cmb_BranchName = string.Empty;

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

        string RBranchid = string.Empty;
        string Branchid = string.Empty;
        string BranchAlias = string.Empty;

        string Vw_Chk = string.Empty;
        string ReadHQ = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {

            PID = "40";    // This is for UpsellingSetting  


            if (!IsPostBack)
            {
                txtStartDt.Text = Curr_DateOnly;
                txtEndDt.Text = Curr_DateOnly;
                grdPromotionPositioning.DataBind();
            }
            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)
                {
                    //LoadBranchName4SuperAdmin();
                    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)
                {
                    //LoadBranchName4SuperAdmin();
                    LoadBranchesOnID();
                }
                //cd_BranchAlias = cmbBranches.SelectedItem.Text;
                //LoadInventoryListGrid(cd_BranchAlias, txtStartDt.Text, txtEndDt.Text);
                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;

                if (!IsPostBack)
                {
                    //LoadCategoriesDataList(BranchAlias);
                    //LoadInventoryListGrid(cd_BranchAlias, txtStartDt.Text, txtEndDt.Text)
                    LoadPromotion(ActiveCallvalue); //John added on 14-Aug-2021 Load Promo Items
                    LoadInventory(ActiveCallvalue); //John added on 17-Aug-2021 Load Inventory

                    //chkActiveStatus.Enabled = true;
                    //chkT.Enabled = false;
                    //chkP.Enabled = true;
                    //btnUpdate.Visible = false;
                    //btnUpdate.CssClass = "btn btn-primary";

                }
            }
            else if (((Convert.ToBoolean(Session["IsMultiBranch"])) == true) && (Session["PortalTypeId"].ToString() == ""))
            {
                if (!IsPostBack)
                {
                    //LoadBranchName();
                    LoadBranchName4SuperAdmin();
                    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;" + Microsoft.Security.Application.Encoder.HtmlEncode(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_UpsellingSetting"].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
                        {
                            btnGetReports.Visible = true;

                            if (cmbBranches.Visible == false)
                            {
                                //  BindGridview(Session["Branch_HQ"].ToString(), txtStartDt.Text, txtEndDt.Text);
                                BranchAlias = Session["Branch_HQ"].ToString();
                                // Loading Parts : 
                                if (!IsPostBack)
                                {
                                    //LoadCategoriesDataList(BranchAlias);
                                    LoadPromotion(BranchAlias); //John added on 14-Aug-2021 Load Promo Items
                                    LoadInventory(BranchAlias); //John added on 17-Aug-2021 Load Inventory
                                }
                                //chkActiveStatus.Enabled = false;
                                //chkT.Enabled = false;
                                //chkP.Enabled = true;
                                //btnUpdate.Visible = false;
                                //btnUpdate.CssClass = "btn btn-primary";
                            }

                        }


                    }

                }

            }
            else
            {

            }

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

                //lblclientname.Text = Session["CM_ID"].ToString();
                //lblstorename.Text = Cmb_BranchName;
            }


        }


        public void ActiveCall()
        {
            string QueryCal = "select ActiveValue from portaldb.usermaster  where Userid=" + Session["UserId"].ToString() + " ";
            ActiveCallvalue = ObjMain.ExecuteScalar(QueryCal);
            if (ActiveCallvalue == "")
            {
                //ActiveCallvalue = ObjSel.GetFirstBranch(Session["Branch_HQ"].ToString());
                //ActiveCallvalue = ObjSel.GetFirstBranch(Session["Branch_HQ"].ToString());
                string _hq_query = "select IsHQ from  portaldb.companymaster where cm_id=" + Session["CM_ID"] + " ;";
                string _Is_HQ_Enabled = Convert.ToString(ObjMain.ExecuteScalar(_hq_query));
                if (_Is_HQ_Enabled == "1")
                {
                    ActiveCallvalue = ObjSel.GetHQ(Session["Branch_HQ"].ToString());

                }
                else if (_Is_HQ_Enabled == "0")
                {
                    ActiveCallvalue = ObjSel.GETBrachAlias8(Session["CM_ID"].ToString(), Session["Branch_HQ"].ToString(), Session["UserId"].ToString());
                }
            }


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

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

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

            //cd_BranchAlias = Microsoft.Security.Application.Encoder.HtmlEncode(ActiveCallvalue);
            //Curr_BranchFullName = ObjUserBL.GetBranchCurr_BranchVal(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), cd_BranchAlias);
            //Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), Curr_BranchFullName);  // This will Return BranchName( Actual Database Name )
            //cmbBranches.Items.FindByText(Curr_BranchFullName).Selected = true;
            //Branchidval = ObjUserBL.GetBranchIDbyName(ActiveCallvalue, ActiveCallvalue);

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

            }



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

            }

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

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

            //if (Session["L_UpsellingSetting"].ToString() == "N" || Session["Page_Acess"].ToString() == "N")
            if ((Session["L_UpsellingSetting"] == null) || Session["L_UpsellingSetting"].ToString() == "N" || Session["Page_Acess"].ToString() == "N")
            {
                //Response.Redirect("DeniedPage.aspx");

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

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

                    }
                    #endregion
                
                    UPDATEBRANCH(BranchAlias);

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

            else
            {


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

                }
                #endregion

             

                LoadPromotion(BranchAlias); //John added on 14-Aug-2021 Load Promo Items
                LoadInventory(BranchAlias); //
            }


         

            //else
            //{

            //    //btnExcel.Enabled = true;
            //    //lblMsgTotalSelection.Text = "Total Sale Selection Between" + "&nbsp;&nbsp;&nbsp;" + txtStartDt.Text + "&nbsp;&nbsp;&nbsp;  And &nbsp;&nbsp;&nbsp;" + txtEndDt.Text;
            //    cd_BranchAlias = Microsoft.Security.Application.Encoder.HtmlEncode(cmbBranches.SelectedItem.Text);
            //    // BindGridview(ActiveCallvalue, txtStartDt.Text, txtEndDt.Text);
            //    System.Threading.Thread.Sleep(2000);
            //    LoadPromotion(ActiveCallvalue); //John added on 14-Aug-2021 Load Promo Items
            //    LoadInventory(ActiveCallvalue); //John added on 17-Aug-2021 Load Inventory

            //}

        }


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

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

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

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


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


                    }


                }


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

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

        }


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

            }

        }


        protected void btnGetReports_Click(object sender, EventArgs e)
        {

        }

        protected void cmbBranches_SelectedIndexChanged(object sender, EventArgs e)
        {

            if (cmbBranches.SelectedIndex == 0)
            {
                Response.Write("UpsellingSetting.aspx");
            }
            else
            {
                DT = ObjUserBL.GetPageRightsDetailsPIDNew(Session["UserId"].ToString(), PID, Microsoft.Security.Application.Encoder.HtmlEncode(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);

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

                }

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

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



                if (DtLicense.Rows.Count > 0)
                {
                    L_MaxUserCnt = DtLicense.Rows[0]["UserCnt"].ToString();
                    L_UpsellingSetting = DtLicense.Rows[0]["UPSELLINGSETTING"].ToString();
                    Session["L_UpsellingSetting"] = L_UpsellingSetting;

                }

                if ((Session["L_UpsellingSetting"] == null) || Session["L_UpsellingSetting"].ToString() == "N" || Session["Page_Acess"].ToString() == "N")
                {
                    if (cmbBranches.SelectedIndex == 1)
                    {
                        // btnExcel.Enabled = true;

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

                        }
                        #endregion
                        LoadPromotion(BranchAlias); //John added on 14-Aug-2021 Load Promo Items
                        LoadInventory(BranchAlias); //John added on 17-Aug-2021 Load Inventory

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

                    }
                    #endregion

                    LoadPromotion(BranchAlias); //John added on 14-Aug-2021 Load Promo Items
                    LoadInventory(BranchAlias); //Jo

                }

                //if (Session["L_UpsellingSetting"].ToString() == "N" || Session["Page_Acess"].ToString() == "N")
                //{
                //    Response.Redirect("DeniedPage.aspx");

                //}
                //else if (Session["Write_Acess"].ToString() == "N")
                //{
                //    //btnGeneratebyinventoryid.Enabled = false;
                //    // btnGenerateIorderlaTiming.Enabled = false;
                //    //btnUpdate.Enabled = false;
                //}

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

                //    //btnGeneratebyinventoryid.Enabled = true;
                //    //btnGenerateIorderlaTiming.Enabled = true;
                //    //btnUpdate.Enabled = true;
                //    //LoadInventoryName(Cmb_BranchName);
                //    // LoadBaseTiming(Cmb_BranchName);
                //}
            }
            UPDATEBRANCH(Cmb_BranchName);

        }

        private void LoadPromotion(string sDB)
        {
            DataTable DT = new DataTable();
            string sCmd =" Select B.InventoryID as ID,B.Barcode as Barcode,InventoryName as Name,Description,MainPosition,SubPosition from {0}.Inventory A " +
                        " join {0}.WebOrderPromo B on A.InventoryID = B.InventoryID " +
                        " Where A.Promo = 1 order by MainPosition,SubPosition; ";

            string command = string.Format(sCmd, sDB);
            DT = ObjMain.GetData_DT(command);
            grdPromotionPositioning.DataSource = DT;
            grdPromotionPositioning.DataBind();
        }

        private void LoadInventory(string DB)
        {
            // Prevention SQL Injection : 12-10-21
            // Prevention XSS 
            // Parameterized Approach 

            string sCondition = string.Empty;

            //if(cmbSearchType.Text != "")
            if (cmbSearchType.SelectedItem.Text == "Barcode")
            {
                sCondition = " and Barcode like CONCAT('%',@SearchText,'%')  ";
            }
            else if (cmbSearchType.SelectedItem.Text == "Name")
            {
                sCondition = " and InventoryName like CONCAT('%',@SearchText,'%') ";
            }
            else if (cmbSearchType.SelectedItem.Text == "Description")
            {
                sCondition = " and Description like CONCAT('%',@SearchText,'%') ";
            }

            DataTable DT = new DataTable();
            string sCmd = "Select InventoryID,Barcode,InventoryName as Name,Description from {0}.Inventory where Active <> 0 and ShowItem <> 0 and Promo <> 1 " + sCondition + "";
            string command = string.Format(sCmd, DB);

            MySqlParameter[] parameters =
                   {
                     new MySqlParameter("@SearchText",txtInput.Text.Trim()),
                   };
            DT = ObjMain.NewGetData_DT(command, parameters);
            grdItemList.DataSource = DT;
            grdItemList.DataBind();
            txtInput.Text = "";
            //ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ShowModalItemList();", true);
        }

        private void UpdateInventoryPromoColumn(string DB, string InventoryID, string PromoValue)
        {
            // Prevention SQL Injection  12-10-21
            // Prevention XSS 
            // Parameterized Approach 

            //Promovalue  0 = not promoitem, 1 = promoitem

            string sCmd = "Update {0}.Inventory set Promo=@Promo where InventoryID=@InventoryID ";
            string command = string.Format(sCmd, DB);
            MySqlParameter[] parameters =
                  {
                     new MySqlParameter("@Promo",PromoValue),
                     new MySqlParameter("@InventoryID",InventoryID),
                  };
            iUpdatePromoColumn = ObjMain.ExecuteQuery(command, parameters);
            if (iUpdatePromoColumn > 0)
            {
                if (PromoValue == "1")
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('New Promo Item Successfully Added.');location.href='UpsellingSetting.aspx'", true);
                }
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('Promo Item Successfully Removed.');location.href='UpsellingSetting.aspx'", true);
                }
            }
        }



        public void InsertPromoItem(string DB, string InventoryID, string Barcode) //John added on 16-Aug-2021 Insert WebOrderPromo
        {
            // Prevention SQL Injection  12-10-21
            // Prevention XSS 
            // Parameterized Approach 
            int NewMainPosition = int.Parse(ObjSel.GetLastWebOrderMainPosition(DB)) + 1; //Auto Increment MainPosition(Based on Last MainPostion +  1) SubPosition default = 1
            string InsertWebPromo = "Insert Into {0}.WebOrderPromo(InventoryID,Barcode,MainPosition,SubPosition)" +
                " Values(@InventoryID,@Barcode,@MainPosition,@SubPosition)";
            string command = string.Format(InsertWebPromo, DB);

            MySqlParameter[] parameters =
                  {
                     
                     new MySqlParameter("@InventoryID",InventoryID),
                     new MySqlParameter("@Barcode",Barcode),
                     new MySqlParameter("@MainPosition",NewMainPosition),
                     new MySqlParameter("@SubPosition",1),
                  };

            iInsertWebOrderPromo = ObjMain.ExecuteQuery(command, parameters);
        }

        public void RemovePromoItem(string DB, string InventoryID) //john added on 16-Aug-2021 Remove WebOderPromo
        {
            string RemoveWebPromo = "Delete from {0}.WebOrderPromo where InventoryID =@InventoryID ";
            string command = string.Format(RemoveWebPromo, DB);
            MySqlParameter[] parameters =
                 {
                   new MySqlParameter("@InventoryID",InventoryID),
                 };
            iDeleteWebOrderPromo = ObjMain.ExecuteQuery(command, parameters);
        }


        protected void grdPromotionPositioning_RowCommand(object sender, GridViewCommandEventArgs e)
        {

            if (cmbBranches.SelectedIndex != 0)
            {
                //BranchFullName = Microsoft.Security.Application.Encoder.HtmlEncode(cmbBranches.SelectedItem.Text);    // This will Return Branch FullName 
                //Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);  // This will Return BranchName( Actual Database Name )

                //BranchFullName = cmbBranches.SelectedItem.Text;     // This will Return Branch FullName 
                //Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);
                BranchFullName = Microsoft.Security.Application.Encoder.HtmlEncode(cmbBranches.SelectedItem.Text);    // This will Return Branch FullName 
                Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);  // This will Return BranchName( Actual Database Name )

                if (cmbBranches.Visible == false)
                {
                    BranchAlias = Session["Branch_HQ"].ToString();
                }
                else
                {
                    //BranchFullName = Microsoft.Security.Application.Encoder.HtmlEncode(cmbBranches.SelectedItem.Text);    // This will Return Branch FullName 
                    //Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);  // This will Return BranchName( Actual Database Name )
                    //BranchAlias = Cmb_BranchName;
                    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;
                    }
                }
                if (e.CommandName == "UpdatePosition")
                {
                    int index = Convert.ToInt32(e.CommandArgument);
                    GridViewRow row = grdPromotionPositioning.Rows[index];
                    string lblID = (row.FindControl("lblID") as Label).Text;
                    string lblBarcode = (row.FindControl("lblBarcode") as Label).Text;
                    string lblName = (row.FindControl("lblName") as Label).Text;
                    string lblDescription = (row.FindControl("lblDescription") as Label).Text;
                    string txtMainPosition = (row.FindControl("txtMainPosition") as TextBox).Text;
                    string txtSubPosition = (row.FindControl("txtSubPosition") as TextBox).Text;

                    //Update da1.WebOrderPromo set MainPosition = 1 ,SubPosition = 1 where barcode = 'A05';
                    string sCmd = "Update {0}.WebOrderPromo set MainPosition=@MainPosition ,SubPosition=@SubPosition where barcode=@barcode  ;";
                    string command = string.Format(sCmd, BranchAlias);

                    MySqlParameter[] parameters =
                     {
                       new MySqlParameter("@MainPosition",txtMainPosition.ToString()),
                       new MySqlParameter("@SubPosition",txtSubPosition.ToString()),
                       new MySqlParameter("@barcode",lblBarcode.ToString()),
                    };
                    iUpdatePromoPosition = ObjMain.ExecuteQuery(command,parameters);
                    if (iUpdatePromoPosition > 0)
                    {
                        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Promo Product Position Updated');location.href='UpsellingSetting.aspx'", true);
                    }

                }
                else if (e.CommandName == "Removeitem")
                {
                    int index = Convert.ToInt32(e.CommandArgument);
                    GridViewRow row = grdPromotionPositioning.Rows[index];
                    string lblID = (row.FindControl("lblID") as Label).Text;
                    string lblBarcode = (row.FindControl("lblBarcode") as Label).Text;
                    string lblName = (row.FindControl("lblName") as Label).Text;
                    string lblDescription = (row.FindControl("lblDescription") as Label).Text;
                    string txtMainPostion = (row.FindControl("txtMainPosition") as TextBox).Text;
                    string txtSubPostion = (row.FindControl("txtSubPosition") as TextBox).Text;

                    UpdateInventoryPromoColumn(BranchAlias, lblID.ToString(), "0"); //Update Inventory table Promo Column to 0
                    RemovePromoItem(BranchAlias, lblID.ToString());  //Delete Inventory in WebOrderPromo table

                }
            }
        }

        protected void grdPromotionPositioning_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            //string RetVal = string.Empty;
            //if (e.Row.RowType == DataControlRowType.DataRow)
            //{
            //    //Find the DropDownList in the Row
            //    Label sIniID = (e.Row.FindControl("IDIndex") as Label);
            //    //DropDownList ddlOption = (e.Row.FindControl("cmbShow") as DropDownList);
            //    TextBox sIniValue = (e.Row.FindControl("txtIniValue") as TextBox);

            //    if (cmbBranches.SelectedIndex != 0)
            //    {
            //        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 )
            //        RetVal = ObjSel.GetIniSettingValue(Cmb_BranchName, sIniID.Text);
            //        sIniValue.Text = RetVal;
            //    }
            //}
        }


        protected void btnAddPromoItem_Click(object sender, EventArgs e)
        {
            BranchFullName = Microsoft.Security.Application.Encoder.HtmlEncode(cmbBranches.SelectedItem.Text);    // This will Return Branch FullName 
            Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);  // This will Return BranchName( Actual Database Name )
            
            if (cmbBranches.Visible == false)
            {
                BranchAlias = Session["Branch_HQ"].ToString();
            }
            else
            {
                //BranchFullName = Microsoft.Security.Application.Encoder.HtmlEncode(cmbBranches.SelectedItem.Text);    // This will Return Branch FullName 
                //Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);  // This will Return BranchName( Actual Database Name )
                //BranchAlias = Cmb_BranchName;
                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;
                }
            }

            if (grdItemList.Rows.Count > 0)
            {
                foreach (GridViewRow row in grdItemList.Rows)
                {
                    Label InventoryID = (Label)row.FindControl("lblInventoryID");
                    Label Barcode = (Label)row.FindControl("lblBarCode");
                    Label Name = (Label)row.FindControl("lblName");
                    Label Descrription = (Label)row.FindControl("lblDescription");
                    CheckBox chk = (CheckBox)row.FindControl("chkSelect");

                    if (chk.Checked == true)
                    {
                        UpdateInventoryPromoColumn(BranchAlias, Microsoft.Security.Application.Encoder.HtmlEncode(InventoryID.Text), "1");
                        InsertPromoItem(BranchAlias, Microsoft.Security.Application.Encoder.HtmlEncode(InventoryID.Text), Microsoft.Security.Application.Encoder.HtmlEncode(Barcode.Text));
                    }
                }
            }
        }

        protected void btnApplySearch_Click(object sender, EventArgs e)
        {
            BranchFullName = Microsoft.Security.Application.Encoder.HtmlEncode(cmbBranches.SelectedItem.Text);    // This will Return Branch FullName 
            Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);  // This will Return BranchName( Actual Database Name )

            if (cmbBranches.Visible == false)
            {
                BranchAlias = Session["Branch_HQ"].ToString();
            }
            else
            {
                //BranchFullName = Microsoft.Security.Application.Encoder.HtmlEncode(cmbBranches.SelectedItem.Text);    // This will Return Branch FullName 
                //Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);  // This will Return BranchName( Actual Database Name )
                //BranchAlias = Cmb_BranchName;
                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;
                }
            }

            BranchFullName = Microsoft.Security.Application.Encoder.HtmlEncode(cmbBranches.SelectedItem.Text);    // This will Return Branch FullName 
            Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);  // This will Return BranchName( Actual Database Name )
            LoadInventory(BranchAlias);
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ShowModalItemList();", true);
        }
    }
}