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 Newtonsoft.Json;
using System.Net;
using Newtonsoft.Json.Linq;
using static SunWeb.Model.CZohoItemSummary;
using static SunWeb.Model.CZhohoPaymentSummary;

namespace SUNWEB
{
    public partial class Zoho : 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();
        BL_API objAPI = new BL_API();
        MYSQLCLOUD ObjCloudMain = new MYSQLCLOUD();
        Int32 K = 0;
        Int32 L = 0;
        Int32 S = 0;
        string ConStr = ConfigurationManager.ConnectionStrings["ConMysql"].ConnectionString;
        string ConStr_Rds = ConfigurationManager.ConnectionStrings["ConRDS"].ConnectionString;
        string Curr_Date = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        string Curr_DateOnly = System.DateTime.Now.ToString("yyyy-MM-dd");
        DateTime MonthstartDt;
        DataSet ds = new DataSet();
        MYSQLDB ObjMain = new MYSQLDB();
        DataTable DT = new DataTable();
        DataTable Dt1 = new DataTable();
        DataTable Dt2 = new DataTable();
        DataTable Dt3 = new DataTable();
        DataTable Dt4 = new DataTable();
        DataTable DtLicense = new DataTable();
        DataTable DtSuperAdmin = new DataTable();
        DataTable DtMultiBranch = new DataTable();
        DataTable DtNormalUser = new DataTable();
        DataTable DTProductSale = new DataTable();
        MySqlCommand Cmdv = new MySqlCommand();
        // User Variables 
        string UserId = string.Empty;
        string UserName = string.Empty;
        string PortalTypeId = string.Empty;
        string cd_Id = string.Empty;
        string Datapath = string.Empty;
        string cd_BranchAlias = string.Empty;
        string IsMultiBranch = string.Empty;
        string IsSuperAdmin = string.Empty;
        string ActiveCallvalue = string.Empty;
        // License Variables ..
        string PID = string.Empty;
        string Page_Acess = string.Empty;
        string Read_Acess = string.Empty;
        string Write_Acess = string.Empty;
        string Isdowld_Acess = string.Empty;
        string Rcd_id = string.Empty;
        string RPortalid = string.Empty;
        string Useridvalue = string.Empty;
        string QueryCurr_Select = string.Empty;
        string L_MaxUserCnt = string.Empty;
        
        string L_Zoho = 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;

        string BraNam = "";
        string FDate = "";
        string TDate = "";
        string ExecQry = "";
        public string sCmd;

        string sZohoAccessToken = string.Empty;
        string sZohoRefreshToken = string.Empty;
        string sZohoTokenURL = string.Empty;
        string sZohoURL = string.Empty;
        string sZohoAPIKey = string.Empty;
        string sZohoSecret = string.Empty;
        string sTenantID = string.Empty;
        string srefreshToken = string.Empty;
        string Stat1 = string.Empty;
        string Stat2 = string.Empty;
        string saccessToken = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {

            PID = "57";    // This is for Zoho Integration Page 


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

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

                        }


                    }

                }

            }
            else
            {

            }


        }


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


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

            if (ISHQ != "")
            {
                ActiveCallvalue = ObjSel.GetFirstBranch(Session["Branch_HQ"].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);
            DT = ObjUserBL.GetPageRightsDetailsPIDNew(Session["UserId"].ToString(), PID, Branchidval);
            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_Zoho = DtLicense.Rows[0]["ZOHO"].ToString();
                Session["L_Zoho"] = L_Zoho;
            }
            if (Session["L_Zoho"].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 = cmbBranches.SelectedItem.Text;
                // BindGridview(ActiveCallvalue, txtStartDt.Text, txtEndDt.Text);
                System.Threading.Thread.Sleep(2000);

            }

        }


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

            }

        }

        protected void cmbBranches_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbBranches.SelectedIndex == 0)
            {
                Response.Redirect("Zoho.aspx", false);
            }
            else
            {
                DT = ObjUserBL.GetPageRightsDetailsPIDNew(Session["UserId"].ToString(), PID, cmbBranches.SelectedItem.Value);
                if (DT.Rows.Count > 0)
                {
                    Page_Acess = DT.Rows[0]["Acess_status"].ToString();
                    Read_Acess = DT.Rows[0]["Read_Access"].ToString();
                    Write_Acess = DT.Rows[0]["Write_Access"].ToString();
                    Isdowld_Acess = DT.Rows[0]["IDwld_Access"].ToString();

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

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

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

                }


                if (DtLicense.Rows.Count > 0)
                {

                    L_Zoho = DtLicense.Rows[0]["ZOHO"].ToString();
                    Session["L_Zoho"] = L_Zoho;
                }
                if (Session["L_Zoho"].ToString() == "N" || Session["Page_Acess"].ToString() == "N")
                {
                    Response.Redirect("DeniedPage.aspx", false);
                }
                else
                {
                    // Call The Report bind  function here 
                    //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;");
                    string StartDT = Microsoft.Security.Application.Encoder.HtmlEncode(txtStartDt.Text.Trim());
                    string EndDt = Microsoft.Security.Application.Encoder.HtmlEncode(txtEndDt.Text.Trim());
                    lblMsgTotalSelection.Text = "Search Result - from" + "&nbsp;&nbsp;" + StartDT + "&nbsp;&nbsp to &nbsp;&nbsp;" + EndDt;
                    cd_BranchAlias = Cmb_BranchName;
                    BraNam = cd_BranchAlias;
                    FDate = txtStartDt.Text;
                    TDate = txtEndDt.Text;
                    //BindGridview(cd_BranchAlias, FDate, TDate);


                }
            }
            UPDATEBRANCH(Cmb_BranchName);

        }


        //from here onwards form code begins 12-Aug-2024

        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 - Journal Report Between" + "&nbsp;&nbsp;&nbsp;" + txtFromDt.Text + "&nbsp;&nbsp;&nbsp;  And &nbsp;&nbsp;&nbsp;" + txtToDt.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");
                LoadJournalMainQuery(Session["Branch_HQ"].ToString(), StartDT, EndDt);
                System.Threading.Thread.Sleep(1000);
            }
            else if (cmbBranches.Visible == true)
            {
                //lblMsgTotalSelection.Text = "Search Result - Journal Report Between" + "&nbsp;&nbsp;&nbsp;" + txtFromDt.Text + "&nbsp;&nbsp;&nbsp;  And &nbsp;&nbsp;&nbsp;" + txtToDt.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");
                Curr_BranchFullName = cmbBranches.SelectedItem.Text;
                cd_BranchAlias = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), Curr_BranchFullName);  // This will Return BranchName( Actual Database Name )
                BraNam = cd_BranchAlias;
                FDate = txtStartDt.Text;
                TDate = txtEndDt.Text;
                LoadJournalMainQuery(cd_BranchAlias, StartDT, EndDt);
            }
        }

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

            //For AccessToken
            Get_ZohoAccessToken(BranchAlias);

            System.Threading.Thread.Sleep(1000);

            // Prevents SQL Injection  : 01-09-21
            // Parameterized Approach 


            sCmd = " Select Date(T.BusinessDate) as BusinessDate,TD.Barcode as Barcode,TD.InventoryDesc as InventoryDesc, Sum(TD.QTY) as Qty,Round(TD.Price,2) as Price,Round(TD.DiscValue*100,2) as Disc " +
                " From {0}.Trans T Left Outer Join {0}.TransDetail TD On T.TransID=TD.TransID" +
                " Where T.TransStatus = 2 And T.NavSync = 0 And TD.ItemStatus <> 1" +
                " And T.BusinessDate Between  @StartDT  and  @EndDt " +
                " Group By T.BusinessDate,TD.Barcode, TD.InventoryDesc,TD.Price,TD.DiscValue" +
                " Order by 1,2;  ";

            string Command = string.Format(sCmd, BranchAlias);
            MySqlParameter[] parameters =
                  {
                     new MySqlParameter("@StartDT",StartDT),
                     new MySqlParameter("@EndDt",EndDt),
                  };


            Dt1 = ObjMain.NewGetData_DT(Command, parameters);
            GridView1.DataSource = Dt1;
            //gridview totals
            GridView1.DataBind();


        }

        public void Get_ZohoAccessToken(string BranchAlias)
        {
            //for getting Xero Tokens
            sCmd = "Select accesstoken, refreshtoken,  clientid, clientsecret, zohoTokenURL, zohoURL, contact_id, organizationID From {0}.zohoAuth";
            string Command3 = string.Format(sCmd, BranchAlias);
            MySqlParameter[] parameters3 =
                  {
                  };

            Dt4 = ObjMain.NewGetData_DT(Command3, parameters3);
            //sAccessToken = Dt4.Rows[0]["accesstoken"].ToString();
            //sRefreshToken = Dt4.Rows[0]["refreshtoken"].ToString();
            //sTenantID = Dt4.Rows[0]["clientid"].ToString();
            Session["sZohoAccessToken"]= Dt4.Rows[0]["accesstoken"].ToString();
            Session["sZohoRefreshToken"] = Dt4.Rows[0]["refreshtoken"].ToString();
            Session["sZohoTokenURL"] = Dt4.Rows[0]["zohotokenurl"].ToString();
            Session["sZohoURL"] = Dt4.Rows[0]["zohourl"].ToString();
            Session["sZohoClientID"] = Dt4.Rows[0]["clientid"].ToString();
            Session["sZohoSecret"] = Dt4.Rows[0]["clientsecret"].ToString();
            Session["sZohoContactID"] = Dt4.Rows[0]["contact_id"].ToString();
            Session["sZohoOrganizationID"] = Dt4.Rows[0]["organizationID"].ToString();
            //Call AccessToken API
            string sResp = objAPI.Zoho_GetAccessToken (Session["sZohoRefreshToken"].ToString (), Session["sZohoTokenURL"].ToString(), Session["sZohoClientID"].ToString(), Session["sZohoSecret"].ToString());
            // Reading Json Data : 
            var ReadData = JObject.Parse(sResp.ToString());
            JArray ReadArray = new JArray();
            ReadArray.Add(ReadData);
            foreach (JToken ReadItem in ReadArray)
            {
                saccessToken = ReadItem["access_token"].ToString();
            }

            //Session["SessionTenantID"] = sTenantID;
            //sAccessToken = saccessToken;
            Session["sessionZohoAccessToken"] = saccessToken;
            //sRefreshToken = srefreshToken;
            //Session["sessionRefreshToken"] = srefreshToken;

            // Update XeroAuth 
            //string Curr_Date = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
            //string QueryUPT = "UPDATE {0}.xeroauth SET accesstoken='" + saccessToken + "', idtoken='" + sidToken + "', refreshtoken='" + srefreshToken + "',gendate='" + Curr_Date + "' ";
            //string commandM = string.Format(QueryUPT, BranchAlias);
            //int U = ObjCloudMain.ExecuteNonQuery(commandM);


        }


        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {

        }
        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs 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)
            {
                GridView1.PageIndex = e.NewPageIndex;
                LoadJournalMainQuery(Session["Branch_HQ"].ToString(), StartDT, EndDt);
            }
            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 )

                GridView1.PageIndex = e.NewPageIndex;
                LoadJournalMainQuery(Cmb_BranchName, StartDT, EndDt);
            }
        }


        #region "Zoho Upload Summary Module"
        //for upalod Sales summary to Zoho system
        public void btnUploadSales_Click(object sender, EventArgs e)
        {
            string BranchAlias = "";
            // 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)
            {
                BranchAlias = Session["Branch_HQ"].ToString();
            }
            else
            {
                BranchFullName = Microsoft.Security.Application.Encoder.HtmlEncode(cmbBranches.SelectedItem.Text);    // This will Return Branch FullName 
                BranchAlias = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);  // This will Return BranchName( Actual Database Name )
            }

  
            //for Item Summary Total
            sCmd = "Select Sum(Total) as Total, Sum(TaxAmount1) as TaxAmount1,Sum(TaxAmount2) as TaxAmount2,Sum(TaxAmount3) as TaxAmoun3" +
                " From {0}.Trans T " +
                " Where T.BusinessDate Between  @StartDT  and  @EndDt" +
                " And TransStatus in (2);";
            string Command1 = string.Format(sCmd, BranchAlias);
            MySqlParameter[] parameters1 =
                  {
                     new MySqlParameter("@StartDT",StartDT),
                     new MySqlParameter("@EndDt",EndDt),
                  };

            Dt2 = ObjMain.NewGetData_DT(Command1, parameters1);

            //for item details
            sCmd = " Select Date(T.BusinessDate) as BusinessDate,TD.Barcode as Barcode,TD.InventoryDesc as InventoryDesc, Sum(TD.QTY) as Qty,TD.Price as Price,TD.DiscValue*100 as Disc " +
            " From {0}.Trans T Left Outer Join {0}.TransDetail TD On T.TransID=TD.TransID" +
            " Where T.TransStatus = 2 And T.NavSync = 0 And TD.ItemStatus <> 1" +
            " And T.BusinessDate Between  @StartDT  and  @EndDt " +
            " Group By T.BusinessDate,TD.Barcode, TD.InventoryDesc,TD.Price,TD.DiscValue" +
            " Order by 1,2;  ";

            string Command = string.Format(sCmd, BranchAlias);
            MySqlParameter[] parameters =
                  {
                     new MySqlParameter("@StartDT",StartDT),
                     new MySqlParameter("@EndDt",EndDt),
                  };

            Dt1 = ObjMain.NewGetData_DT(Command, parameters);

            //For JSon Preparation
            Rootval rootval = new Rootval();

            rootval.customer_id = Session["sZohoContactID"].ToString ();
            rootval.reference_number  = Guid.NewGuid().ToString();
            Session["InvNo"] = rootval.reference_number ;
            List<LineItem> items = new List<LineItem>();
            for (int i = 0; i <= Dt1.Rows.Count - 1; i++)
            {
                LineItem _lineitem = new LineItem();
                _lineitem.name = Dt1.Rows[i]["InventoryDesc"].ToString(); 
                _lineitem.quantity = (double)Dt1.Rows[i]["Qty"];
                _lineitem.rate  = Convert.ToDecimal(Dt1.Rows[i]["Price"]);

                items.Add(_lineitem);
            }
            rootval.line_items = items;
            rootval.due_date = EndDt;
            rootval.status = "sent";

            string JsonSerializedData = JsonConvert.SerializeObject(rootval, Formatting.Indented);
            object JsonDeSerializedData = JsonConvert.DeserializeObject(JsonSerializedData);

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            var sResp1 = objAPI.Zoho_CreateInvoice(Session["sessionZohoAccessToken"].ToString(), Session["sZohoURL"].ToString(),JsonSerializedData, Session["sZohoOrganizationID"].ToString());
            var obj1 = JsonConvert.DeserializeObject(sResp1);
            dynamic result1 = JsonConvert.DeserializeObject<dynamic>(obj1.ToString());
            Stat1 = result1.code;
            if (Stat1!="0" )
            {
                return;
            }
            Session["Invoice_ID"] = result1.invoice.invoice_id;
            
            ////for Payment Summary
            sCmd = " Select TP.PaymentType as PaymentType, Sum(TP.PaymentAmount) as PaymentAmount " +
            " From {0}.TransPayment TP Left Outer Join {0}.Trans T on TP.TransID=T.TransID " +
            " Where TP.BusinessDate Between @StartDT  and  @EndDt " +
            " And T.TransStatus in (2) And T.NavSync=0  " +
            " Group By TP.PaymentType" +
            " Order By 1,2;  ";

            string Command4 = string.Format(sCmd, BranchAlias);
            MySqlParameter[] parameters4 =
                  {
                     new MySqlParameter("@StartDT",StartDT),
                     new MySqlParameter("@EndDt",EndDt),
                  };

            Dt3 = ObjMain.NewGetData_DT(Command4, parameters4);
            for (int i = 0; i <= Dt3.Rows.Count - 1; i++)
            {
                //For JSon Preparation
                RootValP rootvalp = new RootValP();
                //Invoice crootInv = new Invoice();

                rootvalp.customer_id  = Session["sZohoContactID"].ToString();
                rootvalp.payment_mode = Dt3.Rows[i]["PaymentType"].ToString();
                rootvalp.amount  = (double)(decimal)Dt3.Rows[i]["PaymentAmount"];
                rootvalp.date  = EndDt;
                rootvalp.reference_number = Session["InvNo"].ToString();
                rootvalp.bank_charges = 0;

               
                List<Invoice> invoice = new List<Invoice>();
                for (int k = 0; k < 1; k++)
                {
                    Invoice _invoice = new Invoice();
                    _invoice.invoice_id = Session["Invoice_ID"].ToString();
                    _invoice.amount_applied  = (double)(decimal)Dt3.Rows[i]["PaymentAmount"];
                    invoice.Add(_invoice);
                }
                rootvalp.invoices  = invoice ;


                string JsonSerializedData1 = JsonConvert.SerializeObject(rootvalp, Formatting.Indented);
                object JsonDeSerializedData1 = JsonConvert.DeserializeObject(JsonSerializedData1);

                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                var sresp2 = objAPI.Zoho_CreatePayment(Session["sessionZohoAccessToken"].ToString(), Session["sZohoURL"].ToString(), JsonSerializedData1, Session["sZohoOrganizationID"].ToString());
                var obj2 = JsonConvert.DeserializeObject(sresp2);
                dynamic result2 = JsonConvert.DeserializeObject<dynamic>(obj2.ToString());
                Stat2 =  result2.code;
                if (Stat2 != "0")
                {
                    return;
                }

            }
            //Final
            if (Stat1 == "0" && Stat2 == "0")
            {
                sCmd = "Update {0}.Trans Set NavSync=1 Where BusinessDate Between @StartDT  and  @EndDt ";
                string Command5 = string.Format(sCmd, BranchAlias);
                MySqlParameter[] parameters5 =
                    {
                     new MySqlParameter("@StartDT",StartDT),
                     new MySqlParameter("@EndDt",EndDt),
                    };
                int U = ObjCloudMain.ExecuteQuery(Command5, parameters5);

                btnGetReports_Click(btnGetReports, EventArgs.Empty);
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Sales Summary uploaded to Zoho successfully ') ", true);
            }
            else
            {
                btnGetReports_Click(btnGetReports, EventArgs.Empty);
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Sales Summary Upload has been Failed ') ", true);
            }






        }
        #endregion 







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











    }
}