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 System.Data;
using System.Web.UI.DataVisualization.Charting;
using System.Web;
using System.Web.Services;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Web.UI.HtmlControls;

namespace SUNWEB
{
    public partial class StockReport : System.Web.UI.Page
    {
        BL_SELECT ObjSel = new BL_SELECT();
        BLCompany ObjBL = new BLCompany();
        PLCOMMON ObjPL = new PLCOMMON();
        MYSQLCLOUD ObjCloudMain = new MYSQLCLOUD();
        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 M = 0;
        Int32 N = 0;
        Int32 O = 0;
        Int32 P = 0;
        Int32 S = 0;
        Int32 UpdateToInventoryCostAverageTable = 0;
        Int32 UpdateFromInventoryCostAverageTable = 0;


        Int32 UpdateTransferHeader = 0;
        Int32 iGetFromBranch = 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();
        MYSQLCLOUD ObjCloud = new MYSQLCLOUD();
        DataTable DT = new DataTable();
        DataTable Dt2 = new DataTable();
        DataTable DTTransferStock = new DataTable();
        DataTable DTInventory = new DataTable();
        DataTable DtLicense = new DataTable();
        DataTable DtSuperAdmin = new DataTable();
        DataTable DtMultiBranch = new DataTable();
        DataTable DtNormalUser = new DataTable();
        DataTable DtSearchInv = new DataTable();
        DataTable DTGetFromBranch = new DataTable();
        DataTable DTFromICA = new DataTable();
        DataTable DTToICA = new DataTable();
        DataTable DTSTOCKTRANSFERRPT = new DataTable();
        DataTable DTRECEIVETRANSFERRPT = new DataTable();
        DataTable DTvTRANSFERRPT = new DataTable();
        DataTable DTvRECEIVERPT = new DataTable();
        DataTable DTvRETURNRPT = new DataTable();
        DataSet DS = new DataSet();



        //MYSQLDB ObjMain = new MYSQLDB();
        MYSQLCLOUD ObjMainCloud = new MYSQLCLOUD();

        decimal totaltaxableamount = 0;
        decimal Gtotaltaxableamount = 0;

        decimal totaltaxamount = 0;
        decimal Gtotaltaxamount = 0;
        // 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;

        // 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;
        // NEW 
        string ActiveCallvalue = 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_Stock = 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 BranchAlias = string.Empty;
        string ISHQ = string.Empty;
        string sTableName = string.Empty;
        string sPackQty = string.Empty;
        string TransferID = string.Empty;
        // Added On 02-12-2021
        string ReadHQ = string.Empty;

       
        string RBranchid = string.Empty;
        string Branchid = string.Empty;
        string sFromDate = string.Empty;
        string sToDate = string.Empty;
        // Added On 02-12-2021
     
        protected void Page_Load(object sender, EventArgs e)
        {


            PID = "12"; //  This is for Stock Concepts
            if (!IsPostBack)
            {

                txtFromDt.Text = Curr_DateOnly;
                txtToDt.Text = Curr_DateOnly;


                //StockTransferRpt.Refresh();

            }
            if (Session["UserName"] == null)
            {
                Response.Redirect("Login.aspx");
            }
            //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)
                {
                    LoadBranchesOnID();
                    //LoadBranchName4SuperAdmin();
                    ActiveCall();
                    LoadTransferBranch(cmbBranches.SelectedItem.Text);
                }
            }
            else if (((Convert.ToBoolean(Session["IsSuperAdmin"])) == true) && (Session["PortalTypeId"].ToString() == ""))
            {
                if (!IsPostBack)
                {
                    LoadBranchesOnID();
                   // LoadBranchName4SuperAdmin();
                    // ActiveCall();
                }

                cd_BranchAlias = cmbBranches.SelectedItem.Text;
            }
            else if (((Convert.ToBoolean(Session["IsMultiBranch"])) == true) && (Session["PortalTypeId"].ToString() == ""))
            {

                if (!IsPostBack)
                {
                    //LoadBranchName();
                    LoadBranchesOnID();
                }

                cd_BranchAlias = cmbBranches.SelectedItem.Text;

            }
            else if (((Session["PortalTypeId"].ToString() != "") || (Convert.ToBoolean(Session["IsSuperAdmin"])) == false) && ((Convert.ToBoolean(Session["IsMultiBranch"])) == false))
            {
                cmbBranches.Enabled = false;
                cmbBranches.Visible = false;
                lblBranchAliasName.Text = "Welcome" + "&nbsp;&nbsp;" + Session["Branch_HQ"].ToString() + "&nbsp; !";
                cd_BranchAlias = Session["Branch_HQ"].ToString();
                Datapath = Session["DataPath"].ToString();
                PortalTypeId = Session["PortalTypeId"].ToString();
                PID = "12"; //  This is for Stock Concepts

                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_Stock"].ToString() == "N") || (Session["Page_Acess"].ToString() == "N"))
                {
                    Response.Redirect("DeniedPage.aspx");
                }
                else if (Session["Write_Acess"].ToString() == "N")
                {
                    Response.Redirect("DeniedPage.aspx");
                }
            }
            else
            {
                if (!IsPostBack)
                {

                    if (cmbBranches.Visible == true)
                    {
                        if (cmbBranches.Text == "Select Branch")
                        {

                        }
                    }
                    else
                    {
                        LoadTransferBranch(Session["Branch_HQ"].ToString());
                    }
                }
            }
        }

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

            #region  HQ Validation in ActiveCall Function : Starts 
            cd_BranchAlias = ActiveCallvalue;
            // HQ Validation For Loading Branch Name : Dropdown  Added Karthik  On 02-12-21 

            ReadHQ = ObjUserBL.GetBranchFullNameByBranchName(Session["Branch_HQ"].ToString(), cd_BranchAlias);

            if (ReadHQ == "HQ")
            {
                cmbBranches.Items.FindByText(ReadHQ).Selected = true;
            }
            else
            {
                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);

            }

            #endregion

            if (Branchidval != "")
            {
                DT = ObjUserBL.GetPageRightsDetailsPIDNew(Session["UserId"].ToString(), PID, Branchidval);
            }
            else
            {
                DT = ObjUserBL.GetPageRightsDetailsPIDNew(Session["UserId"].ToString(), PID, Session["Fistbranch"].ToString());

            }
            if (DT.Rows.Count > 0)
            {
                Page_Acess = DT.Rows[0]["Acess_status"].ToString();
                Read_Acess = DT.Rows[0]["Read_Access"].ToString();
                Write_Acess = DT.Rows[0]["Write_Access"].ToString();
                Isdowld_Acess = DT.Rows[0]["IDwld_Access"].ToString();

                Session["Page_Acess"] = Page_Acess;
                Session["Read_Acess"] = Read_Acess;
                Session["Write_Acess"] = Write_Acess;
                Session["Isdowld_Acess"] = Isdowld_Acess;
            }
            Rcd_id = ObjMain.ExecuteScalar("select cd_id from portaldb.companydetails where cd_branchid=" + Microsoft.Security.Application.Encoder.HtmlEncode(cmbBranches.SelectedItem.Value) + " and cd_branchalias='" + ActiveCallvalue + "';");
            RPortalid = ObjMain.ExecuteScalar("select portaltypeid  from portaldb.invoicedetails where cd_id=" + Rcd_id + ";");
            DtLicense = ObjUserBL.GetLicenseDetails(RPortalid);
            if (DtLicense.Rows.Count > 0)
            {
                L_Stock = DtLicense.Rows[0]["STOCK"].ToString(); 
                Session["L_Stock"] = L_Stock;
            }

            if ((Session["L_Stock"] == null) || Session["L_Stock"].ToString() == "N" || Session["Page_Acess"].ToString() == "N")
            {

                if (cmbBranches.SelectedItem.Text == "HQ")
                {


                }
                else
                {
                    Response.Redirect("DeniedPage.aspx");
                }

                
            }
            else if (Session["Write_Acess"].ToString() == "N")
            {
                Response.Redirect("DeniedPage.aspx");
            }
            else
            {
                // Load Part : 
            }
        }


        public void LoadBranchName4SuperAdmin()
        {
            //DtSuperAdmin = ObjUserBL.GetBranchOnSuperAdmin(Session["Branch_HQ"].ToString(), Session["UserId"].ToString());
            //if (DtSuperAdmin.Rows.Count > 0)
            //{
            //    cmbBranches.DataSource = DtSuperAdmin;
            //    cmbBranches.DataTextField = "BranchName";
            //    cmbBranches.DataValueField = "Branchid";
            //    cmbBranches.DataBind();
            //    cmbBranches.Items.Insert(0, "Select Branch");
            //}

            DtSuperAdmin = ObjUserBL.GetBranchOnSuperAdminWithHQ(Session["Branch_HQ"].ToString(), Session["UserId"].ToString());
            if (DtSuperAdmin.Rows.Count > 0)
            {
                cmbBranches.DataSource = DtSuperAdmin;
                cmbBranches.DataTextField = "BranchFullname";
                cmbBranches.DataValueField = "Branchid";
                cmbBranches.DataBind();
            }
        }

        public void LoadBranchName()
        {
            //DtNormalUser = ObjUserBL.GetBranchOnLoginValues(Session["Branch_HQ"].ToString(), Session["UserId"].ToString());
            //if (DtNormalUser.Rows.Count > 0)
            //{
            //    cmbBranches.DataSource = DtNormalUser;
            //    cmbBranches.DataTextField = "BranchName";
            //    cmbBranches.DataValueField = "Branchid";
            //    cmbBranches.DataBind();
            //    cmbBranches.Items.Insert(0, "Select Branch");
            //}
            DtNormalUser = ObjUserBL.GetBranchOnLoginValues8(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), Session["CM_ID"].ToString());
            if (DtNormalUser.Rows.Count > 0)
            {
                cmbBranches.DataSource = DtNormalUser;
                cmbBranches.DataTextField = "BranchName";
                cmbBranches.DataValueField = "Branchid";
                cmbBranches.DataBind();
                //cmbBranches.Items.Insert(0, "Select Branch");
            }
        }

        public void LoadTransferBranch(string BranchAlias)
        {
            string sDBname = ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), BranchAlias);
            //string sCmd = "Select BranchID,BranchFullname From " + sDBname + ".branches where BranchFullName <> '" + BranchAlias + "' order by branchID;";
            string sCmd = "Select BranchID,BranchFullname From {0}.branches  order by branchID;";
            string command = string.Format(sCmd, sDBname);

            DT = ObjMainCloud.GetData_DT(command);
            cmbSelectBranch.DataSource = DT;
            cmbSelectBranch.DataBind();
            cmbSelectBranch.DataTextField = "BranchFullname";
            cmbSelectBranch.DataValueField = "BranchID";
            cmbSelectBranch.DataBind();
            cmbSelectBranch.Items.Insert(0, "ALL");
        }

        public void UPDATEBRANCH(string ActiveCallvalue)
        {
            if (!string.IsNullOrEmpty(Session["UserId"] as string))
            {
                Useridvalue = Session["UserId"].ToString();
                QueryCurr_Select = "Update portaldb.usermaster set ActiveValue='" + ActiveCallvalue + "' where Userid=" + Useridvalue + "";
                S = ObjMain.ExecuteNonQuery(QueryCurr_Select);
            }
            else
            {
                Response.Redirect("Login.aspx");

            }

        }

        public void LoadBranchesOnID()
        {
            DT = ObjUserBL.GetBranchIDList(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), Session["CM_ID"].ToString());
            StringBuilder StrBObj = new StringBuilder();

            for (int i = 0; i < DT.Rows.Count; i++)
            {
                DataRow dr = DT.Rows[i];
                RBranchid = dr["Branchid"].ToString();
                if (StrBObj.Length != 0)
                {

                    RBranchid = "," + RBranchid;
                    StrBObj.Append("  " + RBranchid + "    ");
                }
                else
                {
                    string _get_HQ = ObjSel.GetHQ_Status(Session["CM_ID"].ToString());
                    if (_get_HQ == "0")
                    {

                        //UPDATEBRANCH(Cmb_BranchName);
                        //Response.Redirect(Request.RawUrl);
                        Branchid = RBranchid;
                        StrBObj.Append("SELECT  Branchid ,BranchName,branchfullname,datapath FROM " + Session["Branch_HQ"].ToString() + ".branches where branchid in ( " + Branchid + " ");


                    }
                    else if (_get_HQ == "1")
                    {
                        Branchid = RBranchid;
                        StrBObj.Append("SELECT  Branchid ,BranchName,branchfullname,datapath FROM " + Session["Branch_HQ"].ToString() + ".branches where branchid in (1 , " + Branchid + " ");


                    }


                }


            }
            StrBObj.Append(")");
            Dt2 = ObjCloudMain.GetData_DT(StrBObj.ToString());

            if (Dt2.Rows.Count > 0)
            {
                cmbBranches.DataSource = Dt2;
                cmbBranches.DataTextField = "branchfullname";
                cmbBranches.DataValueField = "Branchid";
                cmbBranches.DataBind();
                cmbBranches.Items.Insert(0, "Select Branch");
            }

        }


        protected void cmbBranches_SelectedIndexChanged(object sender, EventArgs e)
        {
            string sBranchSelected = ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), Microsoft.Security.Application.Encoder.HtmlEncode(cmbBranches.SelectedItem.Text));
            LoadTransferBranch(cmbBranches.SelectedItem.Text);
            UPDATEBRANCH(sBranchSelected);
            divConfirm.Attributes.Add("style", "display: none;");
        }

        [WebMethod(EnableSession = true)]
        public static string GetReportHeader(string Reporttype, string FromBranch, string ToBranch, string ConfirmStatus, string SendStatus, string FromDate, string ToDate, string TransferNo)
        {
            //string ReportType,string FromBranch,string ToBranch,string ConfirmStatus,string SendStatus,string FromDate, string ToDate
            BL_SELECT ObjSel = new BL_SELECT();
            // MYSQLCLOUD ObjMain = new MYSQLCLOUD();
            MYSQLDB MysqlObj = new MYSQLDB();
            DataTable DTHeader = new DataTable();

            string JSONResult = string.Empty;
            string sDateSelection = string.Empty;
            string ToBranchSelected = string.Empty;
            string sConfirmStatus = string.Empty;
            string sSendStatus = string.Empty;
            string sTransferNo = string.Empty;

            string FromBranchDB = ObjSel.GetBranchDBNamebyFullName(HttpContext.Current.Session["Branch_HQ"].ToString(), FromBranch); //Get Branch DB name by Branch Full Name
            string ToBranchDB = ObjSel.GetBranchDBNamebyFullName(HttpContext.Current.Session["Branch_HQ"].ToString(), ToBranch); //Get Branch DB name by Branch Full Name

            string FromBranchID = ObjSel.GetBranchIDbyName(FromBranchDB, FromBranch); //Get Branch ID from Branches table by Branch Full Name
            string ToBranchID = ObjSel.GetBranchIDbyName(FromBranchDB, ToBranch); //Get Branch ID from Branches table by Branch Full Name

            sDateSelection = "Where TransferDate between @D1 and @D2 ";

            if (ConfirmStatus == "NOT CONFIRM")
            {
                sConfirmStatus = " and ConfirmFlag = 0  ";
            }
            else if (ConfirmStatus == "CONFIRMED")
            {
                sConfirmStatus = " and ConfirmFlag = 1  ";
            }



            if (Reporttype == "STOCK TRANSFER")
            {
                if (ToBranch != "ALL")
                {
                    ToBranchSelected = " and tobranchid = @tobranchid ";
                }

                if (SendStatus == "NOT SEND")
                {
                    sSendStatus = " and SendFlag = 0  ";
                }
                else if (SendStatus == "SEND")
                {
                    sSendStatus = " and SendFlag = 1  ";
                }

                if (TransferNo != "")
                {
                    sTransferNo = " and TransferNo = '" + TransferNo + "'";
                }

                string Query = "Select  TransferID,'{1}' as fromBranchID,B.BranchFullName,TransferNo,TransferDate,ConfirmNo,SendDateTime,ConfirmDateTime from {0}.transferstock A " +
                             "join {0}.branches B on A.ToBranchID = B.BranchID " + sDateSelection + ToBranchSelected + sConfirmStatus + sSendStatus + sTransferNo + " group by A.transferID";
                string command = string.Format(Query, FromBranchDB, FromBranch);

                MySqlParameter[] parameters =
                   {
                     new MySqlParameter("@D1",FromDate),
                     new MySqlParameter("@D2",ToDate),
                     new MySqlParameter("@tobranchid",ToBranchID),


                    };


                DTHeader = MysqlObj.NewGetData_DT(command, parameters);

                JSONResult = JsonConvert.SerializeObject(DTHeader);
            }
            else if (Reporttype == "RECEIVE TRANSFER")
            {
                if (TransferNo != "")
                {
                    sTransferNo = " and ConfirmNo = '" + TransferNo + "'";
                }

                if (ToBranch != "ALL")
                {
                    ToBranchSelected = " and tobranchid =@tobranchid ";
                }

                string Query1 = "Select TransferID,'{1}' as fromBranchID,B.BranchFullName,TransferNo,date(ConfirmDateTime) as TransferDate,ConfirmNo,SendDateTime,ConfirmDateTime from {0}.receivestock A  " +
                           "Join {0}.Branches B on A.FromBranchID = B.BranchID " + sDateSelection + ToBranchSelected + sConfirmStatus + sSendStatus + sTransferNo;

                string command = string.Format(Query1, FromBranchDB, FromBranch);
                MySqlParameter[] parameters =
                {
                     new MySqlParameter("@D1",FromDate),
                     new MySqlParameter("@D2",ToDate),
                     new MySqlParameter("@tobranchid",FromBranchID),
                 };


                DTHeader = MysqlObj.NewGetData_DT(command, parameters);
                JSONResult = JsonConvert.SerializeObject(DTHeader);
            }
            else if (Reporttype == "RETURN TRANSFER")
            {
                if (TransferNo != "")
                {
                    sTransferNo = " and ReturnNo = '" + TransferNo + "'";
                }

                if (ToBranch != "ALL")
                {
                    ToBranchSelected = " and tobranchid = @tobranchdi ";
                }

                string sReturnDate = "Where date(ReturnDate) between @D1 and @D2 ";
                string Query2 = "Select ReturnID as TransferID,'{1}' as  fromBranchID,B.BranchFullName,TransferNo,ReturnDate as TransferDate,ReturnNo as ConfirmNo from {0}.returnstock A " +
                                " Join {0}.Branches B on A.FromBranchID = B.BranchID " + sReturnDate + ToBranchSelected + sTransferNo;
                string command = string.Format(Query2, FromBranchDB, FromBranch);
                MySqlParameter[] parameters =
                {
                    new MySqlParameter("@D1", FromDate),
                    new MySqlParameter("@D2", ToDate),
                    new MySqlParameter("@tobranchid",FromBranchID)
                };

                DTHeader = MysqlObj.NewGetData_DT(command, parameters);
                JSONResult = JsonConvert.SerializeObject(DTHeader);

            }

            return JSONResult;
        }

        [WebMethod]
        public static string GetReportDetails(string Reporttype, string FromBranch, string TransferID)
        {
            BL_SELECT ObjSel = new BL_SELECT();
            MYSQLCLOUD ObjMain = new MYSQLCLOUD();
            MYSQLDB MySqlObj = new MYSQLDB();
            DataTable DTDetails = new DataTable();

            string FromBranchDB = ObjSel.GetBranchDBNamebyFullName(HttpContext.Current.Session["Branch_HQ"].ToString(), FromBranch); //Get Branch DB name by Branch Full Name

            string JSONResult = string.Empty;
            if (Reporttype == "STOCK TRANSFER")
            {

                string Query = "Select A.BarCode,Inventoryname, Description, Unit, PackQuantity,Price,sum(PackQuantity * Price) as Amount from {0}.transferstockdetail  A " +
                                "join {0}.Inventory B on A.Barcode = B.Barcode " +
                                "where TransferID =@TransferID group by barcode;";

                string commmand = string.Format(Query, FromBranchDB);

                MySqlParameter[] parameters =
                {
                     new MySqlParameter("@TransferID",TransferID),
                };
                DTDetails = MySqlObj.NewGetData_DT(commmand, parameters);
                JSONResult = JsonConvert.SerializeObject(DTDetails);
            }
            else if (Reporttype == "RECEIVE TRANSFER")
            {
                string Query = "Select A.BarCode,Inventoryname, Description, Unit, AcceptQuantity as PackQuantity,Price,sum(AcceptQuantity * Price) as Amount  from {0}.receivestockdetail A " +
                                   "join {0}.Inventory B on A.Barcode = B.Barcode " +
                                    "where ReceiveID =@ReceiveID group by barcode;";

                string commmand = string.Format(Query, FromBranchDB);
                MySqlParameter[] parameters =
                {
                     new MySqlParameter("@ReceiveID",TransferID),
                };

                DTDetails = MySqlObj.NewGetData_DT(commmand, parameters);

                JSONResult = JsonConvert.SerializeObject(DTDetails);
            }
            else if (Reporttype == "RETURN TRANSFER")
            {
                string Query = "Select A.BarCode,Inventoryname,Description,Unit,ReturnQuantity as PackQuantity,Price,'0' Amount " +
                                " from {0}.returnstockdetail A " +
                                " join {0}.Inventory B on A.Barcode = B.Barcode where returnid = @ReturnID; ";
                string command = string.Format(Query, FromBranchDB);
                MySqlParameter[] parameters =
                {
                    new MySqlParameter("@ReturnID",TransferID),
                };
                DTDetails = MySqlObj.NewGetData_DT(command, parameters);
                JSONResult = JsonConvert.SerializeObject(DTDetails);
            }


            //string Qry1 = "Select A.BarCode,Description,PackUnit,AcceptQuantity as PackQuantity  from " + sBranchSelected + ".receivestockdetail A " +
            //                    "join " + sBranchSelected + ".Inventory B on A.Barcode = B.Barcode " +
            //                    "where ReceiveID ='" + sTransferid + "';";
            return JSONResult;
        }

        [WebMethod]
        public static string BranchList() {          
            DataTable DT = new DataTable();           
            MYSQLCLOUD ObjCloudMain = new MYSQLCLOUD();
            string JSONResult = string.Empty;

            string hqdb = HttpContext.Current.Session["Branch_HQ"].ToString();
            string sQuery = "SELECT  Branchid ,BranchName,branchfullname,datapath,branchprefix FROM {0}.branches";
            string command = string.Format(sQuery, hqdb);         
            DT = ObjCloudMain.GetData_DT(command);
            
            var json = JsonConvert.SerializeObject(DT.AsEnumerable().Select(r => r.ItemArray));          
            return json;
        }

        //Transfer Stock List
        [WebMethod]
        public static string GET_TransferStockList(string db)
        {
            BL_API objAPI = new BL_API();
            string bearertoken = string.Empty;
            bearertoken = objAPI.GetBarerToken();
            string json = objAPI.GET_TransferStockList(bearertoken, db);
            var obj = JsonConvert.DeserializeObject(json);
            return obj.ToString();
        }

        [WebMethod]
        public static string GET_ReceiveStockList(string db)
        {
            BL_API objAPI = new BL_API();
            string bearertoken = string.Empty;
            bearertoken = objAPI.GetBarerToken();
            string json = objAPI.GET_ReceiveStockList(bearertoken, db);
            var obj = JsonConvert.DeserializeObject(json);
            return obj.ToString();
        }

        [WebMethod]
        public static string GET_ReturnStockDetailList(string db)
        {
            BL_API objAPI = new BL_API();
            string bearertoken = string.Empty;
            bearertoken = objAPI.GetBarerToken();
            string json = objAPI.GET_ReturnStockDetailList(bearertoken, db);
            var obj = JsonConvert.DeserializeObject(json);
            return obj.ToString();
        }

    }
}