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 static SunWeb.Model.CXeroItemSummary;
using static SunWeb.Model.CXeroPaymentSummary;
using static SunWeb.Model.CXeroItemSummaryV2;
using Newtonsoft.Json;
using System.Net;
using Newtonsoft.Json.Linq;
using SunWeb.Model;

namespace SUNWEB
{
    public partial class ZeroIntegration : System.Web.UI.Page
    {
        BL_API objAPI = new BL_API();
        MYSQLCLOUD ObjCloudMain = new MYSQLCLOUD();
        BL_SELECT ObjSel = new BL_SELECT();
        BLCompany ObjBL = new BLCompany();
        PLCOMMON ObjPL = new PLCOMMON();
        BL_USER ObjUserBL = new BL_USER(); //This Object for All User and Page Related fuctions included 
        PLCUSTOMER ObjCustPL = new PLCUSTOMER();
        Int32 K = 0;
        Int32 L = 0;
        Int32 S = 0;
        string ConStr = ConfigurationManager.ConnectionStrings["ConMysql"].ConnectionString;
        string ConStr_Rds = ConfigurationManager.ConnectionStrings["ConRDS"].ConnectionString;
        string Curr_Date = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        string Curr_DateOnly = System.DateTime.Now.ToString("yyyy-MM-dd");
        DateTime MonthstartDt;
        DataSet ds = new DataSet();
        MYSQLDB ObjMain = new MYSQLDB();
        DataTable DT = new DataTable();
        DataTable Dt1 = new DataTable();
        DataTable Dt2 = new DataTable();
        DataTable Dt3 = new DataTable();
        DataTable Dt4 = new DataTable();
        DataTable Dt5 = new DataTable();
        DataTable Dt6 = 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_ZeroIntegration = 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 sAccessToken = string.Empty;
        string sRefreshToken = string.Empty;
        string sTenantID = string.Empty;
        string sidToken = string.Empty;
        string saccessToken = string.Empty;
        string srefreshToken = string.Empty;
        string Stat1 = string.Empty;
        string Stat2 = string.Empty;
        string sXeroTokenURL = string.Empty;
        string sXeroURL = string.Empty;
        string sXeroAPIKey = string.Empty;
        string sXeroSecret = string.Empty;
        int iXeroSalesCode=0; //nid added on 10-Nov-2025
        int iXeroSVG = 0;   //nid added on 10-Nov-2025
        int iXeroGST = 0;   //nid added on 10-Nov-2025
        int iXeroRoundDiff = 0;    //nid added on 10-Nov-2025

        //int iXeroTaxType = 0;
        protected void Page_Load(object sender, EventArgs e)
        {

            PID = "54";    // This is for zerointegration 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_ZeroIntegration"].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);
            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_ZeroIntegration = DtLicense.Rows[0]["ZEROINTEGRATION"].ToString();
                Session["L_ZeroIntegration"] = L_ZeroIntegration;
            }
            if (Session["L_ZeroIntegration"].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("ZeroIntegration.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_ZeroIntegration = DtLicense.Rows[0]["ZEROINTEGRATION"].ToString();
                    Session["L_ZeroIntegration"] = L_ZeroIntegration;
                }
                if (Session["L_ZeroIntegration"].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 18-Jan-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_XeroAccessToken(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,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);
            GridView1.DataSource = Dt1;
            //gridview totals
            GridView1.DataBind();


        }

  
        public void Get_XeroAccessToken(string BranchAlias)
        {
            //for getting Xero Tokens
            sCmd = "Select accesstoken, refreshtoken, tenantid, xerotokenurl,xerourl,xeroapikey,xerosecret From {0}.XeroAuth";
            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]["tenantid"].ToString();
            //iXeroTaxType =  Dt4.Rows[0]["xeroTaxType"] == DBNull.Value? 0: Convert.ToInt32(Dt4.Rows[0]["xeroTaxType"]);

            Session["sXeroTokenURL"]= Dt4.Rows[0]["xerotokenurl"].ToString();
            Session["sXeroURL"] = Dt4.Rows[0]["xerourl"].ToString();
            Session["sXeroAPIKey"] = Dt4.Rows[0]["xeroapikey"].ToString();
            Session["sXeroSecret"] = Dt4.Rows[0]["xerosecret"].ToString();
            //Session["sXeroTaxType"] = Dt4.Rows[0]["xeroTaxType"] == DBNull.Value ? 0 : Convert.ToInt32(Dt4.Rows[0]["xeroTaxType"]);

            //Call AccessToken API
            string sResp = objAPI.Xero_GetAccessToken(sRefreshToken,Session["sXeroTokenURL"].ToString(),Session["sXeroAPIKey"].ToString (),Session["sXeroSecret"].ToString () );
            // Reading Json Data : 
            var ReadData = JObject.Parse(sResp.ToString());
            JArray ReadArray = new JArray();
            ReadArray.Add(ReadData);
            foreach (JToken ReadItem in ReadArray)
            {
                sidToken = ReadItem["id_token"].ToString();
                saccessToken = ReadItem["access_token"].ToString();
                srefreshToken = ReadItem["refresh_token"].ToString();
            }

            Session["SessionTenantID"] = sTenantID;
            sAccessToken = saccessToken;
            Session["sessionAccessToken"] = 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 "Xero Upload Summary Module"
        ////for upalod Sales summary to Xero 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 getting XeroContactID
        //    sCmd = "Select XeroContactID From {0}.XeroPOSContacts Where Contactname=@ContactName";
        //    string Command2 = string.Format(sCmd, BranchAlias);
        //    MySqlParameter[] parameters2 =
        //          {
        //             //new MySqlParameter("@ContactName","DemoPOS1"),
        //             new MySqlParameter("@ContactName",BranchAlias),
        //          };

        //    Dt3 = ObjMain.NewGetData_DT(Command2, parameters2);
        //    string sContactID = Dt3.Rows[0]["XeroContactID"].ToString();

        //    //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.Type = "ACCREC";
        //    //rootval.InvoiceNumber = Guid.NewGuid().ToString();
        //    //Session["InvNo"] = rootval.InvoiceNumber;
        //    ////rootval.DueDate = EndDt;
        //    //rootval.DueDate = Curr_DateOnly;
        //    //rootval.LineAmountTypes = "NoTax";
        //    ////rootval.LineAmountTypes = "Exclusive";
        //    //rootval.Status = "AUTHORISED";
        //    //ContactS croot = new ContactS();
        //    //List<LineItem> items = new List<LineItem>();
        //    //for (int i = 0; i <= Dt1.Rows.Count - 1; i++)
        //    //{
        //    //    LineItem _lineitem = new LineItem();
        //    //    _lineitem.ItemCode = Dt1.Rows[i]["Barcode"].ToString().Trim(); ;
        //    //    _lineitem.Description = Dt1.Rows[i]["InventoryDesc"].ToString().Trim();
        //    //    _lineitem.Quantity = (int)(double)Dt1.Rows[i]["Qty"];
        //    //    _lineitem.UnitAmount = (double)(decimal)Dt1.Rows[i]["Price"];
        //    //    _lineitem.DiscountRate = (int)(double)Dt1.Rows[i]["Disc"];
        //    //    _lineitem.AccountCode = "200";
        //    //    items.Add(_lineitem);
        //    //    croot.ContactID = sContactID;
        //    //}
        //    //rootval.Contact = croot;
        //    //rootval.LineItems = items;

        //    int iXeroTaxType = 0;
        //    int.TryParse(Session["sXeroTaxType"].ToString(), out iXeroTaxType);

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

        //    if (iXeroTaxType  == 0) { 
        //        //For JSon Preparation
        //       //Rootval rootval = new Rootval();

        //        rootval.Type = "ACCREC";
        //        rootval.InvoiceNumber = Guid.NewGuid().ToString();
        //        Session["InvNo"] = rootval.InvoiceNumber;
        //        //rootval.DueDate = EndDt;
        //        rootval.DueDate = Curr_DateOnly;
        //        rootval.LineAmountTypes = "NoTax";
        //        rootval.Status = "AUTHORISED";
        //        ContactS croot = new ContactS();
        //        List<LineItem> items = new List<LineItem>();
        //        for (int i = 0; i <= Dt1.Rows.Count - 1; i++)
        //        {
        //             LineItem _lineitem = new LineItem();
        //            _lineitem.ItemCode = Dt1.Rows[i]["Barcode"].ToString().Trim (); ;
        //            _lineitem.Description = Dt1.Rows[i]["InventoryDesc"].ToString().Trim();
        //            _lineitem.Quantity = (int)(double)Dt1.Rows[i]["Qty"];
        //            _lineitem.UnitAmount = (double)(decimal)Dt1.Rows[i]["Price"];
        //            _lineitem.DiscountRate = (int)(double)Dt1.Rows[i]["Disc"];
        //            _lineitem.AccountCode = "400";
        //            items.Add(_lineitem);
        //            croot.ContactID = sContactID;
        //        }
        //        rootval.Contact =croot ;
        //        rootval.LineItems = items;
        //    }
        //    else if(iXeroTaxType == 3)
        //    {
        //        // Root invoice object
        //        rootval.Type = "ACCREC";
        //        rootval.InvoiceNumber = Guid.NewGuid().ToString();
        //        Session["InvNo"] = rootval.InvoiceNumber;
        //        rootval.DueDate = Curr_DateOnly;
        //        rootval.LineAmountTypes = "Exclusive"; // GST exclusive
        //        //rootval.LineAmountTypes = "Inclusive"; // GST exclusive
        //        rootval.Status = "AUTHORISED";

        //        // Contact
        //        ContactS croot = new ContactS();
        //        croot.ContactID = sContactID;

        //        // Line items
        //        List<LineItem> items = new List<LineItem>();

        //        decimal serviceChargeRate = 0.10m;   // 10%
        //        decimal gstRate = 0.09m;             // 9%

        //        double subtotal = 0.0;

        //        // Loop through your POS DataTable
        //        for (int i = 0; i < Dt1.Rows.Count; i++)
        //        {
        //            LineItem _lineitem = new LineItem();
        //            _lineitem.ItemCode = Dt1.Rows[i]["Barcode"].ToString().Trim();
        //            _lineitem.Description = Dt1.Rows[i]["InventoryDesc"].ToString().Trim();
        //            _lineitem.Quantity = (int)(double)Dt1.Rows[i]["Qty"];
        //            _lineitem.UnitAmount = (double)(decimal)Dt1.Rows[i]["Price"];
        //            _lineitem.DiscountRate = (int)(double)Dt1.Rows[i]["Disc"];
        //            _lineitem.AccountCode = "400";
        //            _lineitem.TaxType = "TAX002"; // GST 9%

        //            // Calculate per-line discounted amount (round to 2 decimals)
        //            double lineTotal = _lineitem.UnitAmount * _lineitem.Quantity;
        //            double lineDiscountAmount = Math.Round(lineTotal * (_lineitem.DiscountRate / 100.0), 2);
        //            double discountedLineAmount = lineTotal - lineDiscountAmount;

        //            subtotal += discountedLineAmount;

        //            items.Add(_lineitem);
        //        }

        //        // Add service charge line
        //        //double serviceCharge = Math.Round(subtotal * (double)serviceChargeRate, 2);

        //        //LineItem serviceItem = new LineItem
        //        //{
        //        //    ItemCode = "SRVCHG",
        //        //    Description = $"Service Charge ({serviceChargeRate * 100}%)",
        //        //    Quantity = 1,
        //        //    UnitAmount = serviceCharge,
        //        //    DiscountRate = 0,
        //        //    AccountCode = "400",
        //        //    TaxType = "TAX002" // GST 9%
        //        //};

        //        //items.Add(serviceItem);

        //        // Final invoice
        //        rootval.Contact = croot;
        //        rootval.LineItems = items;


        //    }


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

        //    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
        //    var sResp1=objAPI.Xero_CreateInvoice(Session["sessionAccessToken"].ToString (), JsonSerializedData, Session["SessionTenantID"].ToString (), Session["sXeroURL"].ToString ());
        //    var obj1 = JsonConvert.DeserializeObject(sResp1);
        //    dynamic result1 = JsonConvert.DeserializeObject<dynamic>(obj1.ToString());
        //    Stat1 = result1.Status;

        //    //for Payment Summary
        //    sCmd = " Select TP.PaymentType as PaymentType, Sum(TP.PaymentAmount) as PaymentAmount, TP.BusinessDate as BusinessDate, XP.XeroCode as XCode " +
        //    " From {0}.TransPayment TP Left Outer Join {0}.Trans T on TP.TransID=T.TransID " +
        //    " Left Outer Join {0}.PaymentType PT on TP.PaymentType=PT.PaymentType" +
        //    " Left Outer Join {0}.XeroLinkPaymentType XP On PT.PaymentTypeID=XP.PaymentTypeID " +
        //    " Where TP.BusinessDate Between @StartDT  and  @EndDt " +
        //    " And T.TransStatus in (2) And T.NavSync=0  " +
        //    " Group By TP.PaymentType,TP.BusinessDate,XP.XeroCode" +
        //    " Order By 1,2;  ";

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

        //    Dt5 = ObjMain.NewGetData_DT(Command4, parameters4);
        //    for (int i = 0; i <= Dt5.Rows.Count - 1; i++)
        //    {
        //        //For JSon Preparation
        //        RootPay rootpay = new RootPay();

        //        AccountS crootAcc = new AccountS();
        //        InvoiceS crootInv = new InvoiceS();

        //        crootAcc.Code = Dt5.Rows[i]["XCode"].ToString();
        //        crootInv.InvoiceNumber = Session["InvNo"].ToString();    //GUID from the above

        //        rootpay.Invoice = crootInv;
        //        rootpay.Account = crootAcc;
        //        rootpay.Date = Dt5.Rows[i]["BusinessDate"].ToString();
        //        rootpay.Amount = (double)(decimal)Dt5.Rows[i]["PaymentAmount"];

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

        //        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
        //        var sresp2=objAPI.Xero_UpdatePaymentDetails(Session["sessionAccessToken"].ToString(), JsonSerializedData1, Session["SessionTenantID"].ToString(), Session["sXeroURL"].ToString ());
        //        var obj2 = JsonConvert.DeserializeObject(sresp2);
        //        dynamic result2 = JsonConvert.DeserializeObject<dynamic>(obj2.ToString());
        //        Stat2 = result1.Status;

        //    }
        //    if (Stat1=="OK" && Stat2=="OK")
        //    {
        //        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 XERO successfully ') ", true);
        //    }
        //    else
        //    {
        //        btnGetReports_Click(btnGetReports, EventArgs.Empty);
        //        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Sales Summary Upload has been Failed ') ", true);
        //    }



        //}
        #endregion


        #region "Xero Upload Summary Module V2"

        #region "Old Code with direct sales Amount V2"
        //for upalod Sales summary to Xero 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 getting XeroContactID
        //    sCmd = "Select XeroContactID From {0}.XeroPOSContacts Where Contactname=@ContactName";
        //    string Command2 = string.Format(sCmd, BranchAlias);
        //    MySqlParameter[] parameters2 =
        //          {
        //             //new MySqlParameter("@ContactName","DemoPOS1"),
        //             new MySqlParameter("@ContactName",BranchAlias),
        //          };

        //    Dt3 = ObjMain.NewGetData_DT(Command2, parameters2);
        //    string sContactID = Dt3.Rows[0]["XeroContactID"].ToString();

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

        //    Dt2 = ObjMain.NewGetData_DT(Command1, parameters1);

        //    //int iXeroTaxType = 0;
        //    //int.TryParse(Session["sXeroTaxType"].ToString(), out iXeroTaxType);

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

        //    rootval.Type = "ACCREC";
        //    rootval.InvoiceNumber = Guid.NewGuid().ToString();
        //    Session["InvNo"] = rootval.InvoiceNumber;
        //    rootval.DueDate = Curr_DateOnly;
        //    rootval.LineAmountTypes = "Inclusive";  // already includes GST
        //    rootval.Status = "AUTHORISED";

        //    // Contact
        //    ContactSV2 croot = new ContactSV2();
        //    croot.ContactID = sContactID;

        //    // Single summary line item
        //    List<LineItemV2> items = new List<LineItemV2>();
        //    LineItemV2 summaryLine = new LineItemV2
        //    {
        //        ItemCode = "SALES",
        //        //Description = $"Total POS sales from {Curr_DateOnly:yyyy-MM-dd}",
        //        Description = $"Total POS Sales From " + StartDT + " To " + EndDt + "(TransID: " + Dt2.Rows[0]["StartTransID"] + " - " + Dt2.Rows[0]["EndTransID"] + ")",
        //        Quantity = 1,
        //        UnitAmount = (double)(decimal)Dt2.Rows[0]["Total"],
        //        AccountCode = "200" // your sales account
        //    };
        //    items.Add(summaryLine);

        //    rootval.Contact = croot;
        //    rootval.LineItems = items;

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

        //    ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
        //    var sResp1 = objAPI.Xero_CreateInvoice(Session["sessionAccessToken"].ToString(), JsonSerializedData, Session["SessionTenantID"].ToString(), Session["sXeroURL"].ToString());
        //    var obj1 = JsonConvert.DeserializeObject(sResp1);
        //    dynamic result1 = JsonConvert.DeserializeObject<dynamic>(obj1.ToString());
        //    Stat1 = result1.Status;

        //    //for Payment Summary
        //    sCmd = " Select TP.PaymentType as PaymentType, Sum(TP.PaymentAmount) as PaymentAmount, TP.BusinessDate as BusinessDate, XP.XeroCode as XCode " +
        //    " From {0}.TransPayment TP Left Outer Join {0}.Trans T on TP.TransID=T.TransID " +
        //    " Left Outer Join {0}.PaymentType PT on TP.PaymentType=PT.PaymentType" +
        //    " Left Outer Join {0}.XeroLinkPaymentType XP On PT.PaymentTypeID=XP.PaymentTypeID " +
        //    " Where TP.BusinessDate Between @StartDT  and  @EndDt " +
        //    " And T.TransStatus in (2) And T.NavSync=0  " +
        //    " Group By TP.PaymentType,TP.BusinessDate,XP.XeroCode" +
        //    " Order By 1,2;  ";

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

        //    Dt5 = ObjMain.NewGetData_DT(Command4, parameters4);
        //    for (int i = 0; i <= Dt5.Rows.Count - 1; i++)
        //    {
        //        //For JSon Preparation
        //        RootPay rootpay = new RootPay();

        //        AccountS crootAcc = new AccountS();
        //        InvoiceS crootInv = new InvoiceS();

        //        crootAcc.Code = Dt5.Rows[i]["XCode"].ToString();
        //        crootInv.InvoiceNumber = Session["InvNo"].ToString();    //GUID from the above

        //        rootpay.Invoice = crootInv;
        //        rootpay.Account = crootAcc;
        //        rootpay.Date = Dt5.Rows[i]["BusinessDate"].ToString();
        //        rootpay.Amount = (double)(decimal)Dt5.Rows[i]["PaymentAmount"];

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

        //        ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
        //        var sresp2 = objAPI.Xero_UpdatePaymentDetails(Session["sessionAccessToken"].ToString(), JsonSerializedData1, Session["SessionTenantID"].ToString(), Session["sXeroURL"].ToString());
        //        var obj2 = JsonConvert.DeserializeObject(sresp2);
        //        dynamic result2 = JsonConvert.DeserializeObject<dynamic>(obj2.ToString());
        //        Stat2 = result1.Status;

        //    }
        //    if (Stat1 == "OK" && Stat2 == "OK")
        //    {
        //        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 XERO successfully ') ", true);
        //    }
        //    else
        //    {
        //        btnGetReports_Click(btnGetReports, EventArgs.Empty);
        //        ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Sales Summary Upload has been Failed ') ", true);
        //    }

        //}

        //Total + GST + SVG
        #endregion
        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 getting XeroContactID
            sCmd = "Select XeroContactID From {0}.XeroPOSContacts Where Contactname=@ContactName";
            string Command2 = string.Format(sCmd, BranchAlias);
            MySqlParameter[] parameters2 =
                  {
                     //new MySqlParameter("@ContactName","DemoPOS1"),
                     new MySqlParameter("@ContactName",BranchAlias),
                  };

            Dt3 = ObjMain.NewGetData_DT(Command2, parameters2);
            string sContactID = Dt3.Rows[0]["XeroContactID"].ToString();

            //for getting Xero Chart of accounts codes added on 10-Nov-2025
            sCmd = "Select Type,Code From {0}.XeroChartOfAccount";
            string Command6 = string.Format(sCmd, BranchAlias);
            MySqlParameter[] parameters6 =
                  {
                  };

            Dt6 = ObjMain.NewGetData_DT(Command6, parameters6);
            for (int i = 0; i <= Dt6.Rows.Count - 1; i++)
            {
                if (Dt6.Rows[i]["Type"].ToString() == "SALES")
                {
                    iXeroSalesCode = (int)Dt6.Rows[i]["Code"];
                    Session["sXeroSalesCode"] = (int)Dt6.Rows[i]["Code"];
                }
                if (Dt6.Rows[i]["Type"].ToString() == "SVG")
                {
                    iXeroSVG = (int)Dt6.Rows[i]["Code"];
                    Session["sXeroSVGCode"] = (int)Dt6.Rows[i]["Code"];
                }
                if (Dt6.Rows[i]["Type"].ToString() == "GST")
                {
                    iXeroGST = (int)Dt6.Rows[i]["Code"];
                    Session["sXeroGSTCode"] = (int)Dt6.Rows[i]["Code"];
                }
                if (Dt6.Rows[i]["Type"].ToString() == "ROUNDDIFF")
                {
                    iXeroRoundDiff = (int)Dt6.Rows[i]["Code"];
                    Session["sXeroRoundDiff"] = (int)Dt6.Rows[i]["Code"];
                }
            }


            //for Item Summary Total
            sCmd = "Select  MIN(T.TransID) as StartTransID,MAX(T.TransID) as EndTransID, Sum(Total) as Total, Sum(Round(SubTotal,2)-Round(DiscAmount,2)) as SubTotal, Round(Sum(TaxAmount1),2) As SVCHG, Round(Sum(TaxAmount2),2) as GST," +
            " Round(Sum(Total)- (Sum(Round(SubTotal,2)-Round(DiscAmount,2))+Round(Sum(TaxAmount1),2)+Round(Sum(TaxAmount2),2)),2) as RoundDiff " +
            " From {0}.Trans T " +
            " Where T.BusinessDate Between  @StartDT  and  @EndDt" +
            " And TransStatus in (2) And T.NavSync = 0;";
            string Command1 = string.Format(sCmd, BranchAlias);
            MySqlParameter[] parameters1 =
                  {
                     new MySqlParameter("@StartDT",StartDT),
                     new MySqlParameter("@EndDt",EndDt),
                  };

            Dt2 = ObjMain.NewGetData_DT(Command1, parameters1);

            //int iXeroTaxType = 0;
            //int.TryParse(Session["sXeroTaxType"].ToString(), out iXeroTaxType);

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

            rootval.Type = "ACCREC";
            rootval.InvoiceNumber = Guid.NewGuid().ToString();
            Session["InvNo"] = rootval.InvoiceNumber;
            rootval.Date = EndDt.ToString();
            rootval.DueDate = Curr_DateOnly;
            rootval.LineAmountTypes = "Inclusive";  // already includes GST
            rootval.Status = "AUTHORISED";

            // Contact
            ContactSV2 croot = new ContactSV2();
            croot.ContactID = sContactID;

            // Single summary line item
            List<LineItemV2> items = new List<LineItemV2>();

            items.Add(new LineItemV2
            {
                //ItemCode = "SALES",
                Description = $"Total POS Sales From " + StartDT + " To " + EndDt + "(TransID: " + Dt2.Rows[0]["StartTransID"] + " - " + Dt2.Rows[0]["EndTransID"] + ")",
                Quantity = 1,
                UnitAmount = (double)(decimal)Dt2.Rows[0]["SubTotal"],
                AccountCode = Session["sXeroSalesCode"].ToString(),
                //TaxType = "NONE"
            });

            items.Add(new LineItemV2
            {
                //ItemCode = "SVCHGAMT",
                Description = "Service Charge",
                Quantity = 1,
                UnitAmount = (double)(decimal)Dt2.Rows[0]["SVCHG"],
                AccountCode = Session["sXeroSVGCode"].ToString(),
                //TaxType = "NONE"
            });

            items.Add(new LineItemV2
            {
                //ItemCode = "GSTAMT",
                Description = "GST",
                Quantity = 1,
                UnitAmount = (double)(decimal)Dt2.Rows[0]["GST"],
                AccountCode = Session["sXeroGSTCode"].ToString(),
                //TaxType = "NONE"
            });

            items.Add(new LineItemV2
            {
                //ItemCode = "RoundDiff",
                Description = "RoundDiff",
                Quantity = 1,
                UnitAmount = (double)(decimal)Dt2.Rows[0]["RoundDiff"],
                AccountCode = Session["sXeroRoundDiff"].ToString(),
                //TaxType = "NONE"
            });

            rootval.Contact = croot;
            rootval.LineItems = items;

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

            ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
            var sResp1 = objAPI.Xero_CreateInvoice(Session["sessionAccessToken"].ToString(), JsonSerializedData, Session["SessionTenantID"].ToString(), Session["sXeroURL"].ToString());
            var obj1 = JsonConvert.DeserializeObject(sResp1);
            dynamic result1 = JsonConvert.DeserializeObject<dynamic>(obj1.ToString());
            Stat1 = result1.Status;

            //for Payment Summary
            sCmd = " Select TP.PaymentType as PaymentType, Sum(TP.PaymentAmount) as PaymentAmount, TP.BusinessDate as BusinessDate, XP.XeroCode as XCode " +
            " From {0}.TransPayment TP Left Outer Join {0}.Trans T on TP.TransID=T.TransID " +
            " Left Outer Join {0}.PaymentType PT on TP.PaymentType=PT.PaymentType" +
            " Left Outer Join {0}.XeroLinkPaymentType XP On PT.PaymentTypeID=XP.PaymentTypeID " +
            " Where TP.BusinessDate Between @StartDT  and  @EndDt " +
            " And T.TransStatus in (2) And T.NavSync=0  " +
            " Group By TP.PaymentType,TP.BusinessDate,XP.XeroCode" +
            " Order By 1,2;  ";

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

            Dt5 = ObjMain.NewGetData_DT(Command4, parameters4);
            for (int i = 0; i <= Dt5.Rows.Count - 1; i++)
            {
                //For JSon Preparation
                RootPay rootpay = new RootPay();

                AccountS crootAcc = new AccountS();
                InvoiceS crootInv = new InvoiceS();

                crootAcc.Code = Dt5.Rows[i]["XCode"].ToString();
                crootInv.InvoiceNumber = Session["InvNo"].ToString();    //GUID from the above

                rootpay.Invoice = crootInv;
                rootpay.Account = crootAcc;
                rootpay.Date = Dt5.Rows[i]["BusinessDate"].ToString();
                rootpay.Amount = (double)(decimal)Dt5.Rows[i]["PaymentAmount"];

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

                ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;
                var sresp2 = objAPI.Xero_UpdatePaymentDetails(Session["sessionAccessToken"].ToString(), JsonSerializedData1, Session["SessionTenantID"].ToString(), Session["sXeroURL"].ToString());
                var obj2 = JsonConvert.DeserializeObject(sresp2);
                dynamic result2 = JsonConvert.DeserializeObject<dynamic>(obj2.ToString());
                Stat2 = result1.Status;

            }
            if (Stat1 == "OK" && Stat2 == "OK")
            {
                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 XERO 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. */
        }





      




    }
}