using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using System.IO;
using System.Configuration;
using MySql.Data.MySqlClient;
using MySql.Data;
using CLS_BL;
using CLS_DL;
using CLS_PL;
using System.Web.UI.DataVisualization.Charting;
using InfoSoftGlobal;
using System.Drawing.Printing;
using System.Drawing;
using System.Drawing.Text;


namespace SUNWEB
{
    public partial class HourlySale : 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");
        string YearAlone = DateTime.Now.Year.ToString();
        string Monthid = DateTime.Now.Month.ToString();
        DateTime MonthstartDt;
        MYSQLDB ObjMain = new MYSQLDB();
        MYSQLCLOUD ObjMainCloud = new MYSQLCLOUD();
        string ActiveCallvalue = string.Empty;
        DataTable DT = new DataTable();
        DataTable Dt2 = new DataTable();
        DataTable DtLicense = new DataTable();
        DataTable Dtt = new DataTable();
        DataTable DtLinechart = new DataTable();
        DataTable ReadResult = new DataTable();
        // DataTable Dt_View = new DataTable();
        StringBuilder str = new StringBuilder();

        // 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 Cd_BranchName = string.Empty;
        string Rcd_id = string.Empty;
        string RPortalid = 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;
        //// Others
        string Branchidval = string.Empty;
        string Useridvalue = string.Empty;
        string QueryCurr_Select = string.Empty;
        string BranchFullName = string.Empty;
        string Curr_BranchFullName = string.Empty;
        string Cmb_BranchName = string.Empty;
        string ISHQ = string.Empty;


        // Chart Variables : 
        DataTable dt = new DataTable("Chart");
        string X, Y;
        string GraphWidth = "850";
        string GraphHeight = "390";
        string[] color = new string[25];

        // Time Group Amount Variable : 
        // Time Group 00  
        string Tm0;
        string Amt0;

        // Time Group 01 
        string Tm1;
        string Amt1;

        // Time Group 02
        string Tm2;
        string Amt2;

        // Time Group 03
        string Tm3;
        string Amt3;


        // Time Group 04
        string Tm4;
        string Amt4;

        // Time Group 05
        string Tm5;
        string Amt5;

        // Time Group 06
        string Tm6;
        string Amt6;
        // Time Group 07
        string Tm7;
        string Amt7;

        // Time Group 08
        string Tm8;
        string Amt8;
        // Time Group 09
        string Tm9;
        string Amt9;

        // Time Group 10
        string Tm10;
        string Amt10;

        // Time Group 11
        string Tm11;
        string Amt11;
        // Time Group 12
        string Tm12;
        string Amt12;
        // Time Group 13
        string Tm13;
        string Amt13;
        // Time Group 14
        string Tm14;
        string Amt14;

        // Time Group 15
        string Tm15;
        string Amt15;
        // Time Group 16
        string Tm16;
        string Amt16;

        // Time Group 17
        string Tm17;
        string Amt17;

        // Time Group 18
        string Tm18;
        string Amt18;
        // Time Group 19
        string Tm19;
        string Amt19;

        // Time Group 20
        string Tm20;
        string Amt20;
        // Time Group 21
        string Tm21;
        string Amt21;

        // Time Group 22
        string Tm22;
        string Amt22;
        // Time Group 23
        string Tm23;
        string Amt23;

        string RTimeGroupValue;
        string RAmount;

        string L_MaxUserCnt = string.Empty;
        string L_RetailDashboard = string.Empty;
        string L_SummarySales = string.Empty;
        string L_ItemSales = string.Empty;
        string L_TaxAnalysis = string.Empty;
        string L_TopSale = string.Empty;
        string L_MothlySales = string.Empty;
        string L_HourlySales = string.Empty;
        string L_GroupSale = string.Empty;
        string HQ = string.Empty;
        string Cm_id = string.Empty;

        //  Global Variable for Reports 
        string currentId = string.Empty;
        decimal subTotal = 0;
        int total = 0;
        decimal Totamt = 0;
        decimal SubTotAmt = 0;
        decimal TotDisamt = 0;
        decimal SubDisamt = 0;
        int subTotalRowIndex = 0;
        int subTotalRowIndex1 = 0;


        protected void Page_Load(object sender, EventArgs e)
        {
             PID = "7";                       // This is For RetailsDashboard 

            if (!IsPostBack)
            {
                txtStartDt.Text = Curr_DateOnly;
                txtEndDt.Text = Curr_DateOnly;
                //System.Threading.Thread.Sleep(2000);

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

                    System.Threading.Thread.Sleep(2000);
                    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["IsMultiBranch"])) == true) && (Session["PortalTypeId"].ToString() == ""))
            {
                if (!IsPostBack)
                {
                    System.Threading.Thread.Sleep(2000);
                    LoadBranchName();
                    string QueryCal = "select ActiveValue from portaldb.usermaster  where Userid=" + Session["UserId"].ToString() + " ";
                    ActiveCallvalue = ObjMain.ExecuteScalar(QueryCal);

                    if (ActiveCallvalue != " " || ActiveCallvalue != "Select Branch")
                    {
                        ActiveCall();

                    }

                }

            }

            else if (((Session["PortalTypeId"].ToString() != "") || (Convert.ToBoolean(Session["IsSuperAdmin"])) == false) && ((Convert.ToBoolean(Session["IsMultiBranch"])) == false))
            {
                // XSS Attack Prevention 
                string StartDT = Microsoft.Security.Application.Encoder.HtmlEncode(txtStartDt.Text);
                string EndDt = Microsoft.Security.Application.Encoder.HtmlEncode(txtEndDt.Text);


                // Response.Redirect("SummaryReport.aspx");
                cmbBranches.Enabled = false;
                cmbBranches.Visible = false;
                btnGetReports.Visible = true;

                Cm_id = ObjSel.GETcmid(Session["Cd_Id"].ToString());  // Get cm_id
                HQ = ObjSel.Get_HQ(Cm_id);     // Get the HQ Value
                Curr_BranchFullName = ObjSel.GetBranchFullName(HQ, Session["Branch_HQ"].ToString());
                lblBranchAliasName.ForeColor = System.Drawing.Color.DodgerBlue;
                lblBranchAliasName.Text = "&nbsp;&nbsp;" + Curr_BranchFullName + "&nbsp; !";
                cd_BranchAlias = Session["Branch_HQ"].ToString();
                Datapath = Session["DataPath"].ToString();
                PortalTypeId = Session["PortalTypeId"].ToString();
                DT = ObjUserBL.GetPageRightsDetailsPid(Session["UserId"].ToString(), PID);
                if (DT.Rows.Count > 0)
                {
                    Page_Acess = DT.Rows[0]["Acess_status"].ToString();
                    Read_Acess = DT.Rows[0]["Read_Access"].ToString();
                    Write_Acess = DT.Rows[0]["Write_Access"].ToString();
                    Isdowld_Acess = DT.Rows[0]["IDwld_Access"].ToString();

                    Session["Page_Acess"] = Page_Acess;
                    Session["Read_Acess"] = Read_Acess;
                    Session["Write_Acess"] = Write_Acess;
                    Session["Isdowld_Acess_7"] = Isdowld_Acess;

                    ConfigureColors();
                    CreateBarGraph(Session["Branch_HQ"].ToString(), StartDT.Trim(), EndDt.Trim());  // Calling Graph Function
                    //lblMsgTotalSelection.Text = " HOURLY SALES REPORTS COMPARISION  BETWEEN" + " &nbsp;&nbsp; " + txtStartDt.Text + "&nbsp;&nbsp;&nbsp;  And &nbsp;&nbsp;&nbsp;" + txtEndDt.Text;
                    lblMsgTotalSelection.Text = " Search Result - from" + " &nbsp;&nbsp; " + StartDT.Trim() + "&nbsp;&nbsp; to &nbsp;&nbsp;" + EndDt.Trim();
                    idGenReport.Attributes.Add("style", "background-color: #4c4c4c; color: White;font-size:14px;");
                    //Label1.Text = " HOURLY SALES REPORTS  BETWEEN" + "&nbsp; &nbsp;" + txtStartDt.Text + "&nbsp;&nbsp;&nbsp;  And &nbsp;&nbsp;&nbsp;" + txtEndDt.Text;
                    Label1.Text = " Search Result - from" + "&nbsp;&nbsp;" + StartDT.Trim() + "&nbsp;&nbsp; to &nbsp;&nbsp;" + EndDt.Trim();
                    idHourly.Attributes.Add("style", "background-color: #4c4c4c; color: White;font-size:14px;");
                    BindGrid(Session["Branch_HQ"].ToString(), StartDT.Trim(), EndDt.Trim());
                    System.Threading.Thread.Sleep(2000);

                }

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

                }

            }
            else
            {

            }
            {

            }

            if (Session["UserName"] == null)
            {
                Response.Redirect("Login.aspx");
            }

        }
        /// <summary>
        ///  This Function Uses To Update Current Branch Selction In Dropdown
        ///  Every Page Read the  'ActiveValue' Value and Bind it .
        /// </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 ActiveCall()
        {

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


            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_7"] = 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_HourlySales = DtLicense.Rows[0]["HOURLYSALE"].ToString();
                Session["L_HourlySales"] = L_HourlySales;
            }

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

            else
            {


                ConfigureColors();
                CreateBarGraph(Cmb_BranchName, StartDT.Trim(), EndDt.Trim());  // Calling Graph Function
                //lblMsgTotalSelection.Text = " HOURLY SALES REPORTS COMPARISION  BETWEEN" + " &nbsp;&nbsp; " + txtStartDt.Text + "&nbsp;&nbsp;&nbsp;  And &nbsp;&nbsp;&nbsp;" + txtEndDt.Text;
                //Label1.Text = " HOURLY SALES REPORTS  BETWEEN" + "&nbsp; &nbsp;" + txtStartDt.Text + "&nbsp;&nbsp;&nbsp;  And &nbsp;&nbsp;&nbsp;" + txtEndDt.Text;
                lblMsgTotalSelection.Text = " Search Result - from" + " &nbsp;&nbsp; " + StartDT.Trim() + "&nbsp;&nbsp; to &nbsp;&nbsp;" + EndDt.Trim();
                idGenReport.Attributes.Add("style", "background-color: #4c4c4c; color: White;font-size:14px");
                Label1.Text = " Search Result - from" + "&nbsp;&nbsp;" + StartDT.Trim() + "&nbsp;&nbsp; to &nbsp;&nbsp;" + EndDt.Trim();
                idHourly.Attributes.Add("style", "background-color: #4c4c4c; color: White;font-size:14px;");
                BindGrid(Cmb_BranchName, StartDT.Trim(), EndDt.Trim());
                BindChart();
                System.Threading.Thread.Sleep(2000);

            }



        }


        protected void cmbBranches_SelectedIndexChanged(object sender, EventArgs e)
        {
            // XSS Attack Prevention 
            string StartDT = Microsoft.Security.Application.Encoder.HtmlEncode(txtStartDt.Text);
            string EndDt = Microsoft.Security.Application.Encoder.HtmlEncode(txtEndDt.Text);

            System.Threading.Thread.Sleep(1000);
            if (cmbBranches.SelectedIndex == 0)
            {
                Response.Redirect("HourlySale.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_7"] = 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_HourlySales = DtLicense.Rows[0]["HOURLYSALE"].ToString();
                    Session["L_HourlySales"] = L_HourlySales;
                }

                if (Session["L_HourlySales"].ToString() == "N" || Session["Page_Acess"].ToString() == "N")
                {
                    Response.Redirect("DeniedPage.aspx");
                }
                else
                {
                    //lblMsgTotalSelection.Text = "Search Result - Hourly Sales Reports Between " + "&nbsp;&nbsp;" + txtStartDt.Text + "&nbsp;&nbsp;&nbsp;  And &nbsp;&nbsp;&nbsp;" + txtEndDt.Text;
                    //Label1.Text = " Search Result - Hourly Sales Reports Between " + "&nbsp; &nbsp;" + txtStartDt.Text + "&nbsp;&nbsp;&nbsp;  And &nbsp;&nbsp;&nbsp;" + txtEndDt.Text;
                    lblMsgTotalSelection.Text = " Search Result - from" + " &nbsp;&nbsp; " + StartDT.Trim() + "&nbsp;&nbsp; to &nbsp;&nbsp;" + EndDt.Trim();
                    idGenReport.Attributes.Add("style", "background-color: #4c4c4c; color: White;font-size:14px");
                    Label1.Text = " Search Result - from" + "&nbsp;&nbsp;" + StartDT.Trim() + "&nbsp;&nbsp; to &nbsp;&nbsp;" + EndDt.Trim();
                    idHourly.Attributes.Add("style", "background-color: #4c4c4c; color: White;font-size:14px;");
                    Cd_BranchName = cmbBranches.SelectedItem.Text;
                    ConfigureColors();
                    CreateBarGraph(Cmb_BranchName, StartDT.Trim(), EndDt.Trim());
                    BindChart();
                    if (GridView1.Rows.Count > 0)
                    {
                        BindGrid(Microsoft.Security.Application.Encoder.HtmlEncode(Cmb_BranchName), StartDT.Trim(), EndDt.Trim());


                    }
                    else
                    {
                        BindGrid(Microsoft.Security.Application.Encoder.HtmlEncode(Cmb_BranchName), StartDT.Trim(), EndDt.Trim());

                    }


                }

            }

            // Update the current Branch Selection in db
            UPDATEBRANCH(Microsoft.Security.Application.Encoder.HtmlEncode(Cmb_BranchName));
            Page.Response.Redirect(Page.Request.Url.ToString(), true);

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


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

            System.Threading.Thread.Sleep(1000);
            if (cmbBranches.Visible == false)
            {

                //lblMsgTotalSelection.Text = "Search Result - Hourly Sale Reports Comparision Between " + "&nbsp; &nbsp;" + txtStartDt.Text + "&nbsp;&nbsp;&nbsp;  And &nbsp;&nbsp;&nbsp;" + txtEndDt.Text;
                //Label1.Text = "Search Result - Hourly Sales Reports Between" + "&nbsp; &nbsp;" + txtStartDt.Text + "&nbsp;&nbsp;&nbsp;  And &nbsp;&nbsp;&nbsp;" + txtEndDt.Text;
                lblMsgTotalSelection.Text = " Search Result - from" + " &nbsp;&nbsp; " + StartDT.Trim() + "&nbsp;&nbsp; to &nbsp;&nbsp;" + EndDt.Trim();
                idGenReport.Attributes.Add("style", "background-color: #4c4c4c; color: White;font-size:14px;");
                Label1.Text = " Search Result - from" + "&nbsp;&nbsp;" + StartDT.Trim() + "&nbsp;&nbsp; to &nbsp;&nbsp;" + EndDt.Trim();
                idHourly.Attributes.Add("style", "background-color: #4c4c4c; color: White;font-size:14px;");
                ConfigureColors();
                CreateBarGraph(Session["Branch_HQ"].ToString(), StartDT.Trim(), EndDt.Trim());
                BindGrid(Session["Branch_HQ"].ToString(), StartDT.Trim(), EndDt.Trim());
                BindChart();
            }
            else if (cmbBranches.Visible == true)
            {

                Curr_BranchFullName = Microsoft.Security.Application.Encoder.HtmlEncode(cmbBranches.SelectedItem.Text);
                cd_BranchAlias = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), Curr_BranchFullName);  // This will Return BranchName( Actual Database Name )
                                                                                                                                                    //lblMsgTotalSelection.Text = "Search Result - Hourly Sale Reports Comparision Between " + "&nbsp; &nbsp;" + txtStartDt.Text + "&nbsp;&nbsp;&nbsp;  And &nbsp;&nbsp;&nbsp;" + txtEndDt.Text;
                                                                                                                                                    //Label1.Text = "Search Result - Hourly Sales Reports Between " + "&nbsp; &nbsp;" + txtStartDt.Text + "&nbsp;&nbsp;&nbsp;  And &nbsp;&nbsp;&nbsp;" + txtEndDt.Text;
                lblMsgTotalSelection.Text = " Search Result - from" + " &nbsp;&nbsp; " + StartDT.Trim() + "&nbsp;&nbsp; to &nbsp;&nbsp;" + EndDt.Trim();
                idGenReport.Attributes.Add("style", "background-color: #4c4c4c; color: White;font-size:14px;");
                Label1.Text = " Search Result - from" + "&nbsp;&nbsp;" + StartDT.Trim() + "&nbsp;&nbsp; to &nbsp;&nbsp;" + EndDt.Trim();
                idHourly.Attributes.Add("style", "background-color: #4c4c4c; color: White;font-size:14px;");
                ConfigureColors();
                CreateBarGraph(cd_BranchAlias, StartDT.Trim(), EndDt.Trim());
                BindGrid(cd_BranchAlias, StartDT.Trim(), EndDt.Trim());
                BindChart();
            }


        }

        private void ConfigureColors()
        {
            color[0] = "991396";
            color[1] = "1A2442";
            color[2] = "1A4237";
            color[3] = "FF8E46";
            color[4] = "008E8E";
            color[5] = "D64646";
            color[6] = "8E468E";
            color[7] = "588526";
            color[8] = "AFD8F8";
            color[9] = "008ED6";
            color[10] = "9D080D";
            color[11] = "A186BE";
            color[12] = "006400";
            color[13] = "2F4F4F";
            color[14] = "4B0082";
            color[15] = "8B0A50";
            color[16] = "6E7B8B";
            color[17] = "00688B";
            color[18] = "8B5A00 ";
            color[19] = "8B0000";
            color[20] = "8B8878";
            color[21] = "4B0082";
            color[22] = "483D8B";


        }
        public void LoadBranchName()
        {
            DT = ObjUserBL.GetBranchOnLoginValues8(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), Session["CM_ID"].ToString());
            cmbBranches.DataSource = DT;
            cmbBranches.DataTextField = "branchfullname";
            cmbBranches.DataValueField = "Branchid";
            cmbBranches.DataBind();
            cmbBranches.Items.Insert(0, "Select Branch");

        }

        public void LoadBranchName4SuperAdmin()
        {
            DT = ObjUserBL.GetBranchOnSuperAdmin8(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), Session["CM_ID"].ToString());

            cmbBranches.DataSource = DT;
            cmbBranches.DataTextField = "branchfullname";
            cmbBranches.DataValueField = "Branchid";
            cmbBranches.DataBind();
            cmbBranches.Items.Insert(0, "Select Branch");

        }

        public void LoadBranchNamewithPortalTypeid()
        {
            DT = ObjUserBL.GetBranchOnLoginPortalid(Session["Branch_HQ"].ToString());
            cmbBranches.DataSource = DT;
            cmbBranches.DataTextField = "branchfullname";
            cmbBranches.DataValueField = "Branchid";
            cmbBranches.DataBind();
            cmbBranches.Items.Insert(0, "Select Branch");

        }

        private void CreateBarGraph(string Branch_AliasName, string D1, string D2)
        {

            //XSS Attack Prevention

            string StartDT = Microsoft.Security.Application.Encoder.HtmlEncode(txtStartDt.Text);
            string EndDt = Microsoft.Security.Application.Encoder.HtmlEncode(txtEndDt.Text);


            // Get The Graph Values :  
            string ChartQry = "SELECT A.TransDate,concat(DATE_FORMAT(a.transtime,'%h:%00 %p'),'-',DATE_FORMAT(a.transtime,'%h:59 %p')) as Hour,DATE_FORMAT(a.transtime,'%H') as TimeGroup,Date_format(TransTime,'%y-%m-%d %H:00:00') as DateTime,B.BarCode,Sum(b.qty) as Qty,C.CustomerName, If(B.TakeAway=-1,'Dine Out','Dine In') as TakeAway, B.Name, B.InventoryDesc, B.CategoryNumber,Sum(b.PSDiscAmount+b.ManualDisc+b.MemberDisc+b.TotalDisc) as Disamt, Sum(B.TaxableAmount+B.TaxAmount1+B.TaxAmount2+B.TaxAmount3+B.TaxAmount4+B.TaxAmount5+B.TaxAmount6) As Amount, DATE_FORMAT(a.transtime,'%h:%00 %p') as TM FROM {0}.Trans A JOIN {0}.TransDetail B on A.Transid=B.Transid Left Join {0}.Customers C On a.CustomerNumber=C.CustomerNumber Where  (A.BusinessDate Between @D1 And @D2 ) And B.ItemStatus<>1 Group by Hour ORDER BY HOUR(a.TransTime);";
            string command = string.Format(ChartQry, Branch_AliasName);
            MySqlParameter[] parameters =
                   {
                     new MySqlParameter("@D1",D1),
                     new MySqlParameter("@D2",D2),
                    };

            DT = ObjMain.NewGetData_DT(command, parameters);




           // DT = ObjMainCloud.GetData_DT(ChartQry);


            string strCaption = "Hour wise Total Sales Report";
            //string strSubCaption = "Monthwise Total Sale";
            string xAxis = "Hours ";
            string yAxis = "Total Sale";
            //strXML will be used to store the entire XML document generated
            string strXML = null;
            DataTable DtSession = new DataTable();

            if (cmbBranches.Visible == true)
            {
                Time_Group(Branch_AliasName, StartDT.Trim(), EndDt.Trim());

            }
            else
            {
                Time_Group(Session["Branch_HQ"].ToString(), StartDT.Trim(), EndDt.Trim());
            }



            DtSession = Session["DtResultSet"] as DataTable;
            //Generate the graph element
            strXML = @"<graph caption='" + strCaption + @"' subCaption='" + "" + @"' decimalPrecision='0' 
                          pieSliceDepth='50' formatNumberScale='0' 
                          xAxisName='" + xAxis + @"' yAxisName='" + yAxis + @"' rotateNames='1' >";
            int i = 0;
            foreach (DataRow dr2 in DtSession.Rows)
            {
                strXML += "<set name='" + dr2[0].ToString() + "' value='" + dr2[1].ToString() + "' color='" + color[i] + @"'  link=&quot;JavaScript:myJS('" + dr2["TM"].ToString() + ", " + dr2["Amount"].ToString() + "'); &quot;/>";
                i++;
            }
            //Finally, close <graph> element
            strXML += "</graph>";

            FCLiteral1.Text = InfoSoftGlobal.FusionCharts.RenderChartHTML(
                "FusionCharts/FCF_Column2D.swf",                             // Path to chart's SWF
                "",                                                                              // Leave blank when using Data String method
                strXML,                                                                      // xmlStr contains the chart data
                "mygraph1",                                                             // Unique chart ID
                GraphWidth, GraphHeight,                                        // Width & Height of chart
                false
                );
        }

        /// <summary>
        ///  This Function uses to Get Alll TimeGroup and Its Amount :
        /// </summary>
        /// <param name="Branch_AliasName"></param>
        /// <param name="D1"></param>
        /// <param name="D2"></param>
        public void Time_Group(string Branch_AliasName, string D1, string D2)
        {
            string ChartQry = "SELECT A.TransDate,concat(DATE_FORMAT(a.transtime,'%h:%00 %p'),'-',DATE_FORMAT(a.transtime,'%h:59 %p')) as Hour,DATE_FORMAT(a.transtime,'%H') as TimeGroup,Date_format(TransTime,'%y-%m-%d %H:00:00') as DateTime, Sum(B.TaxableAmount+B.TaxAmount1+B.TaxAmount2+B.TaxAmount3+B.TaxAmount4+B.TaxAmount5+B.TaxAmount6) As Amount, DATE_FORMAT(a.transtime,'%h:%00 %p') as TM FROM {0}.Trans A JOIN {0}.TransDetail B on A.Transid=B.Transid Left Join {0}.Customers C On a.CustomerNumber=C.CustomerNumber Where  (A.BusinessDate Between  @D1 And  @D2 ) And B.ItemStatus=0  and A.Transstatus in (2,3,4) Group by Hour ORDER BY HOUR(a.TransTime);";
            string command = string.Format(ChartQry, Branch_AliasName); 
            MySqlParameter[] parameters =
                  {
                     new MySqlParameter("@D1",D1),
                     new MySqlParameter("@D2",D2)
                    };
            ReadResult = ObjMain.NewGetData_DT(command, parameters);

            //ReadResult = ObjMainCloud.GetData_DT(ChartQry);

            foreach (DataRow dr in ReadResult.Select("TimeGroup='00' "))
            {

                Tm0 = dr["TM"].ToString();
                Amt0 = dr["Amount"].ToString();

            }
            if (Tm0 == null && Amt0 == null)
            {
                Tm0 = "12:00 AM ";
                Amt0 = "0";

            }

            foreach (DataRow dr in ReadResult.Select("TimeGroup='01' "))
            {
                Tm1 = dr["TM"].ToString();
                Amt1 = dr["Amount"].ToString();
            }

            if (Tm1 == null && Amt1 == null)
            {
                Tm1 = "01:00 AM ";
                Amt1 = "0";

            }



            foreach (DataRow dr in ReadResult.Select("TimeGroup='02' "))
            {
                Tm2 = dr["TM"].ToString();
                Amt2 = dr["Amount"].ToString();
            }
            if (Tm2 == null && Amt2 == null)
            {
                Tm2 = "02:00 AM ";
                Amt2 = "0";

            }

            foreach (DataRow dr in ReadResult.Select("TimeGroup='03' "))
            {
                Tm3 = dr["TM"].ToString();
                Amt3 = dr["Amount"].ToString();
            }
            if (Tm3 == null && Amt3 == null)
            {
                Tm3 = "03:00 AM ";
                Amt3 = "0";

            }

            foreach (DataRow dr in ReadResult.Select("TimeGroup='04' "))
            {
                Tm4 = dr["TM"].ToString();
                Amt4 = dr["Amount"].ToString();
            }
            if (Tm4 == null && Amt4 == null)
            {
                Tm4 = "04:00 AM ";
                Amt4 = "0";

            }

            foreach (DataRow dr in ReadResult.Select("TimeGroup='05' "))
            {
                Tm5 = dr["TM"].ToString();
                Amt5 = dr["Amount"].ToString();
            }
            if (Tm5 == null && Amt5 == null)
            {
                Tm5 = "05:00 AM ";
                Amt5 = "0";

            }

            foreach (DataRow dr in ReadResult.Select("TimeGroup='06' "))
            {
                Tm6 = dr["TM"].ToString();
                Amt6 = dr["Amount"].ToString();
            }
            if (Tm6 == null && Amt6 == null)
            {
                Tm6 = "06:00 AM ";
                Amt6 = "0";

            }
            foreach (DataRow dr in ReadResult.Select("TimeGroup='07' "))
            {
                Tm7 = dr["TM"].ToString();
                Amt7 = dr["Amount"].ToString();
            }
            if (Tm7 == null && Amt7 == null)
            {
                Tm7 = "07:00 AM ";
                Amt7 = "0";

            }

            foreach (DataRow dr in ReadResult.Select("TimeGroup='08' "))
            {
                Tm8 = dr["TM"].ToString();
                Amt8 = dr["Amount"].ToString();
            }
            if (Tm8 == null && Amt8 == null)
            {
                Tm8 = "08:00 AM ";
                Amt8 = "0";

            }
            foreach (DataRow dr in ReadResult.Select("TimeGroup='09' "))
            {
                Tm9 = dr["TM"].ToString();
                Amt9 = dr["Amount"].ToString();
            }
            if (Tm9 == null && Amt9 == null)
            {
                Tm9 = "09:00 AM ";
                Amt9 = "0";

            }
            foreach (DataRow dr in ReadResult.Select("TimeGroup='10' "))
            {
                Tm10 = dr["TM"].ToString();
                Amt10 = dr["Amount"].ToString();
            }
            if (Tm10 == null && Amt10 == null)
            {
                Tm10 = "10:00 AM ";
                Amt10 = "0";

            }
            foreach (DataRow dr in ReadResult.Select("TimeGroup='11' "))
            {
                Tm11 = dr["TM"].ToString();
                Amt11 = dr["Amount"].ToString();
            }
            if (Tm11 == null && Amt11 == null)
            {
                Tm11 = "11:00 AM ";
                Amt11 = "0";

            }


            foreach (DataRow dr in ReadResult.Select("TimeGroup='12' "))
            {
                Tm12 = dr["TM"].ToString();
                Amt12 = dr["Amount"].ToString();
            }
            if (Tm12 == null && Amt12 == null)
            {
                Tm12 = "12:00 PM ";
                Amt12 = "0";

            }



            foreach (DataRow dr in ReadResult.Select("TimeGroup='13' "))
            {
                Tm13 = dr["TM"].ToString();
                Amt13 = dr["Amount"].ToString();
            }
            if (Tm13 == null && Amt13 == null)
            {
                Tm13 = "01:00 PM    ";
                Amt13 = "0";

            }
            foreach (DataRow dr in ReadResult.Select("TimeGroup='14' "))
            {
                Tm14 = dr["TM"].ToString();
                Amt14 = dr["Amount"].ToString();
            }
            if (Tm14 == null && Amt14 == null)
            {
                Tm14 = "02:00 PM ";
                Amt14 = "0";

            }

            foreach (DataRow dr in ReadResult.Select("TimeGroup='15' "))
            {
                Tm15 = dr["TM"].ToString();
                Amt15 = dr["Amount"].ToString();
            }

            if (Tm15 == null && Amt15 == null)
            {
                Tm15 = "03:00 PM ";
                Amt15 = "0";

            }
            foreach (DataRow dr in ReadResult.Select("TimeGroup='16' "))
            {
                Tm16 = dr["TM"].ToString();
                Amt16 = dr["Amount"].ToString();
            }
            if (Tm16 == null && Amt16 == null)
            {
                Tm16 = "04:00 PM ";
                Amt16 = "0";

            }

            foreach (DataRow dr in ReadResult.Select("TimeGroup='17' "))
            {
                Tm17 = dr["TM"].ToString();
                Amt17 = dr["Amount"].ToString();
            }
            if (Tm17 == null && Amt17 == null)
            {
                Tm17 = "05:00 PM ";
                Amt17 = "0";

            }
            foreach (DataRow dr in ReadResult.Select("TimeGroup='18' "))
            {
                Tm18 = dr["TM"].ToString();
                Amt18 = dr["Amount"].ToString();
            }
            if (Tm18 == null && Amt18 == null)
            {
                Tm18 = "06:00 PM ";
                Amt18 = "0";

            }
            foreach (DataRow dr in ReadResult.Select("TimeGroup='19' "))
            {
                Tm19 = dr["TM"].ToString();
                Amt19 = dr["Amount"].ToString();
            }

            if (Tm19 == null && Amt19 == null)
            {
                Tm19 = "07:00 PM ";
                Amt19 = "0";

            }

            foreach (DataRow dr in ReadResult.Select("TimeGroup='20' "))
            {
                Tm20 = dr["TM"].ToString();
                Amt20 = dr["Amount"].ToString();
            }
            if (Tm20 == null && Amt20 == null)
            {
                Tm20 = "08:00 PM ";
                Amt20 = "0";

            }

            foreach (DataRow dr in ReadResult.Select("TimeGroup='21' "))
            {
                Tm21 = dr["TM"].ToString();
                Amt21 = dr["Amount"].ToString();
            }
            if (Tm21 == null && Amt21 == null)
            {
                Tm21 = "09:00 PM ";
                Amt21 = "0";

            }
            foreach (DataRow dr in ReadResult.Select("TimeGroup='22' "))
            {
                Tm22 = dr["TM"].ToString();
                Amt22 = dr["Amount"].ToString();
            }
            if (Tm22 == null && Amt22 == null)
            {
                Tm22 = "10:00 PM ";
                Amt22 = "0";
            }

            foreach (DataRow dr in ReadResult.Select("TimeGroup='23' "))
            {
                Tm23 = dr["TM"].ToString();
                Amt23 = dr["Amount"].ToString();
            }
            if (Tm23 == null && Amt23 == null)
            {
                Tm23 = "11:00 PM ";
                Amt23 = "0";
            }


            DataTable DtFinaldata = new DataTable();
            DtFinaldata.Columns.Add("Tm", typeof(string));
            DtFinaldata.Columns.Add("Amount", typeof(decimal));

            DataRow Dr = DtFinaldata.NewRow();
            DataRow Dr1 = DtFinaldata.NewRow();
            DataRow Dr2 = DtFinaldata.NewRow();
            DataRow Dr3 = DtFinaldata.NewRow();
            DataRow Dr4 = DtFinaldata.NewRow();
            DataRow Dr5 = DtFinaldata.NewRow();
            DataRow Dr6 = DtFinaldata.NewRow();
            DataRow Dr7 = DtFinaldata.NewRow();
            DataRow Dr8 = DtFinaldata.NewRow();
            DataRow Dr9 = DtFinaldata.NewRow();
            DataRow Dr10 = DtFinaldata.NewRow();
            DataRow Dr11 = DtFinaldata.NewRow();
            DataRow Dr12 = DtFinaldata.NewRow();

            DataRow Dr13 = DtFinaldata.NewRow();
            DataRow Dr14 = DtFinaldata.NewRow();
            DataRow Dr15 = DtFinaldata.NewRow();
            DataRow Dr16 = DtFinaldata.NewRow();
            DataRow Dr17 = DtFinaldata.NewRow();
            DataRow Dr18 = DtFinaldata.NewRow();
            DataRow Dr19 = DtFinaldata.NewRow();
            DataRow Dr20 = DtFinaldata.NewRow();
            DataRow Dr21 = DtFinaldata.NewRow();
            DataRow Dr22 = DtFinaldata.NewRow();
            DataRow Dr23 = DtFinaldata.NewRow();

            Dr["Tm"] = Tm0;
            Dr["Amount"] = Amt0;
            DtFinaldata.Rows.Add(Dr);

            Dr1["Tm"] = Tm1;
            Dr1["Amount"] = Amt1;
            DtFinaldata.Rows.Add(Dr1);

            Dr2["Tm"] = Tm2;
            Dr2["Amount"] = Amt2;
            DtFinaldata.Rows.Add(Dr2);

            Dr3["Tm"] = Tm3;
            Dr3["Amount"] = Amt3;
            DtFinaldata.Rows.Add(Dr3);

            Dr4["Tm"] = Tm4;
            Dr4["Amount"] = Amt4;
            DtFinaldata.Rows.Add(Dr4);

            Dr5["Tm"] = Tm5;
            Dr5["Amount"] = Amt5;
            DtFinaldata.Rows.Add(Dr5);

            Dr6["Tm"] = Tm6;
            Dr6["Amount"] = Amt6;
            DtFinaldata.Rows.Add(Dr6);

            Dr7["Tm"] = Tm7;
            Dr7["Amount"] = Amt7;
            DtFinaldata.Rows.Add(Dr7);

            Dr8["Tm"] = Tm8;
            Dr8["Amount"] = Amt8;
            DtFinaldata.Rows.Add(Dr8);

            Dr9["Tm"] = Tm9;
            Dr9["Amount"] = Amt9;
            DtFinaldata.Rows.Add(Dr9);

            Dr10["Tm"] = Tm10;
            Dr10["Amount"] = Amt10;
            DtFinaldata.Rows.Add(Dr10);

            Dr11["Tm"] = Tm11;
            Dr11["Amount"] = Amt11;
            DtFinaldata.Rows.Add(Dr11);

            Dr12["Tm"] = Tm12;
            Dr12["Amount"] = Amt12;
            DtFinaldata.Rows.Add(Dr12);

            Dr13["Tm"] = Tm13;
            Dr13["Amount"] = Amt13;
            DtFinaldata.Rows.Add(Dr13);

            Dr14["Tm"] = Tm14;
            Dr14["Amount"] = Amt14;
            DtFinaldata.Rows.Add(Dr14);

            Dr15["Tm"] = Tm15;
            Dr15["Amount"] = Amt15;
            DtFinaldata.Rows.Add(Dr15);

            Dr16["Tm"] = Tm16;
            Dr16["Amount"] = Amt16;
            DtFinaldata.Rows.Add(Dr16);

            Dr17["Tm"] = Tm17;
            Dr17["Amount"] = Amt17;
            DtFinaldata.Rows.Add(Dr17);

            Dr18["Tm"] = Tm18;
            Dr18["Amount"] = Amt18;
            DtFinaldata.Rows.Add(Dr18);

            Dr19["Tm"] = Tm19;
            Dr19["Amount"] = Amt19;
            DtFinaldata.Rows.Add(Dr19);

            Dr20["Tm"] = Tm20;
            Dr20["Amount"] = Amt20;
            DtFinaldata.Rows.Add(Dr20);

            Dr21["Tm"] = Tm21;
            Dr21["Amount"] = Amt21;
            DtFinaldata.Rows.Add(Dr21);

            Dr22["Tm"] = Tm22;
            Dr22["Amount"] = Amt22;
            DtFinaldata.Rows.Add(Dr22);

            Dr23["Tm"] = Tm23;
            Dr23["Amount"] = Amt23;
            DtFinaldata.Rows.Add(Dr23);

            Session["DtResultSet"] = DtFinaldata;

            DtFinaldata.AcceptChanges();




        }

        private void BindGrid(string Branch_AliasName, string D1, string D2)
        {

            string query = "SELECT concat(DATE_FORMAT(a.transtime,'%h:%00 %p'),'-',DATE_FORMAT(a.transtime,'%h:59 %p')) as Hour,B.BarCode,Sum(b.qty) as Qty,B.Name,B.InventoryDesc as InventoryDesc , Sum(b.PSDiscAmount+b.ManualDisc+b.MemberDisc+b.TotalDisc) as Disamt, Sum(B.TaxableAmount+B.TaxAmount1+B.TaxAmount2+B.TaxAmount3+B.TaxAmount4+B.TaxAmount5+B.TaxAmount6) As Amount FROM {0}.Trans A JOIN {0}.TransDetail B on A.Transid=B.Transid Left Join {0}.Customers C On a.CustomerNumber=C.CustomerNumber Where  (A.BusinessDate Between  @D1  And  @D2 ) And B.ItemStatus=0 and A.Transstatus in (2,3,4) Group by Hour,Barcode,CategoryNumber ORDER BY HOUR(a.TransTime)";
            string command = string.Format(query, Branch_AliasName);

            MySqlParameter[] parameters =
                   {
                     new MySqlParameter("@D1",D1),
                     new MySqlParameter("@D2",D2)
                    };
            Dt2 = ObjMain.NewGetData_DT(command, parameters);
            GridView1.DataSource = Dt2;
            GridView1.DataBind();
        }
        private void AddTotalRow(string labelTexte, string labelText, string value, string labelText1, string value1, string labelText2, string value2)
        {

            GridViewRow row = new GridViewRow(0, 0, DataControlRowType.DataRow, DataControlRowState.Normal);
            row.BackColor = Color.FromName("#EAEAEA");
            //row.ForeColor = Color.FromName("#388E8E");
            row.Cells.AddRange(new TableCell[7] { new TableCell (),
                                                      new TableCell (),    //Empty Cell
                                        new TableCell { Text = labelTexte, HorizontalAlign = HorizontalAlign.Right},
                                        new TableCell { Text = labelText, HorizontalAlign = HorizontalAlign.Right},
                                        new TableCell { Text = value, HorizontalAlign = HorizontalAlign.Right},
                                        new TableCell { Text = value1, HorizontalAlign = HorizontalAlign.Right },
                                        new TableCell { Text = value2, HorizontalAlign = HorizontalAlign.Right }});

            GridView1.Controls[0].Controls.Add(row);
        }


        protected void OnDataBound(object sender, EventArgs e)
        {


            for (int i = subTotalRowIndex; i < GridView1.Rows.Count; i++)
            {
                subTotal += Convert.ToDecimal(GridView1.Rows[i].Cells[4].Text);
                SubDisamt += Convert.ToDecimal(GridView1.Rows[i].Cells[5].Text);
                SubTotAmt += Convert.ToDecimal(GridView1.Rows[i].Cells[6].Text);
            }


            this.AddTotalRow(currentId.ToString(), "Sub Total ", subTotal.ToString(), "Sub Disamt", SubDisamt.ToString("N2"), "Sub TotalAmount", SubTotAmt.ToString("N2"));


            for (int i = subTotalRowIndex1; i < GridView1.Rows.Count; i++)
            {
                subTotal += Convert.ToDecimal(GridView1.Rows[i].Cells[4].Text);
                SubDisamt += Convert.ToDecimal(GridView1.Rows[i].Cells[5].Text);
                SubTotAmt += Convert.ToDecimal(GridView1.Rows[i].Cells[6].Text);

            }

            this.AddTotalRow("", "Grand Total", total.ToString(), "GrandDisamt", TotDisamt.ToString("N2"), "TotalAmout", Totamt.ToString("N2"));

        }

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

        protected void btnExcel_Click(object sender, EventArgs e)
        {
            if (Session["Isdowld_Acess_7"].ToString() == "N")
            {
                Page page = HttpContext.Current.Handler as Page;
                string message = "No Access To download";
                System.Web.UI.ScriptManager.RegisterStartupScript(page, page.GetType(), "err_msg", "alert('" + message + "');", true);

            }
            else if (cmbBranches.SelectedIndex != 0)
            {

                //if (cmbBranches.Visible == true)
                // {
                //     BindGrid(cmbBranches.SelectedItem.Text, txtStartDt.Text, txtEndDt.Text);

                // }
                // else
                // { 
                //     BindGrid(Session["Branch_HQ"].ToString(), txtStartDt.Text, txtEndDt.Text);
                // }


                MySqlConnection Cnn = new MySqlConnection(ConStr_Rds);
                Cnn.Open();

                if (cmbBranches.Visible == true)
                {
                    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 )
                    Response.Clear();
                    Response.Buffer = true;
                    Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
                    Response.Charset = "";
                    Response.ContentType = "application/vnd.ms-excel";
                    using (StringWriter sw = new StringWriter())
                    {
                        HtmlTextWriter hw = new HtmlTextWriter(sw);

                        //To Export all pages
                        GridView1.AllowPaging = false;
                        BindGrid(Cmb_BranchName, Microsoft.Security.Application.Encoder.HtmlEncode(txtStartDt.Text), Microsoft.Security.Application.Encoder.HtmlEncode(txtEndDt.Text));
                        GridView1.HeaderRow.BackColor = Color.White;
                        foreach (TableCell cell in GridView1.HeaderRow.Cells)
                        {
                            cell.BackColor = GridView1.HeaderStyle.BackColor;
                        }
                        foreach (GridViewRow row in GridView1.Rows)
                        {
                            row.BackColor = Color.White;
                            foreach (TableCell cell in row.Cells)
                            {
                                if (row.RowIndex % 2 == 0)
                                {
                                    cell.BackColor = GridView1.AlternatingRowStyle.BackColor;
                                }
                                else
                                {
                                    cell.BackColor = GridView1.RowStyle.BackColor;
                                }
                                cell.CssClass = "textmode";
                            }
                        }

                        GridView1.RenderControl(hw);

                        //style to format numbers to string
                        string style = @"<style> .textmode { mso-number-format:\@; } </style>";
                        Response.Write(style);
                        Response.Output.Write(sw.ToString());
                        Response.Flush();
                        Response.End();
                    }
                }
                else
                {

                    Response.Clear();
                    Response.Buffer = true;
                    Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.xls");
                    Response.Charset = "";
                    Response.ContentType = "application/vnd.ms-excel";
                    using (StringWriter sw = new StringWriter())
                    {
                        HtmlTextWriter hw = new HtmlTextWriter(sw);

                        //To Export all pages
                        GridView1.AllowPaging = false;
                        BindGrid(Session["Branch_HQ"].ToString(), Microsoft.Security.Application.Encoder.HtmlEncode(txtStartDt.Text), Microsoft.Security.Application.Encoder.HtmlEncode(txtEndDt.Text));

                        GridView1.HeaderRow.BackColor = Color.White;
                        foreach (TableCell cell in GridView1.HeaderRow.Cells)
                        {
                            cell.BackColor = GridView1.HeaderStyle.BackColor;
                        }
                        foreach (GridViewRow row in GridView1.Rows)
                        {
                            row.BackColor = Color.White;
                            foreach (TableCell cell in row.Cells)
                            {
                                if (row.RowIndex % 2 == 0)
                                {
                                    cell.BackColor = GridView1.AlternatingRowStyle.BackColor;
                                }
                                else
                                {
                                    cell.BackColor = GridView1.RowStyle.BackColor;
                                }
                                cell.CssClass = "textmode";
                            }
                        }

                        GridView1.RenderControl(hw);

                        //style to format numbers to string
                        string style = @"<style> .textmode { mso-number-format:\@; } </style>";
                        Response.Write(style);
                        Response.Output.Write(sw.ToString());
                        Response.Flush();
                        Response.End();
                    }

                }
            }


        }
        protected void GridView1_RowCreated(object sender, GridViewRowEventArgs e)
        {

            subTotal = 0;
            SubDisamt = 0;
            SubTotAmt = 0;
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                DataTable Dt_View = (e.Row.DataItem as DataRowView).DataView.Table;
                string orderId = Convert.ToString(Dt_View.Rows[e.Row.RowIndex]["Hour"]);
                total += Convert.ToInt32(Dt_View.Rows[e.Row.RowIndex]["Qty"]);
                TotDisamt += Convert.ToDecimal(Dt_View.Rows[e.Row.RowIndex]["Disamt"]);
                Totamt += Convert.ToDecimal(Dt_View.Rows[e.Row.RowIndex]["Amount"]);

                if (orderId != currentId)
                {
                    if (e.Row.RowIndex > 0)
                    {
                        for (int i = subTotalRowIndex; i < e.Row.RowIndex; i++)
                        {
                            subTotal += Convert.ToDecimal(GridView1.Rows[i].Cells[4].Text);
                            SubDisamt += Convert.ToDecimal(GridView1.Rows[i].Cells[5].Text);
                            SubTotAmt += Convert.ToDecimal(GridView1.Rows[i].Cells[6].Text);

                        }
                        this.AddTotalRow(currentId.ToString(), "Sub Total", subTotal.ToString(), "Sub Disamt", SubDisamt.ToString("N2"), "Sub TotalAmount", SubTotAmt.ToString("N2"));
                        subTotalRowIndex = e.Row.RowIndex;
                    }
                    currentId = orderId;

                }

            }

        }

        private void BindChart()
        {
            DataTable dt = new DataTable();
            try
            {
                dt = Session["DtResultSet"] as DataTable;

                str.Append(@"<script type=text/javascript> google.load( *visualization*, *1*, {packages:[*corechart*]});
                       google.setOnLoadCallback(drawChart);
                       function drawChart() {
        var data = new google.visualization.DataTable();
        data.addColumn('string', 'Month');
        data.addColumn('number','TotSale');      

        data.addRows(" + dt.Rows.Count + ");");

                for (int i = 0; i <= dt.Rows.Count - 1; i++)
                {
                    str.Append("data.setValue( " + i + "," + 0 + "," + "'" + dt.Rows[i]["Tm"].ToString() + "');");
                    str.Append("data.setValue(" + i + "," + 1 + "," + dt.Rows[i]["Amount"].ToString() + ") ;");
                }

                str.Append(" var chart = new google.visualization.ColumnChart(document.getElementById('chart_div'));");
                str.Append(" chart.draw(data, {height: 400, title: 'HOURLY SALES REPORT',");
                str.Append("hAxis: {title: 'HOURS', titleTextStyle: {color: 'green'}}");
                str.Append("}); }");
                str.Append("$(window).resize(function(){ drawChart();});");
                str.Append("</script>");
                lt.Text = str.ToString().TrimEnd(',').Replace('*', '"');
            }
            catch
            {
            }
        }



    }
}