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;
using System.Web.Script.Serialization;
using SunWeb.Model;


namespace SUNWEB
{
    public partial class AddTransferStock : 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 Q = 0;
        Int32 R = 0;

        Int32 KReceiving = 0;
        Int32 LReceiving = 0;
        Int32 TransferVoid = 0;
        Int32 UpdateTransferHeader = 0;

        Int32 CheckTransferNo = 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 dtItemTransfer = new DataTable();
        DataTable dtFItemTransfer = new DataTable();
        string sSno = string.Empty;
        int iSno = 0;


        //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 sInventoryID;
        string sInventoryname;
        string sBarcode;
        Int32 RowIndex;

        Int32 gPageIndex;
        string Notes = string.Empty;

        string gTransferNo = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {

            }
            else
            {
                Notes = txtNotes.Text;
            }

            if (Session["UserName"] == null)
            {
                Response.Redirect("Login.aspx", false);
            }

            if (Session["UserName"] == null)
            {
                Response.Redirect("Login.aspx", false);
            }


            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.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 


            }


            if (cmbBranches.Visible == false)
            {
                txtFBranch.Text = Session["Branch_HQ"].ToString();
                //txtTransDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
                txtTransDate.Text = Curr_DateOnly;
            }
            else
            {
                txtFBranch.Text = cmbBranches.Text;
                //txtTransDate.Text = DateTime.Now.ToString("yyyy-MM-dd");
                txtTransDate.Text = Curr_DateOnly;
            }

            if (!IsPostBack)
            {
                if (cmbBranches.Visible == true)
                {
                    txtRefNo.CssClass = "form-control";
                    txtTransDate.CssClass = "form-control";
                    txtConfirm.CssClass = "form-control";
                    txtFBranch.CssClass = "form-control";
                    txtSendDate.CssClass = "form-control";
                    txtConfirm.CssClass = "form-control";
                    txtConfirmStatus.CssClass = "form-control";
                    cmbBranches.CssClass = "custom-select";
                    txtSendStatus.CssClass = "form-control";
                    lblBranchTitle.Visible = false;

                    if (Request.QueryString["TransferNo"] == null)
                    {
                        //gTransferNo = Request.QueryString["TransferNo"].ToString();
                        cmbBranches.CssClass = "custom-select";
                        cmbBranches.Text = Request.QueryString["Branchname"].ToString();
                        txtFBranch.Text = cmbBranches.Text;
                        LoadItems(Request.QueryString["Branchname"].ToString());

                        Session["DB"] = ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text);
                        Session["TransferID"] = "0";

                        LoadData();


                    }
                    else
                    {
                        gTransferNo = Request.QueryString["TransferNo"].ToString();
                        cmbBranches.Text = Request.QueryString["Branchname"].ToString();
                        txtFBranch.Text = cmbBranches.Text;
                        LoadItems(Request.QueryString["Branchname"].ToString());

                        Session["DB"] = ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text);
                        Session["TransferID"] = ObjSel.GetTransferIDbyTransferNo(Session["DB"].ToString(), gTransferNo);
                    }

                }
                else
                {
                    gTransferNo = Request.QueryString["TransferNo"].ToString();
                    LoadToBranch(Session["Branch_HQ"].ToString());
                    LoadRefNo(Session["Branch_HQ"].ToString());
                    LoadItems(Session["Branch_HQ"].ToString());
                    LoadTransferDetails(Session["Branch_HQ"].ToString(), "");
                    Session["DB"] = ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text);
                    Session["TransferID"] = ObjSel.GetTransferIDbyTransferNo(Session["DB"].ToString(), gTransferNo);
                }

            }
            else
            {

            }

            if (Request.QueryString["TransferNo"] != null)
            {

                txtRefNo.CssClass = "form-control";
                txtRefNo.Text = Request.QueryString["TransferNo"].ToString();
                string sTransferID = ObjSel.GetTransferIDbyTransferNo(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text), txtRefNo.Text.Trim());
                LoadToBranch(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text));
                txtFBranch.Text = cmbBranches.Text;

                cmbTBranch.SelectedItem.Text = ObjSel.GetBranchFullNameByDB(ObjSel.GetToBranch(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text), sTransferID));

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

            txtUser.Text = ObjSel.GetUserNamebyUserID(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text), int.Parse(Session["UserId"].ToString()));
            Session["username"] = txtUser.Text.Trim();
            if (!IsPostBack)
            {
                txtRefNo.CssClass = "form-control";
                txtTransDate.CssClass = "form-control";
                txtConfirm.CssClass = "form-control";
                txtFBranch.CssClass = "form-control";
                txtSendDate.CssClass = "form-control";
                txtConfirm.CssClass = "form-control";
                txtConfirmStatus.CssClass = "form-control";
                cmbBranches.CssClass = "custom-select";
                txtSendStatus.CssClass = "form-control";
                txtNotes.CssClass = "form-control";
                lblBranchTitle.CssClass = "form-control";


                if (Request.QueryString["TransferNo"] != null)
                {
                    cmbBranches.CssClass = "custom-select";
                    string sTransferIID = ObjSel.GetTransferIDbyTransferNo(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text), txtRefNo.Text.Trim());
                    //gPageIndex = Convert.ToInt32(Session["gridIndex"]);
                    //grdDisplayItems.PageIndex = gPageIndex;
                    LoadTransferDetails(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text), sTransferIID);
                }
            }

            if (txtSendStatus.Text == "Not Send" || txtSendStatus.Text == "")
            {
                btnSend.Enabled = true;
                btnSave.Enabled = true;
                btnVoid.Enabled = true;
                cmbTBranch.Enabled = true;
                foreach (GridViewRow gvr in grdTransferDetails.Rows)
                {
                    TextBox txtinput = ((TextBox)gvr.FindControl("txtinputqty"));
                    txtinput.Enabled = true;
                }
            }
            else
            {
                btnSend.Enabled = false;
                btnSave.Enabled = false;
                btnVoid.Enabled = false;
                btnAddToTransferList.Enabled = false;
                //cmbTBranch.Enabled = false;
                //cmbBranches.CssClass = "custom-select";

                foreach (GridViewRow gvr in grdTransferDetails.Rows)
                {
                    TextBox txtinput = ((TextBox)gvr.FindControl("txtinputqty"));
                    txtinput.Enabled = false;

                    Button btnDelete = ((Button)gvr.FindControl("btnDelete"));
                    btnDelete.Enabled = false;
                    btnDelete.CssClass = "form-control";

                    Button btnDn = ((Button)gvr.FindControl("btnDn"));
                    btnDn.Enabled = false;
                    btnDn.CssClass = "form-control";

                    TextBox txtAdj = ((TextBox)gvr.FindControl("txtAdjQTY"));
                    txtAdj.Enabled = false;
                }
                //DropDownList cmbTBranch = ((DropDownList)gvr.FindControl("cmbTBranch"));
                cmbBranches.CssClass = "custom-select";
                lblBranchTitle.Visible = true;
                lblBranchTitle.Text = cmbTBranch.SelectedItem.Text;
                cmbTBranch.Visible = false;
            }

        }

        public void LoadBranchName4SuperAdmin()
        {
            DtSuperAdmin = ObjUserBL.GetBranchOnSuperAdminWithHQ(Session["Branch_HQ"].ToString(), Session["UserId"].ToString());
            if (DtSuperAdmin.Rows.Count > 0)
            {

            }
        }

        public void LoadBranchName()
        {
            DtNormalUser = ObjUserBL.GetBranchOnLoginValues(Session["Branch_HQ"].ToString(), Session["UserId"].ToString());
            if (DtNormalUser.Rows.Count > 0)
            {

            }
        }

        protected void cmbBranches_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (cmbBranches.Visible == false)
            {
                LoadToBranch(Session["Branch_HQ"].ToString());
                LoadRefNo(Session["Branch_HQ"].ToString());
                LoadItems(Session["Branch_HQ"].ToString());
                LoadTransferDetails(Session["Branch_HQ"].ToString(), "");
            }
            else
            {
                LoadToBranch(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text));
                LoadRefNo(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text));
                LoadItems(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text));
                LoadTransferDetails(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text), "");

            }

        }

        protected void LoadData()
        {
            if (cmbBranches.Visible == false)
            {
                LoadToBranch(Session["Branch_HQ"].ToString());
                LoadRefNo(Session["Branch_HQ"].ToString());
                LoadItems(Session["Branch_HQ"].ToString());
                LoadTransferDetails(Session["Branch_HQ"].ToString(), "");
            }
            else
            {

                LoadToBranch(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text));
                LoadRefNo(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text));
                LoadItems(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text));
                LoadTransferDetails(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text), "");
            }
        }

        public void LoadToBranch(string Branch_AliasName) //Load to Branch ComboBox
        {
            string sCmd = "Select BranchID,BranchName,BranchFullname From " + Branch_AliasName + ".branches where BranchName <> '" + Branch_AliasName + "';";
            DT = ObjMainCloud.GetData_DT(sCmd);
            cmbTBranch.DataSource = DT;
            cmbTBranch.DataTextField = "BranchFullname";
            cmbTBranch.DataValueField = "BranchID";
            cmbTBranch.DataBind();
            cmbTBranch.Items.Insert(0, "Select");

            //var json = JsonConvert.SerializeObject(DT.AsEnumerable().Select(r => r.ItemArray));
            //ScriptManager.RegisterStartupScript(this, this.GetType(), "Script", " dp_branch(" + json + "); ", true);
            //var json = JsonConvert.SerializeObject(DT.AsEnumerable().Select(r => r.ItemArray));
            //ScriptManager.RegisterStartupScript(this, this.GetType(), "Script", " loadbranches(" + json + "); ", true);
        }

        public void LoadTransferDetails(string Branch_AliasName, string sTransferID)
        {
            string sCmd = "Select TSDetailID,B.InventoryID,B.Barcode,B.InventoryName,B.Description,PackUnit,PackQuantity,round(PackPrice,2) as PackPrice  " +
                   " from {0}.transferstockdetail A Join " +
                   " {0}.Inventory B on A.InventoryID=B.InventoryID " +
                   " where TransferID =@TransferID;";

            string command = string.Format(sCmd, Branch_AliasName);

            MySqlParameter[] parameters =
                   {
                     new MySqlParameter("@TransferID",sTransferID),
                   };


            DT = ObjMain.NewGetData_DT(command, parameters);
            grdTransferDetails.DataSource = DT;
            grdTransferDetails.DataBind();
        }

        public void LoadRefNo(string Branch_AliasName)//Load Reference No.
        {
            string RefNo;
            int NewRefNo;
            MySqlConnection Cnn = new MySqlConnection(ConStr_Rds);
            Cnn.Open();
            string sCmd = "Select TransferNo from " + Branch_AliasName + ".transferstock order by transferno desc limit 1;";
            MySqlCommand Cmd = new MySqlCommand(sCmd, Cnn);
            RefNo = Convert.ToString(Cmd.ExecuteScalar());
            if (RefNo.Trim() != "")
            {
                string[] words = RefNo.Split('-');
                NewRefNo = int.Parse(words[1]) + 1;
                txtRefNo.Text = ObjSel.GetBranchPrefix(Branch_AliasName, cmbBranches.Text).ToString() + "-" + String.Format("{0:D7}", NewRefNo);

            }
            else
            {
                txtRefNo.Text = ObjSel.GetBranchPrefix(Branch_AliasName, cmbBranches.Text).ToString() + "-" + "0000001";

            }
            //ScriptManager.RegisterStartupScript(this, this.GetType(), "Script", " generateTransferNo(" + txtRefNo.Text + ");", true);
        }

        public void LoadItems(string Branch_AliasName)
        {
            string DBName;
            DBName = ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text);
            //if (txtInventoryid.Text != "")
            //{
            //    sInventoryID = " and Inventoryid =@Inventoryid ";
            //}

            //if (txtInventoryNameSearch.Text != "")
            //{
            //    sInventoryname = "and like CONCAT('%',@InventorySearchTxt,'%') ";
            //}

            //if (txtBarcodesearch.Text != "")
            //{

            //}
            string sCondition = string.Empty;

            if (cmbSearchOption.SelectedValue == "1") //Barcode
            {
                sCondition = "and Barcode like CONCAT('%',@InputValue,'%') ";
            }
            else if (cmbSearchOption.SelectedValue == "2") //Name
            {
                sCondition = "and InventoryName like CONCAT('%',@InputValue,'%') ";
            }
            else if (cmbSearchOption.SelectedValue == "3") //Description
            {
                sCondition = "and Description like CONCAT('%',@InputValue,'%') ";
            }

            if (Convert.ToInt32(Session["gridIndex"]) == 0)
            {
                string sCmd = "Select InventoryID,Barcode,InventoryName,Description from {0}.inventory where active<>0 and barcode <> 'round' " + sCondition + ";";
                string command = string.Format(sCmd, DBName);

                MySqlParameter[] parameters =
                {
                     new MySqlParameter("@InputValue",txtSearchInput.Text),

                };

                DTInventory = ObjMain.NewGetData_DT(command, parameters);
                grdDisplayItems.DataSource = DTInventory;
                grdDisplayItems.DataBind();
            }
            else
            {
                string sCmd = "Select InventoryID,Barcode,InventoryName,Description from {0}.inventory where active<>0 and barcode <> 'round' " + sInventoryID + " " + sInventoryname + "  " + sBarcode + ";";
                string command = string.Format(sCmd, DBName);
                MySqlParameter[] parameters =
                 {
                     new MySqlParameter("@Inventoryid",txtInventoryid.Text),
                     new MySqlParameter("@InventorySearchTxt",txtInventoryNameSearch.Text.Trim()),
                     new MySqlParameter("@BarcodeSearchTxt",txtBarcodesearch.Text.Trim()),
                    };
                DTInventory = ObjMain.NewGetData_DT(command, parameters);
                grdDisplayItems.PageIndex = int.Parse(Session["gridIndex"].ToString());
                grdDisplayItems.DataSource = DTInventory;
                grdDisplayItems.DataBind();

            }


        }

        protected void txtInventoryid_TextChanged(object sendaer, EventArgs e)
        {
            //LoadItems(cmbBranches.Text);
        }

        protected void cmbTBranch_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        protected void btnSearch_Click(object sender, EventArgs e)
        {
            LoadItems(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text));
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ShowModalItems();", true);
        }

        protected void btnAddItem_Click(object sender, EventArgs e)
        {
            ItemsAddtoTempTable();



            if (cmbBranches.Visible == true)
            {

                InsertTransferHeader(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text));


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

            }

            txtRefNo.Text = ObjSel.GetLastTransferNo(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text));
            Session.Remove("TmpItemTransfer");
            dtItemTransfer.Clear();
            dtFItemTransfer.Clear();
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Items Added ');location.href='AddTransferStock.aspx?Branchname=" + cmbBranches.Text + "&TransferNo=" + txtRefNo.Text + "'", true);

        }

        //protected void grdDisplayItems_PageIndexChanging(object sender, GridViewPageEventArgs e)
        //{
        //    grdDisplayItems.PageIndex = e.NewPageIndex;
        //    Int32 gridIndex = grdDisplayItems.PageIndex;
        //    Session["gridIndex"] = gridIndex;
        //    if (cmbBranches.Visible == true)
        //    {
        //        LoadItems(cmbBranches.Text);
        //    }
        //    else
        //    {
        //        LoadItems(Session["Branch_HQ"].ToString());
        //    }
        //}

        protected void btnInventorySearch_Click(object sender, EventArgs e)
        {
            // LoadItems(cmbBranches.Text);
        }

        private void InsertTransferHeader(string BranchAlias)
        {
            string sFromBranch;
            string sTransferID = ObjSel.GenerateTransferID(BranchAlias);

            sFromBranch = ObjSel.GetBranchIDbyName(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text), txtFBranch.Text.Trim());
            string sToBranch = ObjSel.GetBranchIDbyName(BranchAlias, cmbTBranch.SelectedItem.Text.Trim());
            string sTransferNo = txtRefNo.Text.Trim();
            string sTransferDate = txtTransDate.Text.Trim();
            string sSendDateTime = "";
            string sConfirmNo = "";
            string sConfirmDateTime = "";
            string sAdjustDateTime = "";
            string sInvoiceNo = "";
            string sSubtotal = "0.00";
            string sDiscount = "0";
            string sGst = "0";
            string sTTotal = "0.00";
            string sTNotes = txtNotes.Text;
            string sEmployeename = txtUser.Text.Trim();
            string sSendFlag = "0";
            string sConfirmFlag = "0";
            string sOriginalBranchID = sFromBranch;
            string sOriginalTransferNo = sTransferNo;

            if (ObjSel.CheckedTransferNoifExist(BranchAlias, sTransferNo) == "")
            {
                string sCmd = "Insert Into {0}.transferstock(TransferID,FromBranchID,ToBranchID,TransferNo,TransferDate,SendDateTime,ConfirmNo," +
                                                          " ConfirmDateTime,AdjustDateTime,SInvoiceNo,SubTotal,Discount,GST, " +
                                                          " TTotal,TNotes,Employeename,SendFlag,ConfirmFlag,OriginalBranchID,OriginalTransferNo)" +
                                                          " values" +
                                                          " (@TransferID,@FromBranchID,@ToBranchID,@TransferNo,@TransferDate,@SendDateTime,@ConfirmNo," +
                                                          " @ConfirmDateTime,@AdjustDateTime,@SInvoiceNo,@SubTotal,@Discount,@GST, " +
                                                          " @TTotal,@TNotes,@Employeename,@SendFlag,@ConfirmFlag,@OriginalBranchID,@OriginalTransferNo ) ";

                string command = string.Format(sCmd, BranchAlias);

                MySqlParameter[] parameters =
                   {
                     new MySqlParameter("@TransferID",sTransferID),
                     new MySqlParameter("@FromBranchID",sFromBranch),
                     new MySqlParameter("@ToBranchID",sToBranch),
                     new MySqlParameter("@TransferNo",sTransferNo),
                     new MySqlParameter("@TransferDate",sTransferDate),
                     new MySqlParameter("@SendDateTime",sSendDateTime),
                     new MySqlParameter("@ConfirmNo",sConfirmNo),
                     new MySqlParameter("@ConfirmDateTime",sConfirmDateTime),
                     new MySqlParameter("@AdjustDateTime",sAdjustDateTime),
                     new MySqlParameter("@SInvoiceNo",sInvoiceNo),
                     new MySqlParameter("@SubTotal",sSubtotal),
                     new MySqlParameter("@Discount",sDiscount),
                     new MySqlParameter("@GST",sGst),
                     new MySqlParameter("@TTotal",sTTotal),
                     new MySqlParameter("@TNotes",sTNotes),
                     new MySqlParameter("@Employeename",sEmployeename),
                     new MySqlParameter("@SendFlag",sSendFlag),
                     new MySqlParameter("@ConfirmFlag",sConfirmFlag),
                     new MySqlParameter("@OriginalBranchID",sOriginalBranchID),
                     new MySqlParameter("@OriginalTransferNo",sOriginalTransferNo),

                    };

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

            InsertTranferDetails(BranchAlias);
            DeleteTmpTransferDetail(BranchAlias);
        }

        private void InsertTranferDetails(string BranchAlias)
        {
            string sCmd = " Insert into {0}.transferstockdetail(TransferID,InventoryID,Barcode,PackUnit,PackCapacity,PackQuantity,PackPrice,LooseQuantity,FreeofCharge,ItemTotal,RejectQuantity,Reason,SellingPrice)" +
                          " Select *from {0}.tmptransferstockdetail;";

            string command = string.Format(sCmd, BranchAlias);
            L = ObjCloud.ExecuteNonQuery(command);

        }

        private void DeleteTmpTransferDetail(string BranchAlias)
        {
            string sCmd = "Delete From {0}.tmptransferstockdetail ";
            string command = string.Format(sCmd, BranchAlias);
            K = ObjCloud.ExecuteNonQuery(command);
        }

        protected void CheckBoxProcess_OnCheckedChanged(object sender, EventArgs e)
        {
            foreach (GridViewRow row in grdDisplayItems.Rows)
            {
                Label InvID = row.FindControl("lblInventoryID") as Label;
                Label Barcode = row.FindControl("lbldisplayBarcode") as Label;
                string sBarcode;
                //string sBranchSelected = Session["Branch_HQ"].ToString()
                string sBranchSelected = ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text);

                if ((row.FindControl("chkSelect") as CheckBox).Checked)
                {

                    string iTransferID = ObjSel.GenerateTransferID(sBranchSelected);
                    string sPackUnit = "PCS";
                    int iPackCapacity = 1;
                    int iPackQuantity = 0;
                    double dPackPrice = 0.00;
                    double dLooseQuantity = 0.00;
                    int iFOC = 0;
                    double dItemTotal = 0.00;
                    int iRejectedQTY = 0;
                    string sReason = "";
                    double dSellingPrice = 0.00;
                    sBarcode = Barcode.Text;
                    if (ObjSel.CheckItem(sBranchSelected, sBarcode) == "False")
                    {
                        string sCmd = "Insert into  {0}.tmptransferstockdetail(TransferID,InventoryID,Barcode,PackUnit,PackCapacity,PackQuantity,PackPrice,LooseQuantity, " +
                                                " FreeofCharge,ItemTotal,RejectQuantity,Reason,SellingPrice)" +
                                                " values " +
                                                " ( @TransferID,@InventoryID,@Barcode,@PackUnit,@PackCapacity,@PackQuantity,@PackPrice,@LooseQuantity, " +
                                                "  @FreeofCharge,@ItemTotal,@RejectQuantity,@Reason,@SellingPrice)";

                        string command = string.Format(sCmd, sBranchSelected);

                        MySqlParameter[] parameters =
                        {
                         new MySqlParameter("@TransferID",iTransferID),
                         new MySqlParameter("@InventoryID",InvID.Text),
                         new MySqlParameter("@Barcode",Barcode.Text),
                         new MySqlParameter("@PackUnit",sPackUnit),
                         new MySqlParameter("@PackCapacity",iPackCapacity),
                         new MySqlParameter("@PackQuantity",iPackQuantity),
                         new MySqlParameter("@PackPrice",dPackPrice),
                         new MySqlParameter("@LooseQuantity",dLooseQuantity),
                         new MySqlParameter("@FreeofCharge",iFOC),
                         new MySqlParameter("@ItemTotal",dItemTotal),
                         new MySqlParameter("@RejectQuantity",iRejectedQTY),
                         new MySqlParameter("@Reason",sReason),
                         new MySqlParameter("@SellingPrice",dSellingPrice),

                        };

                        K = ObjMain.ExecuteQuery(command, parameters);

                    }

                }
                else
                {
                    string sCmdi = "Delete from  {0}.tmptransferstockdetail where barcode=@barcode ";
                    string command = string.Format(sCmdi, sBranchSelected);
                    MySqlParameter[] parameters =
                        {
                         new MySqlParameter("@barcode",Barcode.Text),
                        };
                    P = ObjCloud.ExecuteQuery(command, parameters);
                }
            }

        }

        protected void txtRefNo_TextChanged(object sender, EventArgs e)
        {
            string sTransferID = ObjSel.GetTransferIDbyTransferNo(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text), txtRefNo.Text.Trim());
            GetTransferStockHeader(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text), sTransferID);
            LoadTransferDetails(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text), sTransferID);
        }

        protected void btnVoid_Click(object sender, EventArgs e)
        {
            if (txtConfirm.Text == "")
            {
                string sTransferID = ObjSel.GetTransferIDbyTransferNo(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text), txtRefNo.Text.Trim());
                string BranchAlias = ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text);

                string sCmd = "Update {0}.transferstock set sendflag = 3 where transferid = @transferid and confirmflag = 0;";
                string command = string.Format(sCmd, BranchAlias);
                MySqlParameter[] parameters =
                {
                    new MySqlParameter("@transferid",sTransferID),
                };
                TransferVoid = ObjCloud.ExecuteQuery(command, parameters);
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Transfer Void Successfully');location.reload(true); ", true);
            }
            else
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('Cannot Void Transfer, Transfer Already Received'); ", true);
            }
        }

        protected void btnSend_Click(object sender, EventArgs e)
        {
            string sTransferID = ObjSel.GetTransferIDbyTransferNo(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text), txtRefNo.Text.Trim());
            string sDB = ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text);
            if (CheckIfTransferAlreadySave(sDB, int.Parse(sTransferID)) == "true")
            {
                UpdateSendFlag(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text), sTransferID);
                Receivestock(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text), sTransferID);
                Session["gridIndex"] = 0;
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Transfer Stock Send Successfully.');location.reload(true); ", true);

            }
            else
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Please Save First Before Sending'); ", true);
            }
            //Response.Redirect(Request.RawUrl);
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {

            string sTransferID = ObjSel.GetTransferIDbyTransferNo(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text), txtRefNo.Text.Trim());
            string BranchAlias = ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text);
            //string Notes = Request.Form["txtNotes"].ToString();
            string sCmdTransferHeader = "Update " + BranchAlias + ".transferstock set TNotes = '" + Notes + "' where transferid = '" + sTransferID + "'";
            UpdateTransferHeader = ObjCloud.ExecuteNonQuery(sCmdTransferHeader);

            for (int i = 0; i <= grdTransferDetails.Rows.Count - 1; i++)
            {
                TextBox adjustyQTY = (TextBox)grdTransferDetails.Rows[i].Cells[5].FindControl("txtinputqty");
                Label TSDetailID = (Label)grdTransferDetails.Rows[i].Cells[0].FindControl("lblTSDetailID");
                Label lBarcode = (Label)grdTransferDetails.Rows[i].Cells[0].FindControl("lblBarcode");
                string sCmd = "Update " + BranchAlias + ".transferstockdetail set PackQuantity = '" + adjustyQTY.Text + "' where transferid = '" + sTransferID + "' and barcode = '" + lBarcode.Text + "' and TSDetailID = '" + TSDetailID.Text + "'";
                N = ObjCloud.ExecuteNonQuery(sCmd);

            }

            Session["gridIndex"] = 0;
            ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert('Transfer Items Save'); ", true);
        }

        private void UpdateHeader(string sDB, int iTransfer)
        {

        }

        private string CheckIfTransferAlreadySave(string sDB, int iTransferID)
        {
            DataTable DTDetail = new DataTable();
            string sCheckIfTransferAlreadySave = string.Empty;
            sCheckIfTransferAlreadySave = "true";
            string sCmd = "Select * from {0}.transferstockdetail where transferid=@transferid ";
            string command = string.Format(sCmd, sDB);

            MySqlParameter[] parameters =
                   {
                     new MySqlParameter("@transferid",iTransferID),
                   };

            DTDetail = ObjMain.NewGetData_DT(command, parameters);
            if (DTDetail.Rows.Count > 0)
            {
                for (int x = 0; x <= grdTransferDetails.Rows.Count - 1; x++)
                {

                    if (DTDetail.Rows[x]["PackQuantity"].ToString() == "0")
                    {
                        sCheckIfTransferAlreadySave = "false";
                        return sCheckIfTransferAlreadySave;
                    }
                }
            }

            return sCheckIfTransferAlreadySave;
        }

        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,date_format(adjustdatetime,'%Y-%m-%d') as adjustdatetime, " +
                            " case " +
                            " when SendFlag = 0 then 'Not Send' " +
                            " when SendFlag = 1 then 'Send' " +
                            " when SendFlag = 3 then 'Void' " +
                            " else '' " +
                            " end as Sendflag,if(confirmflag=0,'PENDING','CONFIRMED')as ConfirmFlag,TNotes from {0}.transferstock where transferid ={1}  ";

            string command = string.Format(sCmd, sBranchAlias, sTransferID);

            DTTransferStock = ObjMainCloud.GetData_DT(command);
            if (DTTransferStock.Rows.Count > 0)
            {
                txtConfirm.Text = DTTransferStock.Rows[0]["ConfirmNo"].ToString();
                txtTransDate.Text = DTTransferStock.Rows[0]["TransferDate"].ToString();
                txtSendDate.Text = DTTransferStock.Rows[0]["senddatetime"].ToString();
                txtSendStatus.Text = DTTransferStock.Rows[0]["SendFlag"].ToString();
                txtConfirmStatus.Text = DTTransferStock.Rows[0]["ConfirmFlag"].ToString();
                txtNotes.Text = DTTransferStock.Rows[0]["TNotes"].ToString();
            }

        }

        public void UpdateSendFlag(string sBranchAlias, string sTransferID)
        {
            string sSendDateTime = Curr_Date;
            //DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss")
            string sCmd = "Update {0}.transferstock set SendFlag =@SendFlag , SendDatetime=@SendDatetime where transferid=@transferid ";
            string command = string.Format(sCmd, sBranchAlias);

            MySqlParameter[] parameters =
                   {
                     new MySqlParameter("@SendFlag","1"),
                     new MySqlParameter("@SendDatetime",Convert.ToDateTime(sSendDateTime)),
                     new MySqlParameter("@transferid",sTransferID),

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

        public void Receivestock(string sBranchAlias, string sTransferID)
        {

            //Inserting in ReceivingStock Headers
            string BranchDB = ObjSel.GetBranchDBNamebyFullName(sBranchAlias, cmbTBranch.SelectedItem.Text);
            string sCmd = "Insert Into {0}.receivestock(ReceiveID,FromBranchID,ToBranchID,TransferNo,TransferID,TransferDate,SendDateTime,ConfirmNo,ConfirmDateTime,ReplyFlag,ErrorOccur,SubTotal,Discount,GST, " +
                    " TTotal,Accepttotal,Employeename,ConfirmFlag,SInvoiceNo) " +
                    " Select TransferID,FromBranchID,ToBranchID,TransferNo,TransferID,TransferDate,SendDateTime,ConfirmNo,ConfirmDateTime,'0','1',SubTotal,Discount,GST,TTotal,0,Employeename,ConfirmFlag,SInvoiceNo from {1}.transferstock where transferid ={2} ;";


            string command = string.Format(sCmd, BranchDB, sBranchAlias, sTransferID);

            KReceiving = ObjCloud.ExecuteNonQuery(command);



            //Insert ReceiveStock Details
            string sCmdi = "Insert into {0}.receivestockdetail(ReceiveID,TSDetailID,Barcode,PackUnit,SendQuantity,ItemTotal,DeliveryQuantity,AcceptQuantity,RejectQuantity,Reason)" +
             "Select TransferID,TSDetailID,Barcode,PackUnit,PackQuantity,ItemTotal,PackQuantity,0,0,'' from {1}.transferstockdetail where transferid = {2} ;";
            string commandA = string.Format(sCmdi, BranchDB, sBranchAlias, sTransferID);

            LReceiving = ObjCloud.ExecuteNonQuery(commandA);


        }

        protected void btnAddToTransferList_Click(object sender, EventArgs e)
        {
            if (cmbTBranch.SelectedValue != "Select")
            {
                ItemsAddtoTempTable();
                if (cmbBranches.Visible == true)
                {
                    InsertTransferHeader(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text));
                }
                else
                {
                    InsertTransferHeader(Session["Branch_HQ"].ToString());
                }

                txtRefNo.Text = ObjSel.GetLastTransferNo(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text));
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Items Added ');location.href='AddTransferStock.aspx?Branchname=" + cmbBranches.Text + "&TransferNo=" + txtRefNo.Text + "'", true);
            }
            else
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Please Select Branch First.'); ", true);

            }

        }

        private void ItemsAddtoTempTable()
        {
            foreach (GridViewRow row in grdDisplayItems.Rows)
            {
                Label InvID = row.FindControl("lblInventoryID") as Label;
                Label Barcode = row.FindControl("lbldisplayBarcode") as Label;
                string sBarcode;
                string sBranchSelected = ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text);

                if ((row.FindControl("chkSelected") as CheckBox).Checked)
                {

                    string iTransferID = ObjSel.GenerateTransferID(sBranchSelected);
                    if (ObjSel.CheckedTransferNoifExist(sBranchSelected, txtRefNo.Text) == "")
                    {
                        iTransferID = ObjSel.GenerateTransferID(sBranchSelected);
                    }
                    else
                    {
                        iTransferID = ObjSel.CheckedTransferNoifExist(sBranchSelected, txtRefNo.Text);
                    }
                    string sPackUnit = "PCS";
                    int iPackCapacity = 1;
                    int iPackQuantity = 0;
                    double dPackPrice = 0.00;
                    double dLooseQuantity = 0.00;
                    int iFOC = 0;
                    double dItemTotal = 0.00;
                    int iRejectedQTY = 0;
                    string sReason = "";
                    double dSellingPrice = 0.00;
                    sBarcode = Barcode.Text;

                    if (ObjSel.CheckItem(sBranchSelected, sBarcode) == "False")
                    {
                        string sCmd = "Insert into  {0}.tmptransferstockdetail(TransferID,InventoryID,Barcode,PackUnit,PackCapacity,PackQuantity,PackPrice," +
                            "  LooseQuantity,FreeofCharge,ItemTotal,RejectQuantity,Reason,SellingPrice )" +
                            "  values " +
                            "  (@TransferID,@InventoryID,@Barcode,@PackUnit,@PackCapacity,@PackQuantity,@PackPrice,@LooseQuantity, " +
                            "  @FreeofCharge,@ItemTotal,@RejectQuantity,@Reason,@SellingPrice )";

                        string command = string.Format(sCmd, sBranchSelected);
                        MySqlParameter[] parameters =
                        {
                         new MySqlParameter("@TransferID",iTransferID),
                         new MySqlParameter("@InventoryID",InvID.Text),
                         new MySqlParameter("@Barcode",Barcode.Text),
                         new MySqlParameter("@PackUnit",sPackUnit),
                         new MySqlParameter("@PackCapacity",iPackCapacity),
                         new MySqlParameter("@PackQuantity",iPackQuantity),
                         new MySqlParameter("@PackPrice",dPackPrice),
                         new MySqlParameter("@LooseQuantity",dLooseQuantity),
                         new MySqlParameter("@FreeofCharge",iFOC),
                         new MySqlParameter("@ItemTotal",dItemTotal),
                         new MySqlParameter("@RejectQuantity",iRejectedQTY),
                         new MySqlParameter("@Reason",sReason),
                         new MySqlParameter("@SellingPrice",dSellingPrice),
                        };

                        K = ObjCloud.ExecuteQuery(command, parameters);

                    }

                }
                else
                {
                    string sCmdi = "Delete from  {0}.tmptransferstockdetail where barcode=@barcode ";
                    string command = string.Format(sCmdi, sBranchSelected);

                    MySqlParameter[] parameters =
                       {
                         new MySqlParameter("@barcode",Barcode.Text),
                       };
                    P = ObjCloud.ExecuteQuery(command, parameters);
                }
            }
        }

        protected void btnUpdate_Click(object sender, EventArgs e)
        {

        }

        protected void grdTranferDetails_RowEditing(object sender, System.Web.UI.WebControls.GridViewEditEventArgs e)
        {
            string sTransferIID = ObjSel.GetTransferIDbyTransferNo(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text), txtRefNo.Text.Trim());
            //grdTransferView.EditIndex = e.NewEditIndex;

            grdTransferDetails.EditIndex = e.NewEditIndex;
            LoadTransferDetails(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text), sTransferIID);


            //grdTransferDetails.EditIndex = e.NewEditIndex;
            //string barcode = grdTransferDetails.Rows[e.NewEditIndex].Cells[0].Text; 
            //int qty = Int32.Parse(grdTransferDetails.Rows[e.NewEditIndex].Cells[5].Text);


            //string sTransferIID = ObjSel.GetTransferIDbyTransferNo(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text), txtRefNo.Text.Trim());
            //string DBName = ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text);

            //string sCmd = "Update " + DBName + ".transferstockdetail set PackQuantity = '" + qty + "' where transferid = '" + sTransferIID + "' and barcode = '" + barcode + "'";
            //Q = ObjCloud.ExecuteNonQuery(sCmd);

            //grdTransferDetails.EditIndex = -1;
            //LoadTransferDetails(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text), sTransferIID);  
        }

        protected void grdTranferDetails_RowUpdating(object sender, GridViewUpdateEventArgs e)
        {
            //Label barcode = grdTransferDetails.Rows[e.RowIndex].FindControl("lblBarcode") as Label;
            //TextBox qty = grdTransferDetails.Rows[e.RowIndex].FindControl("txtinputqty") as TextBox;


            //string sTransferIID = ObjSel.GetTransferIDbyTransferNo(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text), txtRefNo.Text.Trim());
            //string DBName = ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text);

            //string sCmd = "Update " + DBName + ".transferstockdetail set PackQuantity = '" + qty.Text + "' where transferid = '" + sTransferIID + "' and barcode = '" + barcode.Text + "'";
            //Q = ObjCloud.ExecuteNonQuery(sCmd);

            //grdTransferDetails.EditIndex = -1;
            //LoadTransferDetails(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text), sTransferIID);
        }

        protected void grdTranferDetails_RowCancelingEdit(object sender, System.Web.UI.WebControls.GridViewCancelEditEventArgs e)
        {
            //Setting the EditIndex property to -1 to cancel the Edit mode in Gridview  
            string sTransferIID = ObjSel.GetTransferIDbyTransferNo(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text), txtRefNo.Text.Trim());
            grdTransferDetails.EditIndex = -1;
            LoadTransferDetails(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text), sTransferIID);
        }

        protected void grdTranferDetails_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            // DialogResult result = MessageBox.Show("Do you Want to Start the service", "Confirmation", MessageBoxButtons.YesNo);
            GridViewRow row = (GridViewRow)grdTransferDetails.Rows[e.RowIndex];
            // SqlCommand cmd = new SqlCommand("Delete From userTable (userName,age,birthPLace)");
            Label barcode = grdTransferDetails.Rows[e.RowIndex].FindControl("lblBarcode") as Label;
            Label TSDetailID = grdTransferDetails.Rows[e.RowIndex].FindControl("lblTSDetailID") as Label;
            string sTransferIID = ObjSel.GetTransferIDbyTransferNo(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text), txtRefNo.Text.Trim());
            string DBName = ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text);

            //string sCmd = "Update " + DBName + ".transferstockdetail set PackQuantity = '" + qty.Text + "' where transferid = '" + sTransferIID + "' and barcode = '" + barcode.Text + "'";
            string sCmd = "Delete from {0}.transferstockdetail where barcode=@barcode and TSDetailID=@TSDetailID";
            string command = string.Format(sCmd, DBName);
            MySqlParameter[] parameters =
                       {
                         new MySqlParameter("@barcode",barcode.Text ),
                         new MySqlParameter("@TSDetailID",TSDetailID.Text),
                       };

            Q = ObjMain.ExecuteQuery(command, parameters);


            //grdTransferDetails.DataBind();
            LoadTransferDetails(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text), sTransferIID);
        }

        protected void grdTranferDetails_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            string Name = e.CommandName;

            if (Name == "Update")
            {
                string sTransferIID = ObjSel.GetTransferIDbyTransferNo(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text), txtRefNo.Text.Trim());
                string DBName = ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text);

                RowIndex = int.Parse(e.CommandArgument.ToString());
                string sBarcode = grdTransferDetails.DataKeys[RowIndex]["Barcode"].ToString();
                string sTSDetailID = grdTransferDetails.DataKeys[RowIndex]["lblTSDetailID"].ToString();
                GridViewRow GV = grdTransferDetails.Rows[RowIndex];


                string Qty = ((TextBox)GV.FindControl("txtAdjQTY")).Text;
                //string lblupdate = ((TextBox)GV.FindControl("")).Text;


                //Label lblupdate = GV.FindControl("lblupdate") as Label;
                //lblupdate.Text = "Updated";

                string sCmd = "Update {0}.transferstockdetail set PackQuantity=@PackQuantity where transferid =@transferid and barcode=@barcode and TSDetailID=@TSDetailID ";

                string command = string.Format(sCmd, DBName);
                MySqlParameter[] parameters =
                      {
                         new MySqlParameter("@PackQuantity",Qty ),
                         new MySqlParameter("@transferid",sTransferIID),
                         new MySqlParameter("@barcode",sBarcode),
                         new MySqlParameter("@TSDetailID",sTSDetailID),

                       };

                Q = ObjCloud.ExecuteQuery(command, parameters);

                // LoadTransferDetails(ObjSel.GetBranchDBNamebyFullName(Session["Branch_HQ"].ToString(), cmbBranches.Text), sTransferIID);
                //ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Group1  Name Deleted  ! ');location.href='GroupMaster.aspx'", true);
                //Response.Redirect("GroupMaster.aspx");

                //ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Items Added ');location.href='AddTransferStock.aspx?Branchname=" + cmbBranches.Text + "&TransferNo=" + txtRefNo.Text + "'", true);
                Response.Redirect(Request.RawUrl);



            }



        }

        protected void grdDisplayItems_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {


            string DBName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), txtFBranch.Text.Trim());
            if (cmbBranches.Visible == false)
            {
                grdDisplayItems.PageIndex = e.NewPageIndex;
                LoadItems(Session["Branch_HQ"].ToString());
            }
            else
            {

                #region  Validation Between HQ Branch and Normal Branch 
                //  BranchFullName = cmbBranches.SelectedItem.Text;      // This will Return Branch FullName 
                if (txtFBranch.Text.Trim() == "HQ")
                {
                    DBName = Session["Branch_HQ"].ToString();
                }
                else
                {
                    //BranchName = cmbBranches.SelectedItem.Text;     // This will Return Branch FullName 
                    DBName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), txtFBranch.Text.Trim());  // This will Return BranchName( Actual Database Name )
                    //DBName = cmbBranch;

                }
                #endregion


                grdDisplayItems.PageIndex = e.NewPageIndex;

                ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "ShowModalItems();", true);

                string sCondition = string.Empty;

                if (cmbSearchOption.SelectedValue == "1") //Barcode
                {
                    sCondition = "and Barcode like CONCAT('%',@InputValue,'%') ";
                }
                else if (cmbSearchOption.SelectedValue == "2") //Name
                {
                    sCondition = "and InventoryName like CONCAT('%',@InputValue,'%') ";
                }
                else if (cmbSearchOption.SelectedValue == "3") //Description
                {
                    sCondition = "and Description like CONCAT('%',@InputValue,'%') ";
                }

                if (Convert.ToInt32(Session["gridIndex"]) == 0)
                {
                    string sCmd = "Select InventoryID,Barcode,InventoryName,Description from {0}.inventory where active<>0 and barcode <> 'round' " + sCondition + ";";
                    string command = string.Format(sCmd, DBName);

                    MySqlParameter[] parameters =
                    {
                     new MySqlParameter("@InputValue",txtSearchInput.Text),

                };

                    DTInventory = ObjMain.NewGetData_DT(command, parameters);
                    grdDisplayItems.PageIndex = e.NewPageIndex;
                    grdDisplayItems.DataSource = DTInventory;
                    grdDisplayItems.DataBind();
                }
                else
                {
                    string sCmd = "Select InventoryID,Barcode,InventoryName,Description from {0}.inventory where active<>0 and barcode <> 'round' " + sInventoryID + " " + sInventoryname + "  " + sBarcode + ";";
                    string command = string.Format(sCmd, DBName);
                    MySqlParameter[] parameters =
                     {
                     new MySqlParameter("@Inventoryid",txtInventoryid.Text),
                     new MySqlParameter("@InventorySearchTxt",txtInventoryNameSearch.Text.Trim()),
                     new MySqlParameter("@BarcodeSearchTxt",txtBarcodesearch.Text.Trim()),
                    };
                    DTInventory = ObjMain.NewGetData_DT(command, parameters);
                    grdDisplayItems.PageIndex = int.Parse(Session["gridIndex"].ToString());
                    grdDisplayItems.PageIndex = e.NewPageIndex;
                    grdDisplayItems.DataSource = DTInventory;
                    grdDisplayItems.DataBind();

                }



            }
        }

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

            string JSONResult = string.Empty;
            //string sTransferID = "1";
            string sQuery = "Select * from  {0}.transferstock 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 GetReportDetail(string DB, string TransferID)
        {
            DataTable DTDetail = new DataTable();
            MYSQLDB MySqlObj = new MYSQLDB();

            string JSONResult = string.Empty;
            // string sTransferID = "1";
            string sQuery = "Select A.Barcode,InventoryName,Description,Unit,PackQuantity from {0}.transferstockdetail A " +
                            " join {0}.Inventory B on A.InventoryID = B.InventoryID 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;
        }

        //John added on 27-Feb-2025
        [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_InventoryList(string db)
        {
            BL_API objAPI = new BL_API();
            string bearertoken = string.Empty;
            bearertoken = objAPI.GetBarerToken();
            string json = objAPI.GET_Inventories(bearertoken, db);
            var obj = JsonConvert.DeserializeObject(json);
            return obj.ToString();
        }

        [WebMethod]
        public static string GET_Categories(string db)
        {
            BL_API objAPI = new BL_API();
            string bearertoken = string.Empty;
            bearertoken = objAPI.GetBarerToken();
            string json = objAPI.GET_Categories(bearertoken, db);
            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();
        }

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

        [WebMethod]
        public static string ICAD(string db)
        {

            //BL_API objAPI = new BL_API();
            //string bearertoken = string.Empty;
            //bearertoken = objAPI.GetBarerToken();

            //string json = objAPI.GET_Inventories(bearertoken, db);
            //var obj = JsonConvert.DeserializeObject(json);
            //return obj.ToString();


            BL_API objAPI = new BL_API();
            string bearertoken = string.Empty;
            bearertoken = objAPI.GetBarerToken();

            //inventory
            string inventories = objAPI.GET_Inventories(bearertoken, db);
            var jsoninventories = JsonConvert.DeserializeObject(inventories).ToString();
            //IEnumerable<InventoryModel> lInventories = JsonConvert.DeserializeObject<IEnumerable<InventoryModel>>(jsoninventories);
            IList<InventoryModel> lInventories = JsonConvert.DeserializeObject<IList<InventoryModel>>(jsoninventories);
            var obj = JsonConvert.DeserializeObject(inventories);
            return obj.ToString();
        }

        [WebMethod]
        public static string InventoryWithCostDetail(string db)
        {
            //try
            //{

                JavaScriptSerializer json_serializer = new JavaScriptSerializer();
                IEnumerable<InventoryModel> oInventory;
                InventoryCategories oCateogry;
                InventoryCostAverageDetail oInventoryCostAverageDetail;

                BL_API objAPI = new BL_API();
                string bearertoken = string.Empty;
                bearertoken = objAPI.GetBarerToken();

                //inventory
                var inventories = objAPI.GET_Inventories(bearertoken, db);
                var jsoninventories = JsonConvert.DeserializeObject(inventories).ToString();
                IEnumerable<InventoryModel> lInventories = JsonConvert.DeserializeObject<IEnumerable<InventoryModel>>(jsoninventories);
             
                //category
                var categories = objAPI.GET_Categories(bearertoken, db);
                var jsoncategories = JsonConvert.DeserializeObject(categories).ToString();
                IEnumerable<InventoryCategories> lCategories = JsonConvert.DeserializeObject<IEnumerable<InventoryCategories>>(jsoncategories);

                //inventorycostaverage
                var inventorycostaverage = objAPI.GET_InventoryCostAverage(bearertoken, db);
                var jsoninventorycostaverage = JsonConvert.DeserializeObject(inventorycostaverage).ToString();
                IEnumerable<InventoryCostAverage> lInventoryCostAverage = JsonConvert.DeserializeObject<IEnumerable<InventoryCostAverage>>(jsoninventorycostaverage);


                //inventorycostaveragedetail
                var inventorycostavergeadetails = objAPI.GET_InventoryCostAverageDetail(bearertoken, db);
                var jsoninventorycostavergeadetails = JsonConvert.DeserializeObject(inventorycostavergeadetails).ToString();
                IEnumerable<InventoryCostAverageDetail> lInventoryCostAverageDetails = JsonConvert.DeserializeObject<IEnumerable<InventoryCostAverageDetail>>(jsoninventorycostavergeadetails);


             
                List<InventoryDetail> inventorydetail = new List<InventoryDetail>();

                //var icadetaillist = new List<InventoryCostAverageDetail>();
                //var inventorydetail = new List<InventoryDetail>();



                foreach (InventoryCategories category in lCategories)
                {
                    foreach (InventoryModel inventory in lInventories)
                    {
                        if (category.CategoryID == inventory.CategoryID)
                        {
                            foreach (InventoryCostAverage inventoryCostAverage in lInventoryCostAverage)
                            {
                                if (inventoryCostAverage.InventoryID == inventory.InventoryID)
                                {
                                    List<InventoryCostAverageDetail> icadetaillist = new List<InventoryCostAverageDetail>();
                                    foreach (InventoryCostAverageDetail inventoryCostAverageDetail in lInventoryCostAverageDetails)
                                    {
                                        if (inventoryCostAverageDetail.inventoryid == inventory.InventoryID)
                                        {
                                            icadetaillist.Add(inventoryCostAverageDetail);
                                        }                                 
                                    }

                                    double inqty = 0.00;
                                    double outqty = 0.00;

                                    var itemlist = lInventoryCostAverageDetails.Where(x => x.inventoryid == inventory.InventoryID);

                                    foreach (var x in itemlist)
                                    {
                                        inqty = inqty + (double)x.inqty;
                                        outqty = outqty + (double)x.outqty;
                                    }

                                    InventoryDetail inventoryDetail = new InventoryDetail(
                                            inventoryid: inventory.InventoryID,
                                            barcode: inventory.Barcode.Trim(),
                                            name: inventory.InventoryName.Trim(),
                                            description: inventory.Description.Trim(),
                                            categoryid: category.CategoryID,
                                            category: category.CategoryName.Trim(),
                                            totalinqty: inqty,
                                            totaloutqty: outqty,
                                            qoh: (inqty - outqty),
                                            icadetail: icadetaillist
                                        );
                                    inventorydetail.Add(inventoryDetail);
                                }
                            }
                        }

                    }
                }

                var json = JsonConvert.SerializeObject(inventorydetail);
                return json.ToString();
            //}

            //catch (Exception ex)
            //{
            //    Console.WriteLine(ex.Message);
            //}

            //return "";

        }

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

        [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();
        }

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

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

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

        #endregion
    }
}
