using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections;
using System.Web;
using System.IO;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using System.Configuration;
using MySql.Data.MySqlClient;
using MySql.Data;
using CLS_BL;
using CLS_DL;
using CLS_PL;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
using System.Web.UI.DataVisualization.Charting;
using System.Drawing.Printing;
using System.Drawing;
using System.Drawing.Text;
namespace SUNWEB
{
    public partial class GroupSale : System.Web.UI.Page
    {
        BL_SELECT ObjSel = new BL_SELECT();
        BLCompany ObjBL = new BLCompany();
        PLCOMMON ObjPL = new PLCOMMON();
        BL_USER ObjUserBL = new BL_USER(); //This Object for All User and Page Related fuctions included 
        PLCUSTOMER ObjCustPL = new PLCUSTOMER();
        Int32 K = 0;
        Int32 L = 0;
        Int32 S = 0;
        string ConStr = ConfigurationManager.ConnectionStrings["ConMysql"].ConnectionString;
        string ConStr_Rds = ConfigurationManager.ConnectionStrings["ConRDS"].ConnectionString;
        string Curr_Date = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        string Curr_DateOnly = System.DateTime.Now.ToString("yyyy-MM-dd");
        DateTime MonthstartDt;
        DataSet ds = new DataSet();
        MYSQLDB ObjMain = new MYSQLDB();
        DataTable DT = new DataTable();
        DataTable Dt1 = 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();
        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;
        string PID = string.Empty;   // License Variables ..
        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_GroupSale = string.Empty;
        string BranchFullName = string.Empty;
        string Curr_BranchFullName = string.Empty;
        string Cmb_BranchName = string.Empty;
        string Branchidval = string.Empty;
        string BraNam = "";
        string FDate = "";
        string TDate = "";
        string HQ = string.Empty;
        string Cm_id = string.Empty;
        string ISHQ = string.Empty;

        DataTable  DtExcel = new DataTable();
        protected void Page_Load(object sender, EventArgs e)
        {
            PID = "8";                      // This is For GroupSale
            MySqlConnection Cn = new MySqlConnection(ConStr_Rds);
            Cn.Open();
            if (!IsPostBack)
            {
                txtFromDt.Text = Curr_DateOnly;
                txtToDt.Text = Curr_DateOnly;
            }
            if (Session["UserName"] == null)
            {
                Response.Redirect("Login.aspx");
            }
            MonthstartDt = new DateTime(System.DateTime.Now.Year, System.DateTime.Now.Month, 1);


            //if (!IsPostBack)
            //{
            //    //LoadGrid();
            //    BraNam = "rasa1";
            //    FDate = txtFromDt.Text;
            //    TDate = txtToDt.Text;
            //    LoadGroupSalesMainQuery("rasa1", txtFromDt.Text, txtToDt.Text);
            //}
            if (((Convert.ToBoolean(Session["IsSuperAdmin"])) == true) && (Session["PortalTypeId"].ToString() == "") && ((Convert.ToBoolean(Session["IsMultiBranch"])) == true))
            {
                if (!IsPostBack)
                {
                    LoadBranchName4SuperAdmin();

                    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();
                }
                cd_BranchAlias = cmbBranches.SelectedItem.Text;
                BraNam = cd_BranchAlias;
                FDate = txtFromDt.Text;
                TDate = txtToDt.Text;
                LoadGroupSalesMainQuery(cd_BranchAlias, Microsoft.Security.Application.Encoder.HtmlEncode(txtFromDt.Text), Microsoft.Security.Application.Encoder.HtmlEncode(txtToDt.Text));
            }
            else if (((Convert.ToBoolean(Session["IsMultiBranch"])) == true) && (Session["PortalTypeId"].ToString() == ""))
            {
                if (!IsPostBack)
                {
                    LoadBranchName();
                    ActiveCall();
                }
            }
            else if (((Session["PortalTypeId"].ToString() != "") || (Convert.ToBoolean(Session["IsSuperAdmin"])) == false) && ((Convert.ToBoolean(Session["IsMultiBranch"])) == false))
            {
                cmbBranches.Enabled = false;
                cmbBranches.Visible = false;

                Cm_id = ObjSel.GETcmid(Session["Cd_Id"].ToString());  // Get cm_id
                HQ = ObjSel.Get_HQ(Cm_id);     // Get the HQ Value
                Curr_BranchFullName = ObjSel.GetBranchFullName(HQ, Session["Branch_HQ"].ToString());
                lblBranchAliasName.ForeColor = System.Drawing.Color.DodgerBlue;
                lblBranchAliasName.Text = "&nbsp;" + "-" + "&nbsp;" + Curr_BranchFullName + "&nbsp; ";
                cd_BranchAlias = Session["Branch_HQ"].ToString();
                Datapath = Session["DataPath"].ToString();
                PortalTypeId = Session["PortalTypeId"].ToString();
                PID = "8"; //  This is for ItemSale 
                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_GroupSale"].ToString() == "N") || (Session["Page_Acess"].ToString() == "N"))
                {
                    Response.Redirect("DeniedPage.aspx", false);
                }
                else
                {
                    // XSS Attack Prevention 
                    string StartDT = Microsoft.Security.Application.Encoder.HtmlEncode(txtFromDt.Text);
                    string EndDt = Microsoft.Security.Application.Encoder.HtmlEncode(txtFromDt.Text);



                    lblMsgTotalSelection.Text = " Search Result - Group Sales Report  Between" + "&nbsp;&nbsp;&nbsp;&nbsp;" + StartDT.Trim() + "&nbsp;&nbsp;&nbsp;  And &nbsp;&nbsp;&nbsp;" + EndDt.Trim();
                    if (!IsPostBack)
                    {
                        if (Session["Isdowld_Acess"].ToString() == "N")
                        {
                            // btnExcel.Enabled = false;
                            Response.Write(@"<script language='javascript'>alert('No Access To download.')</script>");
                        }
                        else
                        {
                            btnGenerate.Visible = true;
                            //btnExcel.Enabled = true;
                            if (cmbBranches.Visible == false)
                            {

                                LoadGroupSalesMainQuery(Session["Branch_HQ"].ToString(), StartDT.Trim(), EndDt.Trim());
                            }

                        }
                    }
                }
            }
            else
            {

            }
        }
        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 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 ActiveCall()
        {
            string QueryCal = "select ActiveValue from portaldb.usermaster  where Userid=" + Session["UserId"].ToString() + " ";
            ActiveCallvalue = ObjMain.ExecuteScalar(QueryCal);
            if (ActiveCallvalue == "")
            {
                ActiveCallvalue = ObjSel.GetFirstBranch7(Session["Branch_HQ"].ToString(), Session["UserId"].ToString());
            }


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

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

            cd_BranchAlias = 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 (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_GroupSale = DtLicense.Rows[0]["GROUPSALE"].ToString();
                Session["L_GroupSale"] = L_GroupSale;
            }
            if (Session["L_GroupSale"].ToString() == "N" || Session["Page_Acess"].ToString() == "N")
            {
                Response.Redirect("DeniedPage.aspx", false);
            }
            else
            {
                #region Write(Button click ) & download rights ...

                if (Session["Write_Acess"].ToString() == "N")
                {
                    btnGenerate.Enabled = false;
                }
                if (Session["Isdowld_Acess"].ToString() == "N")
                {
                    btnExcel.Enabled = false;
                }
                #endregion



                // XSS Attack Prevention 
                string StartDT = Microsoft.Security.Application.Encoder.HtmlEncode(txtFromDt.Text);
                string EndDt = Microsoft.Security.Application.Encoder.HtmlEncode(txtFromDt.Text);


                //btnExcel.Enabled = true;
                lblMsgTotalSelection.Text = "Search Result - Group Sales Report Between" + "&nbsp;&nbsp;&nbsp;" + StartDT.Trim() + "&nbsp;&nbsp;&nbsp;  And &nbsp;&nbsp;&nbsp;" + EndDt.Trim();
                BraNam = cd_BranchAlias;
                FDate = txtFromDt.Text;
                TDate = txtToDt.Text;
                LoadGroupSalesMainQuery(cd_BranchAlias, StartDT.Trim(), EndDt.Trim());
                //BindGridview(ActiveCallvalue, txtStartDt.Text, txtEndDt.Text);
                System.Threading.Thread.Sleep(2000);
            }
        }
        protected void cmbBranches_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbBranches.SelectedIndex == 0)
            {
                Response.Redirect("GroupSale.aspx", false);
            }
            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;
                }

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

                if (ISHQ != "")
                {
                    ActiveCallvalue = ObjSel.GetFirstBranch(Session["Branch_HQ"].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_GroupSale = DtLicense.Rows[0]["GROUPSALE"].ToString();
                    Session["L_GroupSale"] = L_GroupSale;
                }
                if (Session["L_GroupSale"].ToString() == "N" || Session["Page_Acess"].ToString() == "N")
                {
                    Response.Redirect("DeniedPage.aspx", false);
                }
                else
                {

                    #region Write(Button click ) & download rights ...

                    if (Session["Write_Acess"].ToString() == "N")
                    {
                        btnGenerate.Enabled = false;
                    }
                    if (Session["Isdowld_Acess"].ToString() == "N")
                    {
                        btnExcel.Enabled = false;
                    }
                    #endregion


                    // XSS Attack Prevention 
                    string StartDT = Microsoft.Security.Application.Encoder.HtmlEncode(txtFromDt.Text);
                    string EndDt = Microsoft.Security.Application.Encoder.HtmlEncode(txtFromDt.Text);

                    //btnExcel.Enabled = true;
                    //lblMsgTotalSelection.Text = "Group Sales Report Between" + "&nbsp;&nbsp;&nbsp;" + txtFromDt.Text + "&nbsp;&nbsp;&nbsp;  And &nbsp;&nbsp;&nbsp;" + txtToDt.Text;
                    lblMsgTotalSelection.Text = " Search Result - Group Sales Report Between" + "&nbsp;&nbsp;&nbsp;" + StartDT.Trim() + "&nbsp;&nbsp;&nbsp;  And &nbsp;&nbsp;&nbsp;" + EndDt.Trim();
                    cd_BranchAlias = Cmb_BranchName;
                    BraNam = cd_BranchAlias;
                    FDate = txtFromDt.Text;
                    TDate = txtToDt.Text;
                    LoadGroupSalesMainQuery(Microsoft.Security.Application.Encoder.HtmlEncode(cd_BranchAlias), StartDT.Trim(), EndDt.Trim());
                    //BindGridview(cd_BranchAlias, txtStartDt.Text, txtEndDt.Text);
                }
            }
            UPDATEBRANCH(Cmb_BranchName);
        }
        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", false);
            }
        }

        //from here onwards report code begins
        protected void btnGenerate_Click(object sender, EventArgs e)
        {

            // XSS Attack Prevention 
            string StartDT = Microsoft.Security.Application.Encoder.HtmlEncode(txtFromDt.Text);
            string EndDt = Microsoft.Security.Application.Encoder.HtmlEncode(txtToDt.Text);


            if (cmbBranches.Visible == false)
            {
                btnGenerate.Visible = true;
                lblMsgTotalSelection.Text = "Search Result - Group Sales Report Between" + "&nbsp;&nbsp;&nbsp;" + StartDT.Trim() + "&nbsp;&nbsp;&nbsp;  And &nbsp;&nbsp;&nbsp;" + EndDt.Trim();
                LoadGroupSalesMainQuery(Session["Branch_HQ"].ToString(), StartDT.Trim(), EndDt.Trim());
                System.Threading.Thread.Sleep(2000);
            }
            else if (cmbBranches.Visible == true)
            {
                lblMsgTotalSelection.Text = "Search Result - Group Sales Report Between" + "&nbsp;&nbsp;&nbsp;" + StartDT.Trim() + "&nbsp;&nbsp;&nbsp;  And &nbsp;&nbsp;&nbsp;" + EndDt.Trim();
                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;
                FDate = txtFromDt.Text;
                TDate = txtToDt.Text;
                LoadGroupSalesMainQuery(cd_BranchAlias, StartDT.Trim(), EndDt.Trim());
            }
        }
        protected void LoadGroupSalesMainQuery(string BranchAlias, string D1, string D2)
        {
            System.Threading.Thread.Sleep(1000);

            string sCmd;
            sCmd = "Select 'Group1' as GroupName,if(isnull(sum(b.qty)),0,sum(b.qty)) as Qty,Format(if(isnull(sum(b.Amount)),0.00,sum(b.Amount)),2) as TotalAmount" +
                " From {0}.Trans a " +
                " Join {0}.transdetail b on a.transid=b.transid " +
                " Where date(businessdate) between  @D1  and  @D2    and transstatus in (2,3,4) and " +
                " b.itemstatus = 0 and  Group1<>'' " +
                " Union " +
                " Select 'Group2' as GroupName,if(isnull(sum(b.qty)),0,sum(b.qty)) as Qty,Format(if(isnull(sum(b.Amount)),0.00,sum(b.Amount)),2) as TotalAmount " +
                " From {0}.Trans a " +
                " Join {0}.transdetail b on a.transid=b.transid" +
                " Where date(businessdate) between @D1  and  @D2   and transstatus in (2,3,4) and" +
                " b.itemstatus = 0 and  Group2<>''" +
                " Union" +
                " Select 'Group3' as GroupName,if(isnull(sum(b.qty)),0,sum(b.qty)) as Qty,Format(if(isnull(sum(b.Amount)),0.00,sum(b.Amount)),2) as TotalAmount " +
                " From {0}.Trans a " +
                " Join {0}.transdetail b on a.transid=b.transid" +
                " Where date(businessdate) between @D1  and  @D2   and transstatus in (2,3,4) and" +
                " b.itemstatus = 0 and  Group3<>''" +
                " Union" +
                " Select 'Group4' as GroupName,if(isnull(sum(b.qty)),0,sum(b.qty)) as Qty,Format(if(isnull(sum(b.Amount)),0.00,sum(b.Amount)),2) as TotalAmount " +
                " From {0}.Trans a" +
                " Join {0}.transdetail b on a.transid=b.transid" +
                " Where date(businessdate) between @D1  and  @D2   and transstatus in (2,3,4) and" +
                " b.itemstatus = 0 and  Group4<>''" +
                " Union" +
                " Select 'Group5' as GroupName,if(isnull(sum(b.qty)),0,sum(b.qty)) as Qty,Format(if(isnull(sum(b.Amount)),0.00,sum(b.Amount)),2) as TotalAmount " +
                " From {0}.Trans a" +
                " Join {0}.transdetail b on a.transid=b.transid" +
                " Where date(businessdate) between @D1  and  @D2   and transstatus in (2,3,4) and " +
                " b.itemstatus = 0 and  Group5<>''";
            string command = string.Format(sCmd, BranchAlias);
            MySqlParameter[] parameters =
                   {
                     new MySqlParameter("@D1",D1),
                     new MySqlParameter("@D2",D2),
                    };
            Dt1 = ObjMain.NewGetData_DT(command, parameters);

            GridView1.DataSource = Dt1;
            //gridview totals
            int totalQty = 0;
            double totalAmount = 0;
            foreach (DataRow dr in Dt1.Rows)
            {
                totalQty += Convert.ToInt32(dr["Qty"]);
                totalAmount += Convert.ToDouble(dr["TotalAmount"]);
            }
            GridView1.Columns[2].FooterText = totalQty.ToString();
            GridView1.Columns[3].FooterText = totalAmount.ToString("#,##0.00");
            GridView1.DataBind();
        }
        protected void gv_RowDataBound(object sender, GridViewRowEventArgs e)
        {

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

            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                MySqlConnection Cn = new MySqlConnection(ConStr_Rds);
                Cn.Open();
                GridView gv = (GridView)e.Row.FindControl("GridView2");
                Dt2.Clear();
                string sCmd;
                sCmd = "Select  B." + ((DataRowView)e.Row.DataItem)["GroupName"].ToString() + " as GroupNam,sum(Qty) as Qty," +
                //" Format(sum(b.TaxAmount1+b.TaxAmount2+b.TaxAmount3+b.TaxAmount4+b.TaxAmount5+b.TaxAmount6+TaxableAmount),2) as TotalAmount" +
                " Format(sum(B.Amount),2) as TotalAmount" +
                " From {0}.Trans A" +
                " Join {0}.transdetail B on A.TransID = B.TransID" +
                " Join {0}.inventorycategories C on B.CategoryNumber = C.Categorynumber" +
                " Where date(businessdate)  between  @FDate  and  @TDate    and B.Itemstatus = 0" +
                " And A.Transstatus in (2,3,4) and " + ((DataRowView)e.Row.DataItem)["GroupName"].ToString() + "<>''" +
                //" Group by Group1 order by Qty desc"; //john hide on 10-March-2021
                " Group by " + ((DataRowView)e.Row.DataItem)["GroupName"].ToString() + " order by Qty desc"; //John added on 10-March-2021 Make group by group dynamic


                string command = string.Format(sCmd, BraNam);

                MySqlParameter[] parameters =
                   {
                     new MySqlParameter("@FDate",FDate),
                     new MySqlParameter("@TDate",TDate),
                    };

                Dt2 = ObjMain.NewGetData_DT(command, parameters);

                gv.DataSource = Dt2;
                gv.DataBind();
            }
        }

        protected void btnExcel_Click(object sender, EventArgs e)
         {

            // XSS Prevention  : 30-09-21 

            string StartDT = Microsoft.Security.Application.Encoder.HtmlEncode(txtFromDt.Text);
            string EndDt = Microsoft.Security.Application.Encoder.HtmlEncode(txtToDt.Text);


            cd_BranchAlias = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), cmbBranches.SelectedItem.Text.Trim());

            //string sCmd = "SELECT ID, EmployeeNumber, EmployeeName, InTime, OutTime, WorkTime, DaybyWorkTime FROM {0}.timeinoutrecord;";
            string sCmd = "Select  'Group1' as GroupHeader, B.Group1 as GroupName,sum(Qty) as Qty,Format(sum(b.Amount),2) as TotalAmount " +
                            " From {0}.Trans A Join {0}.transdetail B on A.TransID = B.TransID Join {0}.inventorycategories C on B.CategoryNumber = C.Categorynumber " +
                            " Where date(businessdate)  between  @StartDT  and  @EndDt    and B.Itemstatus = 0 And A.Transstatus in (2, 3, 4) and Group1<>'' " +
                            " Group by Group1 " +
                            " UNION " +
                            " Select  'Group2' as GroupHeader, B.Group2 as GroupName,sum(Qty) as Qty,Format(sum(b.Amount), 2) as TotalAmount " +
                            " From {0}.Trans A Join {0}.transdetail B on A.TransID = B.TransID Join {0}.inventorycategories C on B.CategoryNumber = C.Categorynumber" +
                            " Where date(businessdate)  between  @StartDT  and  @EndDt    and B.Itemstatus = 0 And A.Transstatus in (2, 3, 4) and Group2<>''" +
                            " Group by Group2 " +
                            " UNION" +
                            " Select  'Group3' as GroupHeader, B.Group3 as GroupName,sum(Qty) as Qty,Format(sum(b.Amount), 2) as TotalAmount " +
                            " From {0}.Trans A Join {0}.transdetail B on A.TransID = B.TransID Join {0}.inventorycategories C on B.CategoryNumber = C.Categorynumber" +
                            " Where date(businessdate)  between  @StartDT  and  @EndDt    and B.Itemstatus = 0 And A.Transstatus in (2, 3, 4) and Group3<>''" +
                            " Group by Group3" +
                            " UNION" +
                            " Select  'Group4' as GroupHeader, B.Group4 as GroupName,sum(Qty) as Qty,Format(sum(b.Amount), 2) as TotalAmount" +
                            " From {0}.Trans A Join {0}.transdetail B on A.TransID = B.TransID Join {0}.inventorycategories C on B.CategoryNumber = C.Categorynumber" +
                            " Where date(businessdate)  between  @StartDT  and  @EndDt    and B.Itemstatus = 0 And A.Transstatus in (2, 3, 4) and Group4<>''" +
                            " Group by Group4" +
                            " UNION " +
                            " Select  'Group5' as GroupHeader, B.Group5 as GroupName,sum(Qty) as Qty,Format(sum(b.Amount), 2) as TotalAmount" +
                            " From {0}.Trans A Join {0}.transdetail B on A.TransID = B.TransID Join {0}.inventorycategories C on B.CategoryNumber = C.Categorynumber" +
                            " Where date(businessdate)  between  @StartDT  and  @EndDt    and B.Itemstatus = 0 And A.Transstatus in (2, 3, 4) and Group5<>''" +
                            " Group by Group5" +
                            " Order by 1,3 desc; ";

            // Prevent the SQL Injections
            // Parameterized Approach 


            string command = string.Format(sCmd, cd_BranchAlias);
            //MySqlParameter[] parameters = { };
            MySqlParameter[] parameters =
                 {
                          new MySqlParameter("@StartDT",StartDT.Trim()),
                          new MySqlParameter("@EndDt",EndDt.Trim())
                         };
            DtExcel = ObjMain.NewGetData_DT(command, parameters);



         
            GridView GridView3 = new GridView();
            GridView3.AllowPaging = false;
            GridView3.DataSource = DtExcel;
            GridView3.DataBind();
            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition",
                "attachment;filename=GroupSale.xls");
            Response.Charset = "";
            Response.ContentType = "application/vnd.ms-excel";
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            for (int i = 0; i < GridView3.Rows.Count; i++)
            {
                GridView3.Rows[i].Attributes.Add("class", "textmode");
            }
            GridView3.RenderControl(hw);
            string style = @"<style> td { mso-number-format:\@; } </style>";
            Response.Write(style);
            Response.Output.Write(sw.ToString());
            Response.Flush();
            Response.End();



            /*
            //Build the CSV file data as a Comma separated string.
            string csv = string.Empty;

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

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

            foreach (DataRow row in DtExcel.Rows)
            {
                foreach (DataColumn column in DtExcel.Columns)
                {
                    //Add the Data rows.
                    csv += row[column.ColumnName].ToString().Replace(",", ";") + ',';
                }

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

            //Download the CSV file.
            Response.Clear();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment;filename=GroupSale.csv");
            Response.Charset = "utf8";
            Response.ContentType = "application/text";
            


            Response.Output.Write(csv);

            Response.Flush();
            Response.End();
            */







        }

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