using System;
using System.Collections.Generic;
using System.Linq;
using System.Collections;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Text;
using System.Configuration;
using MySql.Data.MySqlClient;
using System.Security.Cryptography;
using System.IO;
using MySql.Data;
using CLS_BL;
using CLS_DL;
using CLS_PL;

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

        string L_RetailPayment = string.Empty;
        string Branchidval = string.Empty;
        string BranchFullName = string.Empty;
        string Curr_BranchFullName = string.Empty;
        string Cmb_BranchName = string.Empty;

        string HQ = string.Empty;
        string Cm_id = string.Empty;
        string ISHQ = string.Empty;
        DataSet DS = new DataSet();
        string L_OnlineKDS = string.Empty;
        string Vw_Chk = string.Empty;
        string STrandid = string.Empty;

        DataTable Dt = new DataTable();
        DataTable DtNew = new DataTable();
        DataTable DtResult = new DataTable();
        DataTable DtRead = new DataTable();
        string TransID = string.Empty;

        string RTransNO = string.Empty;
        string RUserName = string.Empty;
        string RPassword = string.Empty;
        string RMobileNo = string.Empty;
        string REmail = string.Empty;
        string Addr1 = string.Empty;
        string Addr2 = string.Empty;
        string Addr3 = string.Empty;
        string Addr4 = string.Empty;
        int J = 0;

        // Default Value Passing 
        string TransStatus = "2";
        string BranchDB = "da1";
        //End 
        // Variable Declartion 
        string RItemsId = string.Empty;
        string CheckStatus = string.Empty;
        string kdsCheck = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {

            PID = "28";    // This is for Retail Payment Page 

            MonthstartDt = new DateTime(System.DateTime.Now.Year, System.DateTime.Now.Month, 1);
            if (Session["UserName"] == null)
            {
                Response.Redirect("Login.aspx");
            }
            if (((Convert.ToBoolean(Session["IsSuperAdmin"])) == true) && (Session["PortalTypeId"].ToString() == "") && ((Convert.ToBoolean(Session["IsMultiBranch"])) == true))
            {
                if (!IsPostBack)
                {
                    LoadBranchName4SuperAdmin();

                    string QueryCal = "select ActiveValue from portaldb.usermaster  where Userid=" + Session["UserId"].ToString() + " ";
                    ActiveCallvalue = ObjMain.ExecuteScalar(QueryCal);
                    if (ActiveCallvalue != " " || ActiveCallvalue != "Select Branch")
                    {
                        ActiveCall();

  
                    }
                }
            }
            else if (((Convert.ToBoolean(Session["IsSuperAdmin"])) == true) && (Session["PortalTypeId"].ToString() == ""))
            {
                if (!IsPostBack)
                {
                    LoadBranchName4SuperAdmin();
                }
                cd_BranchAlias = cmbBranches.SelectedItem.Text;
                
            }
            else if (((Convert.ToBoolean(Session["IsMultiBranch"])) == true) && (Session["PortalTypeId"].ToString() == ""))
            {
                if (!IsPostBack)
                {
                    LoadBranchName();
                    ActiveCall();
                }
            }
            else if (((Session["PortalTypeId"].ToString() != "") || (Convert.ToBoolean(Session["IsSuperAdmin"])) == false) && ((Convert.ToBoolean(Session["IsMultiBranch"])) == false))
            {
                cmbBranches.Enabled = false;
                cmbBranches.Visible = false;

                Cm_id = ObjSel.GETcmid(Session["Cd_Id"].ToString());  // Get cm_id
                HQ = ObjSel.Get_HQ(Cm_id);     // Get the HQ Value
                Curr_BranchFullName = ObjSel.GetBranchFullName(HQ, Session["Branch_HQ"].ToString());
                lblBranchAliasName.ForeColor = System.Drawing.Color.DodgerBlue;
                lblBranchAliasName.Text = "Branch Name" + "&nbsp;" + "-" + "&nbsp;" + Curr_BranchFullName + "&nbsp; ";

                cd_BranchAlias = Session["Branch_HQ"].ToString();
                Datapath = Session["DataPath"].ToString();
                PortalTypeId = Session["PortalTypeId"].ToString();

                DT = ObjUserBL.GetPageRightsDetailsPid(Session["UserId"].ToString(), PID);
                if (DT.Rows.Count > 0)
                {
                    Page_Acess = DT.Rows[0]["Acess_status"].ToString();
                    Read_Acess = DT.Rows[0]["Read_Access"].ToString();
                    Write_Acess = DT.Rows[0]["Write_Access"].ToString();
                    Isdowld_Acess = DT.Rows[0]["IDwld_Access"].ToString();

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

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

                        }


                    }

                }

            }
            else
            {

            }




            // modified before lin



        }



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


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

            if (ISHQ != "")
            {
                ActiveCallvalue = ObjSel.GetFirstBranch(Session["Branch_HQ"].ToString());
                UPDATEBRANCH(ActiveCallvalue);
            }

            cd_BranchAlias = ActiveCallvalue;
            Curr_BranchFullName = ObjUserBL.GetBranchCurr_BranchVal(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), cd_BranchAlias);
            Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), Curr_BranchFullName);  // This will Return BranchName( Actual Database Name )
            cmbBranches.Items.FindByText(Curr_BranchFullName).Selected = true;
            Branchidval = ObjUserBL.GetBranchIDbyName(ActiveCallvalue, ActiveCallvalue);
            if (Branchidval != "")
            {
                DT = ObjUserBL.GetPageRightsDetailsPIDNew(Session["UserId"].ToString(), PID, Branchidval);
            }
            else
            {
                DT = ObjUserBL.GetPageRightsDetailsPIDNew(Session["UserId"].ToString(), PID, Session["Fistbranch"].ToString());

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

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


                L_OnlineKDS = DtLicense.Rows[0]["ONLINEKDS"].ToString();
                Session["L_OnlineKDS"] = L_OnlineKDS;
            }
            if (Session["L_OnlineKDS"].ToString() == "N" || Session["Page_Acess"].ToString() == "N")
            {
                Response.Redirect("DeniedPage.aspx");
            }
            else
            {

                //btnExcel.Enabled = true;
                //lblMsgTotalSelection.Text = "Total Sale Selection Between" + "&nbsp;&nbsp;&nbsp;" + txtStartDt.Text + "&nbsp;&nbsp;&nbsp;  And &nbsp;&nbsp;&nbsp;" + txtEndDt.Text;
                cd_BranchAlias = cmbBranches.SelectedItem.Text;


                if (Request.QueryString["Transid"] != null)
                {
                    //int rowIndex = int.Parse(Request.QueryString["Transid"].ToString());
                    //TransID = Convert.ToString(rowIndex);
                    STrandid = Decrypt_QueryString(Request.QueryString["Transid"]).ToString().Trim();
                    TransID = STrandid;
                    hidTransid.Value = TransID;
                    BranchDB = Cmb_BranchName;
                }


                if (!IsPostBack)
                {

                    if (Request.QueryString["Transid"] != null)
                    {
                        //int rowIndex = int.Parse(Request.QueryString["Transid"].ToString());
                        //TransID = Convert.ToString(rowIndex);
                        STrandid = Decrypt_QueryString(Request.QueryString["Transid"]).ToString().Trim();
                        TransID = STrandid;

                        BranchDB = Cmb_BranchName;
                    }




                    string QueryHeader = "select T.Transid,T.Userid,T.TransNo,TD.ItemID, TD.Name,TD.InventoryDesc,T.TransStatus,T.TransDate,TP.Paydate,TD.Qty,TD.Price, TD.Amount,T.Subtotal ,TD.TaxableAmount,(T.TaxAmount1+T.Taxamount2+T.Taxamount3+T.TaxAmount4+T.TaxAmount5+T.TaxAmount6) AS Tax  ,TP.PaymentType,TP.PaymentAmount from  " + BranchDB + ".trans As T  join " + BranchDB + ".transdetail AS TD ON T.Transid=TD.Transid  join " + BranchDB + ".transpayment as TP  On T.Transid= TP.Transid  where T.Transid=" + TransID + "; ";
                    Dt = ObjMain.GetData_DT(QueryHeader);
                    dtOLOrderView.DataSource = Dt;
                    dtOLOrderView.DataBind();




                    // Reading Values from Db using Transid 
                    DtRead = ObjMain.GetData_DT("select T.Transid,T.TransNo,T.Userid, DATE_FORMAT(T.Transdate,'%d-%m-%Y') as Transdate,T.Subtotal,T.Taxamount1,T.Taxamount2 ,T.Taxamount3,T.Taxamount4,T.Taxamount5,T.Total,T.discAmount, DATE_FORMAT(TP.Paydate,'%d-%m-%Y') as Paydate,TP.PaymentType from  " + BranchDB + ".trans AS T Join " + BranchDB + ".transpayment as TP   ON T.Transid=TP.Transid where T.transid=" + TransID + ";");
                    lblHTransNO.Text = DtRead.Rows[0]["TransNo"].ToString();
                    lblOrderDate.Text = DtRead.Rows[0]["Transdate"].ToString();
                    lblPaymentType.Text = DtRead.Rows[0]["PaymentType"].ToString();
                    lblPaymentDate.Text = DtRead.Rows[0]["Paydate"].ToString();
                    hidUserid.Value = DtRead.Rows[0]["Userid"].ToString();

                    ReadUserData();

                    //Remove in olkdsnotification Table 

                    string query23 = "select * from   " + BranchDB + ".olkdsnotification where Status=0 and  TransID=" + TransID + " ;";
                    kdsCheck = ObjMain.ExecuteScalar(query23);

                    if (kdsCheck != "")
                    {
                        string QrykdsRemove = "delete from " + BranchDB + ".olkdsnotification where Status=0 and TransID=" + TransID + " ;";
                        S = ObjMain.ExecuteNonQuery(QrykdsRemove);
                    
                    }

                    
                }


              
                System.Threading.Thread.Sleep(1000);

            }

        }


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

            }

        }

        protected void dtOLOrderView_ItemDataBound(object sender, DataListItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                string RTransid = (e.Item.FindControl("lblTransid") as Label).Text;
                string RItemsId = (e.Item.FindControl("lblItemID") as Label).Text;
                DataList DtChild = e.Item.FindControl("dlCondiments") as DataList;

                string ChildQuery = " Select Condimentname from " + BranchDB + ".Transdetailcondiment where transid =" + RTransid + " and itemid =" + RItemsId + " ";
                DtNew = ObjMain.GetData_DT(ChildQuery);
                DtChild.DataSource = DtNew;
                DtChild.DataBind();

                // Assingin  Total Values to Lable
                lblTQTY.Text = GetTotalQTY(BranchDB, int.Parse(RTransid)) + "  Items";
                lblGST.Text = "S$" + " " + GETGST(BranchDB, int.Parse(RTransid));
                lblSubtotal.Text = "S$" + " " + GetSubTotal(BranchDB, int.Parse(RTransid));
                lblTOTAL.Text = "S$" + " " + GetGTotal(BranchDB, int.Parse(RTransid));
                lblSubTotalDL.Text = "S$" + " " + GetSubTotal(BranchDB, int.Parse(RTransid));
                lblQtyDL.Text = GetTotalQTY(BranchDB, int.Parse(RTransid));
            }

        }

        /// <summary>
        ///  This Function Gets Total Qty from Transdetails Table 
        /// </summary>
        /// <param name="sDB"></param>
        /// <param name="iTransID"></param>
        /// <returns></returns>
        private string GetTotalQTY(string sDB, int iTransID)
        {
            string sGetTotalQTY = string.Empty;
            sGetTotalQTY = ObjMain.ExecuteScalar("Select sum(QTY) TQty from " + sDB + ".Transdetail where Transid = " + iTransID + ";");
            if (sGetTotalQTY == "")
            {
                sGetTotalQTY = "0";
            }
            return sGetTotalQTY;
        }


        protected void cmbBranches_SelectedIndexChanged(object sender, EventArgs e)
        {





        }




        /// <summary>
        ///  This Fuction Uses to Get GST Amount Value
        /// </summary>
        /// <param name="sDB"></param>
        /// <param name="iTransID"></param>
        /// <returns></returns>
        private string GETGST(string sDB, int iTransID)
        {
            string sGETGST = string.Empty;
            sGETGST = ObjMain.ExecuteScalar("Select round(TaxAmount2,2) as TaxAmount2 from " + sDB + ".trans where transstatus =" + TransStatus + " and transid = " + iTransID + ";");
            if (sGETGST == "")
            {
                sGETGST = "N/A";
            }
            else if (sGETGST == "0.00")
            {
                sGETGST = "N/A";
            }
            return sGETGST.ToString();
        }


        /// <summary>
        /// This Function Gets the Subtotal Of Particular Transaction
        /// </summary>
        /// <param name="sDB"></param>
        /// <param name="iTransID"></param>
        /// <returns></returns>
        private string GetSubTotal(string sDB, int iTransID)
        {
            string sGetTotalQTY = string.Empty;
            sGetTotalQTY = ObjMain.ExecuteScalar("Select Round(subtotal,2) as Subtotal  from " + sDB + ".Trans where Transid = " + iTransID + ";");
            if (sGetTotalQTY == "")
            {
                sGetTotalQTY = "0";
            }
            return sGetTotalQTY;
        }




        private string GetGTotal(string sDB, int iTransID)
        {
            string sGTotal = string.Empty;
            sGTotal = ObjMain.ExecuteScalar("Select Round(Total,2) as GTotal  from " + sDB + ".Trans where Transid = " + iTransID + ";");
            if (sGTotal == "")
            {
                sGTotal = "0";
            }
            return sGTotal;
        }


        // Decryption  Code 

        public static string Decrypt_QueryString(string str)
        {
            str = str.Replace(" ", "+");
            string DecryptKey = "2013;[pnuLIT)WebCodeExpert";
            byte[] byKey = { };
            byte[] IV = { 18, 52, 86, 120, 144, 171, 205, 239 };
            byte[] inputByteArray = new byte[str.Length];

            byKey = System.Text.Encoding.UTF8.GetBytes(DecryptKey.Substring(0, 8));
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            inputByteArray = Convert.FromBase64String(str);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            System.Text.Encoding encoding = System.Text.Encoding.UTF8;
            return encoding.GetString(ms.ToArray());
        }


        public void ReadUserData()
        {
            DtRead = ObjMain.GetData_DT("Select *  from " + BranchDB + ".OLUserMaster where Userid=" + hidUserid.Value + "");

            if (DtRead.Rows.Count > 0)
            {
                RUserName = DtRead.Rows[0]["UserName"].ToString();
                RPassword = DtRead.Rows[0]["Password"].ToString();
                RMobileNo = DtRead.Rows[0]["MobileNo"].ToString();
                REmail = DtRead.Rows[0]["Email"].ToString();
                Addr1 = DtRead.Rows[0]["Address1"].ToString();
                Addr2 = DtRead.Rows[0]["Address2"].ToString();
                Addr3 = DtRead.Rows[0]["Address3"].ToString();
                Addr4 = DtRead.Rows[0]["Address4"].ToString();

                // Assign values to Lable

                lblCustomerName.Text = RUserName;
                lblCustMobile.Text = RMobileNo;
                var Customeraddress = Addr1;
                Customeraddress = Customeraddress.Replace(",", "<br />");
                lblAddress1.Text = Customeraddress;
                lblAddress2.Text = Addr2;
                //lblAddress3.Text = Addr3;
                //lblAddress4.Text = Addr4;

            }


        }

        protected void btnCofirm_Click(object sender, EventArgs e)
        {
            BranchFullName = cmbBranches.SelectedItem.Text;    // This will Return Branch FullName 
            Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);  // This will Return BranchName( Actual Database Name )

            string ChkQuery = " Select  OlStatus from " + Cmb_BranchName + ".Trans  where Transid=" + hidTransid.Value + "  ";
            CheckStatus = ObjMain.ExecuteScalar(ChkQuery);

            if (CheckStatus == "" || CheckStatus == null)
            {

                string Status = "Prepared";
                string UQuery = "Update  " + Cmb_BranchName + ".Trans  Set OlStatus='" + Status + "'  where Transid=" + hidTransid.Value + "   ";
                K = ObjMain.ExecuteNonQuery(UQuery);
                if (K > 0)
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Transaction  Completed !');location.href='OnlineKDS.aspx'", true);
                }
                else
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Transaction  Failed !');", true);
                }
                
            }
            else
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Transaction Status already Updated !');location.href='OnlineKDS.aspx'", true);
            }





        }
        protected void btnCancel_Click(object sender, EventArgs e)
        {

            BranchFullName = cmbBranches.SelectedItem.Text;    // This will Return Branch FullName 
            Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);  // This will Return BranchName( Actual Database Name )

            string ChkQuery = " Select  OlStatus from " + Cmb_BranchName + ".Trans  where Transid=" + hidTransid.Value + "  ";
            CheckStatus = ObjMain.ExecuteScalar(ChkQuery);

            if (CheckStatus == "" || CheckStatus == null)
            {
                string Status = "Cancel";
                string UQuery = "Update  " + Cmb_BranchName + ".Trans  Set OlStatus='" + Status + "'  where Transid=" + hidTransid.Value + "  ";
                K = ObjMain.ExecuteNonQuery(UQuery);
                if (K > 0)
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Transaction Cancelled !');location.href='OnlineKDS.aspx'", true);
                }
                else
                {
                    ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Transaction  Failed !');", true);
                }

               
            }
            else
            {
                ScriptManager.RegisterStartupScript(Page, Page.GetType(), "err_msg", "alert(' Transaction Status already Updated !');location.href='OnlineKDS.aspx'", true);
            }


        }




    }
}