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 RAPOReport : 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 Dt2 = new DataTable();
        DataTable DtLicense = new DataTable();
        DataTable DtSuperAdmin = new DataTable();
        DataTable DtMultiBranch = new DataTable();
        DataTable DtNormalUser = new DataTable();
        DataTable DTProductSale = new DataTable();
        DataTable DtVal1 = new DataTable();
        DataTable DtVal2 = new DataTable();
        DataTable DtVal3 = 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_RAPO = 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 Vw_Chk = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {
            PID = "18";    // This is for ItemSale
            if (!IsPostBack)
            {
                txtStartDt.Text = Curr_DateOnly;
                txtEndDt.Text = Curr_DateOnly;
            }
            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)
                {
                    LoadBranchName4SuperAdmin();
                }
                cd_BranchAlias = cmbBranches.SelectedItem.Text;
                //LoadInventoryListGrid(cd_BranchAlias, txtStartDt.Text, txtEndDt.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 = "Branch Name" + "&nbsp;" + "-" + "&nbsp;" + Curr_BranchFullName + "&nbsp; ";

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

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

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

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


                    //lblMsgTotalSelection.Text = "Search Result - RAPO  Report   Between" + "&nbsp;&nbsp;&nbsp;&nbsp;" + txtStartDt.Text + "&nbsp;&nbsp;&nbsp;  and  &nbsp;&nbsp;&nbsp;" + txtEndDt.Text;
                    lblMsgTotalSelection.Text = "Search Result - from " + "&nbsp;&nbsp;" + StartDT + "&nbsp;&nbsp;  to  &nbsp;&nbsp;" + EndDt;
                    idGenReport.Attributes.Add("style", "background-color: #4c4c4c; color: White;font-size:14px;");
                    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(), StartDT, EndDt);
                            }

                        }


                    }

                }

            }
            else
            {

            }
        }

        private void ActiveCall()
        {

            // XSS Attack Prevention 

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



            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=" + 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_RAPO = DtLicense.Rows[0]["RAPOREPORT"].ToString();
                Session["L_RAPO"] = L_RAPO;

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

                //lblMsgTotalSelection.Text = "Search Result - RA/PO Report Selection Between" + "&nbsp;&nbsp;&nbsp;" + txtStartDt.Text + "&nbsp;&nbsp;&nbsp;  And &nbsp;&nbsp;&nbsp;" + txtEndDt.Text;
                lblMsgTotalSelection.Text = "Search Result - from " + "&nbsp;&nbsp;" + StartDT + "&nbsp;&nbsp;  to  &nbsp;&nbsp;" + EndDt;
                idGenReport.Attributes.Add("style", "background-color: #4c4c4c; color: White;font-size:14px;");
                cd_BranchAlias = cmbBranches.SelectedItem.Text;
                BindGridview(ActiveCallvalue, StartDT, EndDt);
                System.Threading.Thread.Sleep(2000);

            }
        }

        protected void btnGetReports_Click(object sender, EventArgs e)
        {

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

            if (cmbBranches.Visible == false)
            {
                btnGetReports.Visible = true;
                // lblMsgTotalSelection.Text = "  Search Result - RA/PO  Selection Between   " + txtStartDt.Text + "&nbsp;&nbsp;&nbsp;  And &nbsp;&nbsp;&nbsp;" + txtEndDt.Text;
                BindGridview(Session["Branch_HQ"].ToString(), StartDT, EndDt);
                lblMsgTotalSelection.Text = "Search Result - from " + "&nbsp;&nbsp;" + StartDT + "&nbsp;&nbsp;  to  &nbsp;&nbsp;" + EndDt;
                idGenReport.Attributes.Add("style", "background-color: #4c4c4c; color: White;font-size:14px;");
                //  System.Threading.Thread.Sleep(2000);
            }
            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 -RA/PO  Selection Between   " + txtStartDt.Text + "&nbsp;&nbsp;&nbsp;  And &nbsp;&nbsp;&nbsp;" + txtEndDt.Text;
                lblMsgTotalSelection.Text = "Search Result - from " + "&nbsp;&nbsp;" + StartDT + "&nbsp;&nbsp;  to  &nbsp;&nbsp;" + EndDt;
                idGenReport.Attributes.Add("style", "background-color: #4c4c4c; color: White;font-size:14px;");
                BindGridview(cd_BranchAlias, StartDT, EndDt);

            }


        }
        private void BindGridview(string BranchName, string D1, string D2)
        {

            DataTable Dt = new DataTable();

            string cmd = "select H.Termid , H.Transdate,H.Cashierid , H.Transtype, H.Paymenttype,H.Paycurrency,H.Amount,H.Notes,H.Businessdate ,H.RAPO from "
               + " ("
               + " select Termid , Transdate,Cashierid , Transtype, Paymenttype,Paycurrency,Amount,Notes,Businessdate,'RA' AS RAPO from {0}.rapo  Where date(BusinessDate) Between  @D1  and   @D2  And TransType in (0) "
               + " Union all "
               + " select Termid , Transdate,Cashierid , Transtype, Paymenttype,Paycurrency,Amount,Notes,Businessdate ,'PO' AS RAPO from {0}.rapo  Where date(BusinessDate) Between @D1  and   @D2  And TransType in (1) "
               + " ) H ";

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

            MySqlParameter[] parameters =
                   {
                     new MySqlParameter("@D1",D1),
                     new MySqlParameter("@D2",D2),
                    };

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

        protected void btnGenerateRpt_Click(object sender, EventArgs e)
        {
            gvRAPOList.Visible = true;
            // loadRpt(txtStartDt.Text, txtEndDt.Text, Session["Branch_HQ"].ToString());
        }

        //private void loadRpt(string startDate, string EndDate, string Branch)
        //{
        //    System.Threading.Thread.Sleep(1000);
        //    try
        //    {

        //        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 )

        //        //check the view is and create.

        //        string Vw_Chk_Qry = "SHOW FULL TABLES IN " + Cmb_BranchName + " WHERE TABLE_TYPE LIKE 'VIEW' and Tables_in_" + Cmb_BranchName + "='vRAPO';";
        //        Vw_Chk = ObjMain.ExecuteScalar(Vw_Chk_Qry);

        //        if (Vw_Chk == "")
        //        {
        //            string Ins_Vw = "Create view " + Cmb_BranchName + ".vRAPO as SELECT BusinessDate,PaymentType,PayCurrency,Amount ,CashierId as CashierId from "
        //                                     + Cmb_BranchName + ".rapo;";
        //            L = ObjMain.ExecuteNonQuery(Ins_Vw);
        //        }



        //        CrystalReportViewer1.Visible = true;
        //        TableLogOnInfos crtableLogoninfos = new TableLogOnInfos();
        //        TableLogOnInfo crtableLogoninfo = new TableLogOnInfo();
        //        ConnectionInfo crConnectionInfo = new ConnectionInfo();
        //        Tables CrTables;

        //        string q2 = "select * from  " + Cmb_BranchName + ".vRAPO r  where date(r.businessdate) between '" + startDate + "'   and  '" + EndDate + "'order by r.businessdate desc;";

        //        DS = ObjMain.GetData_DS(q2);

        //        if (DS.Tables[0].Rows.Count > 0)
        //        {
        //            rep = new ReportDocument();
        //            rep.Load(Server.MapPath("~/RAPO.rpt"));

        //            rep.SetDataSource(DS.Tables[0]);
        //            CrTables = rep.Database.Tables;

        //            foreach (CrystalDecisions.CrystalReports.Engine.Table CrTable in CrTables)
        //            {
        //                crtableLogoninfo = CrTable.LogOnInfo;

        //                crtableLogoninfo.ConnectionInfo = crConnectionInfo;

        //                CrTable.ApplyLogOnInfo(crtableLogoninfo);

        //            }

        //            CrystalReportViewer1.ReportSource = rep;
        //            //Session["Report"] = rep;
        //            CrystalReportViewer1.DataBind();
        //            CrystalReportViewer1.RefreshReport();
        //        }
        //        else
        //        {
        //            CrystalReportViewer1.Visible = false;
        //            Response.Write(@"<script language='javascript'>alert('No Data Found ! ')</script>");
        //        }


        //    }

        //    catch (Exception ex)
        //    {
        //        throw ex;

        //    }
        //    finally
        //    {

        //    }
        //}

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

            }

        }
        decimal totqty = 0;
        decimal GTOTAMT;
        decimal DisscntQty = 0;
        decimal GDISCAMT;
        protected void cmbBranches_SelectedIndexChanged(object sender, EventArgs e)
        {

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


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

                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 = 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_RAPO = DtLicense.Rows[0]["RAPOREPORT"].ToString();
                    Session["L_RAPO"] = L_RAPO;
                }

                if (Session["L_RAPO"].ToString() == "N" || Session["Page_Acess"].ToString() == "N")
                {
                    Response.Redirect("DeniedPage.aspx");
                }
                else
                {
                    //btnExcel.Enabled = true;
                    // lblMsgTotalSelection.Text = "Total Sale Selection Between" + "&nbsp;&nbsp;&nbsp;" + txtStartDt.Text + "&nbsp;&nbsp;&nbsp;  And &nbsp;&nbsp;&nbsp;" + txtEndDt.Text;
                    cd_BranchAlias = Cmb_BranchName;
                    BindGridview(Cmb_BranchName, StartDT, EndDt); //FUNCTION 
                }
            }
            UPDATEBRANCH(cd_BranchAlias);

        }

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


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

            }

            if (cmbBranches.Visible == false)
            {
                Curr_BranchFullName = Microsoft.Security.Application.Encoder.HtmlEncode(cmbBranches.SelectedItem.Text);
                cd_BranchAlias = Session["Branch_HQ"].ToString();

            }

            DataTable Dt1 = new DataTable();
            if (cmbRAPO.SelectedIndex == 1)
            {



                string cmd = "select H.Termid , H.Transdate,H.Cashierid , H.Transtype, H.Paymenttype,H.Paycurrency,H.Amount,H.Notes,H.Businessdate ,H.RAPO from "
                 + " ("
                 + " select Termid , Transdate,Cashierid , Transtype, Paymenttype,Paycurrency,Amount,Notes,Businessdate,'RA' AS RAPO from {0}.rapo  Where date(BusinessDate) Between  @StartDT  and  @EndDt  And TransType in (0) "
                 + " Union all "
                 + " select Termid , Transdate,Cashierid , Transtype, Paymenttype,Paycurrency,Amount,Notes,Businessdate ,'PO' AS RAPO from {0}.rapo  Where date(BusinessDate) Between  @StartDT  and @EndDt  And TransType in (1) "
                 + " )H ";
                string command = string.Format(cmd, cd_BranchAlias);

                MySqlParameter[] parameters =
                  {
                     new MySqlParameter("@StartDT",StartDT),
                     new MySqlParameter("@EndDt",EndDt),
                    };

                Dt1 = ObjMain.NewGetData_DT(command, parameters);
                gvRAPOList.DataSource = Dt1;
                gvRAPOList.DataBind();


            }
            else if (cmbRAPO.SelectedIndex == 2)
            {



                string cmd = "select H.Termid , H.Transdate,H.Cashierid , H.Transtype, H.Paymenttype,H.Paycurrency,H.Amount,H.Notes,H.Businessdate ,H.RAPO from "
                 + " ("
                 + " select Termid , Transdate,Cashierid , Transtype, Paymenttype,Paycurrency,Amount,Notes,Businessdate,'RA' AS RAPO from {0}.rapo  Where date(BusinessDate) Between  @StartDT  and  @EndDt  And TransType in (0) "
                 + " Union all "
                 + " select Termid , Transdate,Cashierid , Transtype, Paymenttype,Paycurrency,Amount,Notes,Businessdate ,'PO' AS RAPO from {0}.rapo  Where date(BusinessDate) Between  @StartDT  and  @EndDt  And TransType in (1) "
                 + " )H  WHERE  H.RAPO='RA'";

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

                MySqlParameter[] parameters =
                 {
                     new MySqlParameter("@StartDT",StartDT),
                     new MySqlParameter("@EndDt",EndDt),
                 };

                Dt1 = ObjMain.NewGetData_DT(command, parameters);
                gvRAPOList.DataSource = Dt1;
                gvRAPOList.DataBind();

            }
            if (cmbRAPO.SelectedIndex == 3)
            {


                string cmd = "select H.Termid , H.Transdate,H.Cashierid , H.Transtype, H.Paymenttype,H.Paycurrency,H.Amount,H.Notes,H.Businessdate ,H.RAPO from "
                 + " ("
                 + " select Termid , Transdate,Cashierid , Transtype, Paymenttype,Paycurrency,Amount,Notes,Businessdate,'RA' AS RAPO from {0}.rapo  Where date(BusinessDate) Between @StartDT  and  @EndDt  And TransType in (0) "
                 + " Union all "
                 + " select Termid , Transdate,Cashierid , Transtype, Paymenttype,Paycurrency,Amount,Notes,Businessdate ,'PO' AS RAPO from {0}.rapo  Where date(BusinessDate) Between @StartDT  and  @EndDt And TransType in (1) "
                 + " )H  WHERE  H.RAPO='PO' ";

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

                MySqlParameter[] parameters =
                  {
                     new MySqlParameter("@StartDT",StartDT),
                     new MySqlParameter("@EndDt",EndDt),
                    };

                Dt1 = ObjMain.NewGetData_DT(command, parameters);





                gvRAPOList.DataSource = Dt1;
                gvRAPOList.DataBind();

            }

        }
        protected void gvRAPOList_RowDataBound(object sender, GridViewRowEventArgs e)
        {
            if (e.Row.RowType == DataControlRowType.DataRow)
            {
                //string customerId = gvRAPOList.DataKeys[e.Row.RowIndex].Value.ToString();
                GridView gvChildValue = e.Row.FindControl("gvRAPOList") as GridView;

                Label Discqttty = e.Row.FindControl("lblRDisqty") as Label;
                DisscntQty += Convert.ToDecimal(Discqttty.Text);

            }
            if (e.Row.RowType == DataControlRowType.Footer)
            {

                (e.Row.FindControl("lblGrandDiscQTY") as Label).Text = DisscntQty.ToString();


            }
        }


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



            if (Session["Isdowld_Acess"].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)
                {
                    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);



                    if (cmbRAPO.SelectedIndex == 1)
                    {

                        string QryAll = ("select H.Termid , H.Transdate,H.Cashierid , H.Transtype, H.Paymenttype,H.Paycurrency,H.Amount,H.Notes,H.Businessdate ,H.RAPO from "
                    + " ("
                    + " select Termid ,  DATE_FORMAT(Transdate, '%d/%m/%Y') as  Transdate,Cashierid , Transtype, Paymenttype,Paycurrency, round(Amount,2) as Amount ,Notes, DATE_FORMAT(Businessdate, '%d/%m/%Y') as  Businessdate,'RA' AS RAPO from {0}.rapo  Where date(BusinessDate) Between  @StartDT  and  @EndDt  And TransType in (0) "
                    + " Union all "
                    + " select Termid ,  DATE_FORMAT(Transdate, '%d/%m/%Y') as  Transdate,Cashierid , Transtype, Paymenttype,Paycurrency,round(Amount,2) as Amount,Notes,DATE_FORMAT(Businessdate, '%d/%m/%Y') as  Businessdate ,'PO' AS RAPO from  {0}.rapo  Where date(BusinessDate) Between   @StartDT  and  @EndDt  And TransType in (1) "
                    + " )H ");

                        string command = string.Format(QryAll, Cmb_BranchName);

                        MySqlParameter[] parameters =
                         {
                         new MySqlParameter("@StartDT",StartDT),
                         new MySqlParameter("@EndDt",EndDt),
                        };

                        DtVal1 = ObjMain.NewGetData_DT(command, parameters);


                        // Jquery Codde For Calculation  


                        decimal AmTT = 0;

                        for (int i = 0; i <= DtVal1.Rows.Count - 1; i++)
                        {
                            if (i > 0)
                            {

                                DtVal1.Rows.InsertAt(DtVal1.NewRow(), i);
                                DtVal1.Rows[i]["Amount"] = AmTT;

                                i++;

                            }
                            AmTT += Convert.ToDecimal(DtVal1.Rows[i]["Amount"]);

                        }


                        DtVal1.Rows.Add(DtVal1.NewRow());
                        DtVal1.Rows[DtVal1.Rows.Count - 1]["Amount"] = AmTT;


                        // Jquery Calculation End 

                        //Create a dummy GridView
                        GridView GridView1 = new GridView();
                        GridView1.ShowFooter = true;


                        GridView1.AllowPaging = false;
                        GridView1.DataSource = DtVal1;
                        GridView1.DataBind();
                        Response.Clear();
                        Response.Buffer = true;
                        Response.AddHeader("content-disposition",
                         "attachment;filename=RAPOALL.xls");
                        Response.Charset = "";
                        Response.ContentType = "application/vnd.ms-excel";
                        StringWriter sw = new StringWriter();
                        HtmlTextWriter hw = new HtmlTextWriter(sw);
                        for (int i = 0; i < GridView1.Rows.Count; i++)
                        {
                            //Apply text style to each Row
                            GridView1.Rows[i].Attributes.Add("class", "textmode");
                        }


                        GridView1.RenderControl(hw);

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


                    }
                    else if (cmbRAPO.SelectedIndex == 2)
                    {

                        string QryVal2 = ("select H.Termid , H.Transdate,H.Cashierid , H.Transtype, H.Paymenttype,H.Paycurrency,H.Amount,H.Notes,H.Businessdate ,H.RAPO from "
                        + " ("
                        + " select Termid,DATE_FORMAT(Transdate, '%d/%m/%Y') as  Transdate,Cashierid , Transtype, Paymenttype,Paycurrency,round(Amount,2) as Amount,Notes,DATE_FORMAT(Businessdate, '%d/%m/%Y') as  Businessdate,'RA' AS RAPO from {0}.rapo  Where date(BusinessDate) Between  @StartDT  and  @EndDt  And TransType in (0) "
                        + " Union all "
                        + " select Termid,DATE_FORMAT(Transdate, '%d/%m/%Y') as  Transdate,Cashierid , Transtype, Paymenttype,Paycurrency,round(Amount,2) as Amount,Notes,DATE_FORMAT(Businessdate, '%d/%m/%Y') as  Businessdate ,'PO' AS RAPO from {0}.rapo  Where date(BusinessDate) Between  @StartDT  and  @EndDt  And TransType in (1) "
                        + " )H  WHERE  H.RAPO='RA'");

                        string command1 = string.Format(QryVal2, Cmb_BranchName);
                        MySqlParameter[] parameters =
                        {
                     new MySqlParameter("@StartDT",StartDT),
                     new MySqlParameter("@EndDt",EndDt),
                    };

                        DtVal2 = ObjMain.NewGetData_DT(command1, parameters);


                        // Jquery Codde For Calculation  
                        decimal AmTT = 0;

                        for (int i = 0; i <= DtVal2.Rows.Count - 1; i++)
                        {
                            if (i > 0)
                            {

                                DtVal2.Rows.InsertAt(DtVal2.NewRow(), i);
                                DtVal2.Rows[i]["Amount"] = AmTT;

                                i++;

                            }
                            AmTT += Convert.ToDecimal(DtVal2.Rows[i]["Amount"]);

                        }


                        DtVal2.Rows.Add(DtVal2.NewRow());
                        DtVal2.Rows[DtVal2.Rows.Count - 1]["Amount"] = AmTT;


                        // Jquery Calculation End 




                        //Create a dummy GridView
                        GridView GridView1 = new GridView();
                        GridView1.ShowFooter = true;


                        GridView1.AllowPaging = false;
                        GridView1.DataSource = DtVal2;
                        GridView1.DataBind();
                        Response.Clear();
                        Response.Buffer = true;
                        Response.AddHeader("content-disposition",
                         "attachment;filename=ExportRA.xls");
                        Response.Charset = "";
                        Response.ContentType = "application/vnd.ms-excel";
                        StringWriter sw = new StringWriter();
                        HtmlTextWriter hw = new HtmlTextWriter(sw);
                        for (int i = 0; i < GridView1.Rows.Count; i++)
                        {
                            //Apply text style to each Row
                            GridView1.Rows[i].Attributes.Add("class", "textmode");
                        }


                        GridView1.RenderControl(hw);

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


                    }
                    else if (cmbRAPO.SelectedIndex == 3)
                    {

                        string QryVal3 = ("select H.Termid , H.Transdate,H.Cashierid , H.Transtype, H.Paymenttype,H.Paycurrency,H.Amount,H.Notes,H.Businessdate ,H.RAPO from "
                        + " ("
                        + " select Termid ,DATE_FORMAT(Transdate, '%d/%m/%Y') as  Transdate,Cashierid , Transtype, Paymenttype,Paycurrency,round(Amount,2) as Amount,Notes,DATE_FORMAT(Businessdate, '%d/%m/%Y') as  Businessdate,'RA' AS RAPO from {0}.rapo  Where date(BusinessDate) Between  @StartDT  and  @EndDt  And TransType in (0) "
                        + " Union all "
                        + " select Termid ,DATE_FORMAT(Transdate, '%d/%m/%Y') as  Transdate,Cashierid , Transtype, Paymenttype,Paycurrency,round(Amount,2) as Amount,Notes,DATE_FORMAT(Businessdate, '%d/%m/%Y') as  Businessdate ,'PO' AS RAPO from {0}.rapo  Where date(BusinessDate) Between  @StartDT  and  @EndDt  And TransType in (1) "
                        + " )H  WHERE  H.RAPO='PO'");

                        string command = string.Format(QryVal3, Cmb_BranchName);

                        MySqlParameter[] parameters =
                       {
                       new MySqlParameter("@StartDT",StartDT),
                       new MySqlParameter("@EndDt",EndDt),
                       };

                        DtVal3 = ObjMain.NewGetData_DT(command, parameters);

                        // Jquery Codde For Calculation  
                        decimal AmTT = 0;

                        for (int i = 0; i <= DtVal3.Rows.Count - 1; i++)
                        {
                            if (i > 0)
                            {

                                DtVal3.Rows.InsertAt(DtVal3.NewRow(), i);
                                DtVal3.Rows[i]["Amount"] = AmTT;

                                i++;

                            }
                            AmTT += Convert.ToDecimal(DtVal3.Rows[i]["Amount"]);

                        }


                        DtVal3.Rows.Add(DtVal3.NewRow());
                        DtVal3.Rows[DtVal3.Rows.Count - 1]["Amount"] = AmTT;


                        // Jquery Calculation End 

                        //Create a dummy GridView
                        GridView GridView1 = new GridView();
                        GridView1.ShowFooter = true;


                        GridView1.AllowPaging = false;
                        GridView1.DataSource = DtVal3;
                        GridView1.DataBind();
                        Response.Clear();
                        Response.Buffer = true;
                        Response.AddHeader("content-disposition",
                         "attachment;filename=ExportPO.xls");
                        Response.Charset = "";
                        Response.ContentType = "application/vnd.ms-excel";
                        StringWriter sw = new StringWriter();
                        HtmlTextWriter hw = new HtmlTextWriter(sw);
                        for (int i = 0; i < GridView1.Rows.Count; i++)
                        {
                            //Apply text style to each Row
                            GridView1.Rows[i].Attributes.Add("class", "textmode");
                        }


                        GridView1.RenderControl(hw);

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


                    }


                }


            }

        }


    }
}