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


namespace SUNWEB
{
    public partial class ReceivingStockTransfer : System.Web.UI.Page
    {
        BL_SELECT ObjSel = new BL_SELECT();
        BLCompany ObjBL = new BLCompany();
        PLCOMMON ObjPL = new PLCOMMON();
        BL_USER ObjUserBL = new BL_USER(); //This Object for All User and Page Related fuctions included 
        PLCUSTOMER ObjCustPL = new PLCUSTOMER();
        Int32 K = 0;
        Int32 L = 0;
        Int32 M = 0;
        Int32 N = 0;
        Int32 O = 0;
        Int32 P = 0;
        Int32 UpdateToInventoryCostAverageTable = 0;
        Int32 UpdateFromInventoryCostAverageTable = 0;


        Int32 UpdateTransferHeader = 0;
        Int32 iGetFromBranch = 0;
        Int32 iInsertHeader = 0;
        Int32 iInsertDetail = 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();

        //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;
        string Branch;
        //string sReturnNo = string.Empty;

        string Search;
        string gTransferNo = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {


            //if (!IsPostBack)
            //{
            //LoadBranchName4SuperAdmin();
            //}

            if (!IsPostBack)
            {

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

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


            }
            else if (((Convert.ToBoolean(Session["IsSuperAdmin"])) == true) && (Session["PortalTypeId"].ToString() == ""))
            {
                if (!IsPostBack)
                {
                    LoadBranchName4SuperAdmin();
                }


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

                if (!IsPostBack)
                {
                    LoadBranchName();
                }

                cd_BranchAlias = cmbBranches.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 = "3"; //  This is for ItemSale 


            }
            else
            {

            }


            // txtTransDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
            txtTransDate.Text = Curr_DateOnly;

            //Load Selected Transfer No.



            if (!IsPostBack)
            {

                if (cmbBranches.Visible == true)
                {
                    if (cmbBranches.Text == "Select Branch")
                    {
                        //LoadToBranch(cmbBranches.SelectedItem.Text);
                        //LoadRefNo(cmbBranches.SelectedItem.Text);
                        //LoadItems(cmbBranches.SelectedItem.Text);
                    }
                }
                else
                {
                    //LoadToBranch(Session["Branch_HQ"].ToString());
                    //LoadRefNo(Session["Branch_HQ"].ToString());
                    //LoadItems(Session["Branch_HQ"].ToString());
                    //LoadTransferDetails(Session["Branch_HQ"].ToString(), "");
                }
            }

            if (!IsPostBack)
            {
                if (Request.QueryString["TransferNo"] != null)
                {
                    gTransferNo = Request.QueryString["TransferNo"].ToString();
                    txtRefNo.Text = Request.QueryString["TransferNo"].ToString();
                    Branch = Request.QueryString["ToBranch"].ToString();
                    string Branch2 = Request.QueryString[0].ToString();
                    cmbBranches.Text = ObjSel.GetBranchFullNameByDB(Branch);
                    //string sReceiveID = ObjSel.GetReceiveIDbyTransferNo(Session["Branch_HQ"].ToString(), txtRefNo.Text.Trim());
                    //GetTransferStockHeader(Session["Branch_HQ"].ToString(), sReceiveID);
                    //GetFromBranch(Session["Branch_HQ"].ToString(), sReceiveID);
                    //LoadTransferDetails(Session["Branch_HQ"].ToString(), sReceiveID);
                    string sReceiveID = ObjSel.GetReceiveIDbyTransferNo(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text), txtRefNo.Text.Trim());
                    GetTransferStockHeader(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text), sReceiveID);
                    GetFromBranch(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text), sReceiveID);
                    LoadTransferDetails(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text), sReceiveID);

                    txtUser.Text = ObjSel.GetUserNamebyUserID(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text), int.Parse(Session["UserId"].ToString()));

                    Session["DB"] = ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text);
                    Session["TransferID"] = ObjSel.GetReceiveIDbyTransferNo(Session["DB"].ToString(), gTransferNo);
                }
            }
            if (txtConfirmStatus.Text == "CONFIRMED")
            {
                btnReceive.Enabled = false;
                txtNotes.Enabled = false;
                foreach (GridViewRow gvr in grdReceiveDetails.Rows)
                {
                    TextBox txtAcceptQTY = ((TextBox)gvr.FindControl("txtAcceptQTY"));
                    txtAcceptQTY.Enabled = false;        
                }

            }
            else
            {
                btnReceive.Enabled = true;
                txtNotes.Enabled = true;
            }

            txtRefNo.CssClass = "form-control";
            txtTransDate.CssClass = "form-control";
            txtFBranch.CssClass = "form-control";
            txtSendDate.CssClass = "form-control";
            txtConfirm.CssClass = "form-control";
            txtConfirmStatus.CssClass = "form-control";
            txtNotes.CssClass = "form-control";
        }

        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 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 LoadTransferDetails(string Branch_AliasName, string sReceiveID)
        {
            //string sCmd = "Select B.Barcode,B.InventoryName,B.Description,'PCS' as unit,PackUnit,SendQuantity ,if(AcceptQuantity=0,SendQuantity,AcceptQuantity)as Accept,RejectQuantity as Rejected " +
            //                "from " + Branch_AliasName + ".receivestockdetail A Join  " + Branch_AliasName + ".Inventory B on " +
            //                "A.barcode=B.barcode where ReceiveID = '" + sReceiveID + "';";
            string sCmd = "Select B.Barcode,B.InventoryName,B.Description,'PCS' as unit,PackUnit,SendQuantity ,if(AcceptQuantity=0,SendQuantity,AcceptQuantity)as Accept,RejectQuantity as Rejected " +
                            "from {0}.receivestockdetail A Join  {0}.Inventory B on " +
                            "A.barcode=B.barcode where ReceiveID = @receiveid;";
            string command = string.Format(sCmd, Branch_AliasName);
            MySqlParameter[] parameters = {
                new MySqlParameter("@receiveid",sReceiveID)
            };
            //DT = ObjMainCloud.GetData_DT(sCmd);
            DT = ObjMain.NewGetData_DT(command, parameters);
            grdReceiveDetails.DataSource = DT;
            grdReceiveDetails.DataBind();



        }

        public void GetTransferStockHeader(string sBranchAlias, string sTransferID)
        {
            //string sCmd = "Select transferno,date_format(transferdate,'%Y-%m-%d') as transferdate,date_format(senddatetime,'%Y-%m-%d')  as senddatetime, " +
            //               "confirmno,date_format(confirmdatetime,'%Y-%m-%d') as confirmdatetime, " +
            //               "IF(confirmflag=0,'PENDING','CONFIRMED') as confirmflag from " + sBranchAlias + ".receivestock where receiveid = '" + sTransferID + "';";
            string sCmd = "Select transferno,date_format(transferdate,'%Y-%m-%d') as transferdate,date_format(senddatetime,'%Y-%m-%d')  as senddatetime, " +
                          "confirmno,date_format(confirmdatetime,'%Y-%m-%d') as confirmdatetime, " +
                          "IF(confirmflag=0,'PENDING','CONFIRMED') as confirmflag,TNotes from {0}.receivestock where receiveid = @receiveid;";
            string command = string.Format(sCmd,sBranchAlias);
            MySqlParameter[] parameters = {
                new MySqlParameter("@receiveid",sTransferID)
            };
            //DTTransferStock = ObjMainCloud.GetData_DT(sCmd);
            DTTransferStock = ObjMain.NewGetData_DT(command, parameters);
            if (DTTransferStock.Rows.Count > 0)
            {
                txtTransDate.Text = DTTransferStock.Rows[0]["TransferDate"].ToString();
                txtSendDate.Text = DTTransferStock.Rows[0]["senddatetime"].ToString();
                txtConfirm.Text = DTTransferStock.Rows[0]["confirmno"].ToString();
                txtConfirmStatus.Text = DTTransferStock.Rows[0]["confirmflag"].ToString();
                txtNotes.Text = DTTransferStock.Rows[0]["TNotes"].ToString();
            }

        }

        public void ConfirmReceiveStock(string sBranchAlias, string sReceiveID)
        {
            string sBranchDB = ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), txtFBranch.Text);
            string sConfirmNo = ObjSel.GetBranchPrefix(sBranchAlias, cmbBranches.Text).ToString() + "-" + ObjSel.GenerateConfirmNo(sBranchDB);
            string sConfirmDateTime = Curr_Date;
            string sConfrimFlag = "1";
            string sTNotes =txtNotes.Text;
            //string sCmd = "Update  " + sBranchAlias + ".receivestock " +
            //               "Set confirmno= '" + sConfirmNo + "',confirmdatetime = '" + Convert.ToDateTime(sConfirmDateTime) + "',confirmflag='" + sConfrimFlag + "', TNotes = '" + sTNotes + "', EmployeeName ='" + txtUser.Text + "'" +
            //                "where receiveid = '" + sReceiveID + "'";
            //N = ObjCloud.ExecuteNonQuery(sCmd);
            string sCmd = "Update  {0}.receivestock " +
                          " Set confirmno= @confirmno,confirmdatetime = @confirmdatetime,confirmflag=@confirmflag, TNotes = @notes, EmployeeName = @employeename" +
                          " where receiveid = @receiveid";
            string command = string.Format(sCmd, sBranchAlias);
            MySqlParameter[] parameters =
            {
                new MySqlParameter("@confirmno",sConfirmNo),
                new MySqlParameter("@confirmdatetime",Curr_Date),
                new MySqlParameter("@confirmflag",sConfrimFlag),
                new MySqlParameter("@notes",sTNotes),
                new MySqlParameter("@employeename",txtUser.Text),
                new MySqlParameter("@receiveid",sReceiveID)
            };

            N = ObjCloud.ExecuteQuery(command, parameters);



            string sReceivedQTY;
            string sAcceptQTY;
            for (int i = 0; i <= grdReceiveDetails.Rows.Count - 1; i++)
            {
                Int32 iRejectedQTY = 0;
                TextBox ReceivedQTY = (TextBox)grdReceiveDetails.Rows[i].Cells[5].FindControl("txtReceivedQTY");
                TextBox AcceptQTY = (TextBox)grdReceiveDetails.Rows[i].Cells[6].FindControl("txtAcceptQTY");
                sReceivedQTY = ReceivedQTY.Text;
                sAcceptQTY = AcceptQTY.Text;
                iRejectedQTY = Convert.ToInt32(sReceivedQTY) - Convert.ToInt32(sAcceptQTY);

                Label lBarcode = (Label)grdReceiveDetails.Rows[i].Cells[0].FindControl("lblBarcode");
                //string sCmdi = "update " + sBranchAlias + ".receivestockdetail set AcceptQuantity = '" + AcceptQTY.Text + "',RejectQuantity = '" + iRejectedQTY.ToString() + "' where barcode = '" + lBarcode.Text + "' and receiveid = '" + sReceiveID + "' ";
                //O = ObjCloud.ExecuteNonQuery(sCmdi);
                string sCmdi = "update {0}.receivestockdetail set AcceptQuantity = @acceptquantity,RejectQuantity = @rejectedquantity where barcode = @barcode and receiveid = @receiveid ";
                string command1 = string.Format(sCmdi,sBranchAlias);
                MySqlParameter[] parameter1 =
                {
                    new MySqlParameter("@acceptquantity",AcceptQTY.Text),
                    new MySqlParameter("@rejectedquantity",iRejectedQTY.ToString()),
                    new MySqlParameter("@barcode",lBarcode.Text),
                    new MySqlParameter("@receiveid",sReceiveID),
                };
                O = ObjCloud.ExecuteQuery(command1, parameter1);

                //Deducting QTY in Inventory Cost Average (From Branch)
                //string sCmdSFromICA = "Select PQuantity from " + sBranchDB + ".inventorycostaverage A join " + sBranchDB + ".inventory B on A.InventoryID = B.InventoryID where barcode = '" + lBarcode.Text + "'; ";
                //DTFromICA = ObjMainCloud.GetData_DT(sCmdSFromICA);
                string sCmdSFromICA = "Select PQuantity from {0}.inventorycostaverage A join {0}.inventory B on A.InventoryID = B.InventoryID where barcode = @barcode; ";
                string command2 = string.Format(sCmdSFromICA, sBranchDB);
                MySqlParameter[] parameters2 =
                {
                    new MySqlParameter("@barcode",lBarcode.Text)
                };
                DTFromICA = ObjMain.NewGetData_DT(command2, parameters2);

                if (DTFromICA.Rows.Count > 0)
                {
                    double iFromQOH = double.Parse(DTFromICA.Rows[0]["PQuantity"].ToString());
                    double iLatestFromQOH = iFromQOH - double.Parse(AcceptQTY.Text);
                    //string sCmdFromICA = "Update " + sBranchDB + ".inventorycostaverage A inner join " + sBranchDB + ".inventory B on A.InventoryID = B.InventoryID set PQuantity = " + iLatestFromQOH + "  where barcode = '" + lBarcode.Text + "';";
                    //UpdateFromInventoryCostAverageTable = ObjCloud.ExecuteNonQuery(sCmdFromICA);
                    string sCmdFromICA = "Update {0}.inventorycostaverage A inner join {0}.inventory B on A.InventoryID = B.InventoryID set PQuantity = @pquantity  where barcode = @barcode;";
                    string command3 = string.Format(sCmdFromICA, sBranchDB);
                    MySqlParameter[] parameters3 =
                    {
                        new MySqlParameter("@pquantity",iLatestFromQOH),
                        new MySqlParameter("@barcode",lBarcode.Text),
                    };
                    UpdateFromInventoryCostAverageTable = ObjCloud.ExecuteQuery(command3,parameters3);
                }


                //Adding QTY in Inventory Cost Average (To Branch)
                //string sCmdSToICA = "Select PQuantity from " + sBranchAlias + ".inventorycostaverage A join " + sBranchAlias + ".inventory B on A.InventoryID = B.InventoryID where barcode = '" + lBarcode.Text + "'; ";
                //DTToICA = ObjMainCloud.GetData_DT(sCmdSToICA);
                string sCmdSToICA = "Select PQuantity from {0}.inventorycostaverage A join {0}.inventory B on A.InventoryID = B.InventoryID where barcode = @barcode; ";
                string command4 = string.Format(sCmdSToICA, sBranchAlias);
                MySqlParameter[] parameters4 =
                {
                    new MySqlParameter("@barcode",lBarcode.Text)
                };
                DTToICA = ObjMain.NewGetData_DT(command4,parameters4);
                if (DTToICA.Rows.Count > 0)
                {
                    double iToQOH = double.Parse(DTToICA.Rows[0]["PQuantity"].ToString());
                    double iLatestToQOH = iToQOH + double.Parse(AcceptQTY.Text);
                    //string sCmdICA = "Update " + sBranchAlias + ".inventorycostaverage A inner join " + sBranchAlias + ".inventory B on A.InventoryID = B.InventoryID set PQuantity = " + iLatestToQOH + "  where barcode = '" + lBarcode.Text + "';";
                    //UpdateToInventoryCostAverageTable = ObjCloud.ExecuteNonQuery(sCmdICA);
                    string sCmdICA = "Update {0}.inventorycostaverage A inner join {0}.inventory B on A.InventoryID = B.InventoryID set PQuantity = @pquantity  where barcode = @barcode;";
                    string command5 = string.Format(sCmdICA, sBranchAlias);
                    MySqlParameter[] parameters5 =
                    {
                        new MySqlParameter("@pquantity",iLatestToQOH),
                        new MySqlParameter("@barcode",lBarcode.Text),
                    };
                    UpdateToInventoryCostAverageTable = ObjCloud.ExecuteQuery(command5,parameters5);
                }
            }


            //Updating Transfer Sender Transfer Header
            string sTransferID = ObjSel.GetTransferIDbyTransferNo(sBranchDB, txtRefNo.Text);
            //string sCmdj = "Update " + sBranchDB + ".transferstock set confirmNo = '" + sConfirmNo + "',confirmflag = '" + sConfrimFlag + "',confirmDateTime = '" + sConfirmDateTime + "' where transferid = '" + sTransferID + "' ";
            //UpdateTransferHeader = ObjCloud.ExecuteNonQuery(sCmdj);
            string sCmdj = "Update {0}.transferstock set confirmNo = @confirmno,confirmflag = @confrimflag,confirmDateTime = @confirmdatetime where transferid = @transferid";
            string command6 = string.Format(sCmdj, sBranchDB);
            MySqlParameter[] parameters6 =
            {
                new MySqlParameter("@confirmno",sConfirmNo),
                new MySqlParameter("@confrimflag",sConfrimFlag),
                new MySqlParameter("@confirmdatetime",sConfirmDateTime),
                new MySqlParameter("@transferid",sTransferID),
            };
            UpdateTransferHeader = ObjCloud.ExecuteQuery(command6,parameters6);
        }
        protected void btnReceive_Click(object sender, EventArgs e)
        {
            //string BranchAlias = Session["Branch_HQ"].ToString();
          
            string BranchAlias = ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text);
            string sReceiveID = ObjSel.GetReceiveIDbyTransferNo(BranchAlias, txtRefNo.Text);
            ConfirmReceiveStock(BranchAlias, sReceiveID);
            
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Confirmed Items. ');location.href='ReceivingStockTransfer.aspx?TransferNo=" + txtRefNo.Text + "&ToBranch=" + BranchAlias + "'", true);
            txtRefNo.Text = Request.QueryString["TransferNo"].ToString();

            GetTransferStockHeader(BranchAlias, sReceiveID);
            GetFromBranch(BranchAlias, sReceiveID);
            LoadTransferDetails(BranchAlias, sReceiveID);

            foreach (GridViewRow row in grdReceiveDetails.Rows)
            {
                Label lBarcode = row.FindControl("lblBarcode") as Label;
                double dPackUnit = 0.00;
                double dTprice = 0.00;
                TextBox txtReturnQTY = row.FindControl("txtRejectedQTY") as TextBox;
                //double dPackPrice = 0.00;
               

                if (txtReturnQTY.Text != "0")
                {
                    InsertReturnQTY(BranchAlias);
                    break;
                }
                 
            }
            


        }

        protected void GetFromBranch(string BranchAlias, string sReceiveID)
        {
            //string sCmd = "Select Branchname from " + BranchAlias + ".receivestock a join " + BranchAlias + ".branches b on a.frombranchid = b.branchid where receiveid='" + sReceiveID + "';";
            string sCmd = "Select Branchname from {0}.receivestock a join {0}.branches b on a.frombranchid = b.branchid where receiveid=@receiveid;";
            string command = string.Format(sCmd, BranchAlias);
            MySqlParameter[] parameters =
            {
                new MySqlParameter("@receiveid",sReceiveID)
            };
            //DTGetFromBranch = ObjMainCloud.GetData_DT(sCmd);
            DTGetFromBranch = ObjMain.NewGetData_DT(command, parameters);
            if (DTGetFromBranch.Rows.Count > 0)
            {
                txtFBranch.Text = ObjSel.GetBranchFullNameByDB(DTGetFromBranch.Rows[0]["Branchname"].ToString());

            }
        }

        protected void btnReturn_Click(object sender, EventArgs e)
        {
            string BranchAlias = ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text);
            string sReceiveID = ObjSel.GetReceiveIDbyTransferNo(BranchAlias, txtRefNo.Text);
            // ConfirmReceiveStock(BranchAlias, sReceiveID);
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Are you sure you want to go to Return Invoice?. ');location.href='ReturnStockTransfer.aspx?TransferNo=" + txtRefNo.Text + "&ToBranch=" + BranchAlias + "'", true);
            //InsertDetails();
        }
        //Retunr Stock

        protected void InsertReturnQTY(string sToDB)
        {

            string BranchAlias = ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), txtFBranch.Text);
            string sReturnID = ObjSel.GenerateReturnID(BranchAlias.ToString());

            string sFromBranch = ObjSel.GetBranchIDbyName(BranchAlias, txtFBranch.Text.Trim());
            string sToBranch = ObjSel.GetBranchIDbyName(BranchAlias, cmbBranches.Text.Trim());
            //string sReturnNo = txtReturnNo.Text.Trim();
            // GenerateReturnNo(BranchAlias);
            string sPreFix = string.Empty;
            string sHQ = Session["Branch_HQ"].ToString();
            sPreFix = "RT" + ObjSel.GetBranchPrefix(sHQ, ObjSel.GetBranchFullName(sHQ, sToDB));
            string sReturnNo = sPreFix + "-" +ObjSel.GenerateReturnNo(BranchAlias);
            string sReturnDate = Curr_Date;
            string sTransderDB = ObjSel.GetBranchDBNamebyFullName(BranchAlias, txtFBranch.Text.Trim());
            string sTransferID = ObjSel.GetTransferIDbyTransferNo(sTransderDB, txtRefNo.Text.Trim());
            string sTransferNo = txtRefNo.Text.Trim();
            string sConfrimDB = ObjSel.GetBranchDBNamebyFullName(BranchAlias, cmbBranches.Text.Trim());
            string sConfrimID = ObjSel.GetReturnConfirmIDbyRetrunConfirmNo(sConfrimDB, txtConfirm.Text.Trim());
            string sConfirmNo = txtConfirm.Text.Trim();
            double dSubtotal = 0.00;
            double dDiscount = 0.00;
            double dGST = 0.00;
            double dTTotal = 0.00;
            Int32 iAcceptTotal = 0;
            string sEmployeeName = txtUser.Text;
            Int32 iReturnFlag = 1;
            string sSInvoice = "";
            string sTNotes = txtNotes.Text.Trim();

            //string sCmd = "Insert Into " + BranchAlias + ".ReturnStock(ReturnID,FromBranchID,ToBranchID,ReturnNo,ReturnDate,TransferID,TransferNo,ConfirmID,ConfirmNo,Subtotal,Discount,GST,TTotal,AcceptTotal,EmployeeName,ReturnFlag,SInvoiceNo,TNotes)Values" +
            //             "('" + sReturnID + "','" + sFromBranch + "','" + sToBranch + "','" + sReturnNo + "','" + Convert.ToDateTime(sReturnDate) + "','" + sTransferID + "','" + sTransferNo + "','" + sConfrimID + "','" + sConfirmNo + "','" + dSubtotal + "','" + dDiscount + "','" + dGST + "', " +
            //             " '" + dTTotal + "','" + iAcceptTotal + "','" + sEmployeeName + "','" + iReturnFlag + "','" + sSInvoice + "','" + sTNotes + "')";
            //iInsertHeader = ObjCloud.ExecuteNonQuery(sCmd);
            string sCmd = "Insert Into {0}.ReturnStock(ReturnID,FromBranchID,ToBranchID,ReturnNo,ReturnDate,TransferID,TransferNo,ConfirmID,ConfirmNo,Subtotal,Discount,GST,TTotal,AcceptTotal,EmployeeName,ReturnFlag,SInvoiceNo,TNotes)Values" +
                         "(@returnid,@frombranchid,@tobranchid,@returnno,@returndate,@transferid,@TransferNo,@confirmid,@confirmno,@subtotal,@discount,@gst, " +
                         " @total,@accepttotal,@employeename,@returnflag,@invoice,@notes)";
            string command = string.Format(sCmd, BranchAlias);
            MySqlParameter[] parameters =
            {
                new MySqlParameter("@returnid",sReturnID),
                new MySqlParameter("@frombranchid",sFromBranch),
                new MySqlParameter("@tobranchid",sToBranch),
                new MySqlParameter("@returnno",sReturnNo),
                new MySqlParameter("@returndate",sReturnDate),
                new MySqlParameter("@transferid",sTransferID),
                new MySqlParameter("@TransferNo",sTransferNo),
                new MySqlParameter("@confirmid",sConfrimID),
                new MySqlParameter("@confirmno",sConfirmNo),
                new MySqlParameter("@subtotal",dSubtotal),
                new MySqlParameter("@discount",dDiscount),
                new MySqlParameter("@gst",dGST),
                new MySqlParameter("@total",dTTotal),
                new MySqlParameter("@accepttotal",iAcceptTotal),
                new MySqlParameter("@employeename",sEmployeeName),
                new MySqlParameter("@returnflag",iReturnFlag),
                new MySqlParameter("@invoice",sSInvoice),
                new MySqlParameter("@notes",sTNotes),
            };
            iInsertHeader = ObjCloud.ExecuteQuery(command,parameters);
            InsertDetails(BranchAlias, sReturnID);
         
        }

        public void InsertDetails(string BranchAlias, string sReturnID)
        {
            //Int32 iDReturnID = 0;
            Int32 iRetrunID = int.Parse(sReturnID);
            Int32 iTSDetailD = iRetrunID;

            foreach (GridViewRow row in grdReceiveDetails.Rows)
            {
                Label lBarcode = row.FindControl("lblBarcode") as Label;
                double dPackUnit = 0.00;
                double dTprice = 0.00;
                TextBox txtReturnQTY = row.FindControl("txtRejectedQTY") as TextBox;
                //double dPackPrice = 0.00;
                string sReason = "";

                if (txtReturnQTY.Text != "0")
                {
                    //string sCmd = "Insert Into " + BranchAlias + ".ReturnStockDetail(ReturnID,TSDetailID,Barcode,PackUnit,TransferPrice,ReturnQuantity,Reason)values" +
                    //           "(" + iRetrunID + "," + iTSDetailD + ",'" + lBarcode.Text.Trim() + "','" + dPackUnit + "','" + dTprice + "'," + txtReturnQTY.Text.Trim() + ",'" + sReason + "')";
                    //iInsertDetail = ObjCloud.ExecuteNonQuery(sCmd);
                    //string sCmd = "Insert Into {0}.ReturnStockDetail(ReturnID,TSDetailID,Barcode,PackUnit,TransferPrice,ReturnQuantity,Reason)values" +
                    //           "(@returnid,@tsdetailid,@barcode,@packunit,@transferprice,@returnquantity,@reason)";
                    string sCmd = "Insert Into {0}.ReturnStockDetail(ReturnID,TSDetailID,Barcode,PackUnit,TransferPrice,ReturnQuantity,Reason)values" +
                                   "(@returnid,@tsdetailid,@barcode,@packunit,@transferprice,@returnquantity,@reason)";
                    string command = string.Format(sCmd, BranchAlias);
                    MySqlParameter[] parameters =
                    {
                        new MySqlParameter("@returnid",iRetrunID),
                        new MySqlParameter("@tsdetailid",iTSDetailD),
                        new MySqlParameter("@barcode",lBarcode.Text.Trim()),
                        new MySqlParameter("@packunit",dPackUnit),
                        new MySqlParameter("@transferprice",dTprice),
                        new MySqlParameter("@returnquantity",txtReturnQTY.Text.Trim()),
                        new MySqlParameter("@reason",sReason),

                    };
                    iInsertDetail = ObjCloud.ExecuteQuery(command,parameters);
                }

            }

        }

        //public  void GenerateReturnNo(string Branch_AliasName)//Load Reference No.
        //{
        //    string sReturnNo;
        //    int NewReturn;
        //    MySqlConnection Cnn = new MySqlConnection(ConStr_Rds);
        //    Cnn.Open();
        //    string sCmd = "Select ReturnNo from " + Branch_AliasName + ".ReturnStock order by returnid desc limit 1;";
        //    MySqlCommand Cmd = new MySqlCommand(sCmd, Cnn);
        //    sReturnNo = Convert.ToString(Cmd.ExecuteScalar());

        //    if (sReturnNo.Trim() != "")
        //    {

        //        NewReturn = int.Parse(sReturnNo) + 1;
        //        sReturnNo = String.Format("{0:D10}", NewReturn);
        //    }
        //    else
        //    {
        //        sReturnNo = "0000000001";

        //    }
        //}

        [WebMethod]
        public static string GetReceivingHeader(string DB,string TransferID)
        {
            DataTable DTHeader = new DataTable();
            MYSQLDB MySqlObj = new MYSQLDB();

            string JSONResult = string.Empty;
            string sQuery = "Select *from {0}.receivestock where transferid = @transferid";
            string command = string.Format(sQuery, DB);
            MySqlParameter[] parameters =
            {
                new MySqlParameter("@transferid",TransferID)
            };

            DTHeader = MySqlObj.NewGetData_DT(command, parameters);
            JSONResult = JsonConvert.SerializeObject(DTHeader);
            return JSONResult;
        }

        [WebMethod]
        public static string GetReceivingDetail(string DB,string TransferID)
        {
            DataTable DTDetail = new DataTable();
            MYSQLDB MySqlObj = new MYSQLDB();

            string JSONResult = string.Empty;
            string sQuery = " Select A.Barcode,InventoryName,Description,Unit,DeliveryQuantity,AcceptQuantity,RejectQuantity from {0}.receivestockdetail A " +
                            " join {0}.Inventory B on A.barcode = B.barcode " +
                            " join {0}.receivestock C on A.ReceiveID = C.ReceiveID where Transferid = @TransferID";
            string command = string.Format(sQuery, DB);
            MySqlParameter[] parameters =
            {
                new MySqlParameter("@TransferID",TransferID)
            };
            DTDetail = MySqlObj.NewGetData_DT(command, parameters);
            JSONResult = JsonConvert.SerializeObject(DTDetail);
            return JSONResult;
        }

        [WebMethod]
        public static string GetBranchFullName(string DB, string BranchID)
        {
            DataTable DTBranch = new DataTable();
            MYSQLDB MysqlObj = new MYSQLDB();

            string JSONResult = string.Empty;
            string sQuery = "Select * from {0}.branches where branchid = @BranchID";
            string command = string.Format(sQuery, DB);
            MySqlParameter[] parameters =
            {
                new MySqlParameter("@BranchID",BranchID)
            };

            DTBranch = MysqlObj.NewGetData_DT(command, parameters);
            JSONResult = JsonConvert.SerializeObject(DTBranch);
            return JSONResult;
        }

        #region Receive Stock
        [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 PUT_ReceiveStock(string jsondata)
        {
            BL_API objAPI = new BL_API();
            string bearertoken = string.Empty;
            bearertoken = objAPI.GetBarerToken();
            string json = objAPI.PUT_ReceiveStock(bearertoken, jsondata);
            var obj = JsonConvert.DeserializeObject(json);
            return obj.ToString();
        }

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

        #endregion

        #region Receive Stock Detailed Cost
        [WebMethod]
        public static string PUT_ReceiveStockDetailedCost(string jsondata)
        {
            BL_API objAPI = new BL_API();
            string bearertoken = string.Empty;
            bearertoken = objAPI.GetBarerToken();
            string json = objAPI.PUT_ReceiveStockDetailedCost(bearertoken, jsondata);
            var obj = JsonConvert.DeserializeObject(json);
            return obj.ToString();
        }
        #endregion

        #region Inventory Cost Average Detail
        [WebMethod]
        public static string POST_InventoryCostAverageDetail(string db, string jsondata)
        {
            BL_API objAPI = new BL_API();
            string bearertoken = string.Empty;
            bearertoken = objAPI.GetBarerToken();
            string json = objAPI.POST_InventoryCostAverageDetail(bearertoken, db, jsondata);
            var obj = JsonConvert.DeserializeObject(json);
            return obj.ToString();
        }

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


        //GET_InventoryCostAverageDetail

        #endregion

        #region Transfer Stock
        [WebMethod]
        public static string PUT_TransferStock(string jsondata)
        {
            BL_API objAPI = new BL_API();
            string bearertoken = string.Empty;
            bearertoken = objAPI.GetBarerToken();
            string json = objAPI.PUT_TransferStock(bearertoken, jsondata);
            var obj = JsonConvert.DeserializeObject(json);
            return obj.ToString();
        }

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

        #region Return Stock
        [WebMethod]
        public static string POST_ReturnStock(string db, string jsondata)
        {
            BL_API objAPI = new BL_API();
            string bearertoken = string.Empty;
            bearertoken = objAPI.GetBarerToken();
            string json = objAPI.POST_ReturnStock(bearertoken, db, jsondata);
            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();
        }
        #endregion
    }
}