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 MySql.Data;
using System.Security.Cryptography;
using System.IO;
using CLS_BL;
using CLS_DL;
using CLS_PL;
 
namespace SUNWEB
{
    public partial class OnlineKDS : System.Web.UI.Page
    {
        BL_SELECT ObjSel = new BL_SELECT();
        BLCompany ObjBL = new BLCompany();
        PLCOMMON ObjPL = new PLCOMMON();
        BL_ErrorLog ObjError = new BL_ErrorLog();
        BL_USER ObjUserBL = new BL_USER(); //This Object for All User and Page Related fuctions included 
        PLCUSTOMER ObjCustPL = new PLCUSTOMER();
        Int32 K = 0;
        Int32 L = 0;
        Int32 S = 0;
        string ConStr = ConfigurationManager.ConnectionStrings["ConMysql"].ConnectionString;
        string ConStr_Rds = ConfigurationManager.ConnectionStrings["ConRDS"].ConnectionString;
        string Curr_Date = System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
        string Curr_DateOnly = System.DateTime.Now.ToString("yyyy-MM-dd");
        DateTime MonthstartDt;
        DataSet ds = new DataSet();
        MYSQLDB ObjMain = new MYSQLDB();
        DataTable DT = new DataTable();
        DataTable Dt1 = new DataTable();
        DataTable Dt2 = new DataTable();
        DataTable Dt3 = new DataTable();
        DataTable Dt4 = new DataTable();
        DataTable 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 BraNam = "";
        string FDate = "";
        string TDate = "";

        string HQ = string.Empty;
        string Cm_id = string.Empty;
        string ISHQ = string.Empty;
        string L_OnlineKDS = string.Empty;
        string OrderCnt = string.Empty;
        protected void Page_Load(object sender, EventArgs e)
        {

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


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

                    string QueryCal = "select ActiveValue from portaldb.usermaster  where Userid=" + Session["UserId"].ToString() + " ";
                    ActiveCallvalue = ObjMain.ExecuteScalar(QueryCal);
                    if (ActiveCallvalue != " " || ActiveCallvalue != "Select Branch")
                    {
                        LoadBranchName4SuperAdmin();
                        ActiveCall();
                       
                    }
                }
            }
            else if (((Convert.ToBoolean(Session["IsSuperAdmin"])) == true) && (Session["PortalTypeId"].ToString() == ""))
            {
                if (!IsPostBack)
                {
                    LoadBranchName4SuperAdmin();
                }
                cd_BranchAlias = cmbBranches.SelectedItem.Text;
                LoadOrderList(cd_BranchAlias, txtStartDt.Text, txtEndDt.Text);
                LoadCompletedList(cd_BranchAlias, txtStartDt.Text, txtEndDt.Text);
                LoadCancelledList(cd_BranchAlias, txtStartDt.Text, txtEndDt.Text);
                LoadAdvanceBooking(cd_BranchAlias, txtStartDt.Text, txtEndDt.Text);
            }
            else if (((Convert.ToBoolean(Session["IsMultiBranch"])) == true) && (Session["PortalTypeId"].ToString() == ""))
            {
                if (!IsPostBack)
                {
                    LoadBranchName();
                    ActiveCall();
                }
            }
            else if (((Session["PortalTypeId"].ToString() != "") || (Convert.ToBoolean(Session["IsSuperAdmin"])) == false) && ((Convert.ToBoolean(Session["IsMultiBranch"])) == false))
            {
                cmbBranches.Enabled = false;
                cmbBranches.Visible = false;

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

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

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

                    Session["Page_Acess"] = Page_Acess;
                    Session["Read_Acess"] = Read_Acess;
                    Session["Write_Acess"] = Write_Acess;
                    Session["Isdowld_Acess"] = Isdowld_Acess;
                }
                if ((Session["L_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
                        {
                            btnGetReports.Visible = true;

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

                        }


                    }

                }

            }
            else
            {

            }


        }


        public void ActiveCall()
        {

            try
            {




                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;
                    Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), cd_BranchAlias);  // This will Return BranchName( Actual Database Name )
                    LoadOrderList(Cmb_BranchName, txtStartDt.Text, txtEndDt.Text);
                    LoadCompletedList(Cmb_BranchName, txtStartDt.Text, txtEndDt.Text);
                    LoadCancelledList(Cmb_BranchName, txtStartDt.Text, txtEndDt.Text);
                    LoadAdvanceBooking(Cmb_BranchName, txtStartDt.Text, txtEndDt.Text);



                }
            }
            catch (Exception Ex)
            {
                ObjError.Write(Ex);
            }

        }


        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 btnGetReports_Click(object sender, EventArgs e)
        {
            if (cmbBranches.Visible == false)
            {
                btnGetReports.Visible = true;
                //lblMsgTotalSelection.Text = "Search Result - Journal Report Between" + "&nbsp;&nbsp;&nbsp;" + txtFromDt.Text + "&nbsp;&nbsp;&nbsp;  And &nbsp;&nbsp;&nbsp;" + txtToDt.Text;
                lblGreeting.Text = "Search Result - from" + "&nbsp;&nbsp;" + txtStartDt.Text + "&nbsp;&nbsp to &nbsp;&nbsp;" + txtEndDt.Text;
                //idGenReport.Attributes.Add("style", "background-color: #4c4c4c; color: White;font-size:14px");
                LoadOrderList(Session["Branch_HQ"].ToString(), txtStartDt.Text, txtEndDt.Text);
                LoadCompletedList(Session["Branch_HQ"].ToString(), txtStartDt.Text, txtEndDt.Text);
                LoadCancelledList(Session["Branch_HQ"].ToString(), txtStartDt.Text, txtEndDt.Text);
                LoadAdvanceBooking(Session["Branch_HQ"].ToString(), txtStartDt.Text, txtEndDt.Text);
                System.Threading.Thread.Sleep(2000);
            }
            else if (cmbBranches.Visible == true)
            {
                //lblMsgTotalSelection.Text = "Search Result - Journal Report Between" + "&nbsp;&nbsp;&nbsp;" + txtFromDt.Text + "&nbsp;&nbsp;&nbsp;  And &nbsp;&nbsp;&nbsp;" + txtToDt.Text;
                lblGreeting.Text = "Search Result - from" + "&nbsp;&nbsp;" + txtStartDt.Text + "&nbsp;&nbsp to &nbsp;&nbsp;" + txtEndDt.Text;
                //idGenReport.Attributes.Add("style", "background-color: #4c4c4c; color: White;font-size:14px");
                Curr_BranchFullName = cmbBranches.SelectedItem.Text;
                cd_BranchAlias = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), Curr_BranchFullName);  // This will Return BranchName( Actual Database Name )
                BraNam = cd_BranchAlias;
                FDate = txtStartDt.Text;
                TDate = txtEndDt.Text;
                LoadOrderList(cd_BranchAlias, txtStartDt.Text, txtEndDt.Text);
                LoadCompletedList(cd_BranchAlias, txtStartDt.Text, txtEndDt.Text);
                LoadCancelledList(cd_BranchAlias, txtStartDt.Text, txtEndDt.Text);
                LoadAdvanceBooking(cd_BranchAlias, txtStartDt.Text, txtEndDt.Text);
            }
        }
        
        protected void LoadOrderList(string BranchAlias, string D1, string D2)
        {
            System.Threading.Thread.Sleep(1000);
            MySqlConnection Cn = new MySqlConnection(ConStr_Rds);
            Cn.Open();
            string sCmd;

            //sCmd = "Select T.TransID as TransID, T.TransNo as TransNo, T.TransStatus as TStatus, DATE_FORMAT(T.TransDate,'%Y-%m-%d') as TDate, T.LastDate as LDate, T.CashierName as CName, T.SalesPersonName as SPName," +
            //    " Format(T.SubTotal,2) as SubTotal, Format((T.DiscAmount+T.MemberDiscAmount+T.BirthDayDiscAmount),2) as Disc, Format(T.TaxAmount1,2) as Tax1, Format(T.TaxAmount2,2) as Tax2, Format(T.Total,2) as Total " +
            //    " From " + BranchAlias + ".Trans T " +
            //    " Where T.BusinessDate Between '" + txtFromDt.Text + "' and '" + txtToDt.Text + "' ";

            sCmd = "Select T.Transid As TransID,T.Transno As TransNo, TP.PayDate As PayDate,T.DeliveryDate As DeliveryDate, Round(TP.PaymentAmount,2) as PayAmt, Tp.PaymentType As PaymentType, " +
            " T.Userid as UserID,IFNULL(T.olStatus,'Pending')  as Olstatus " +
            " From  " + BranchAlias + ".Trans as T   Join   " + BranchAlias + ".TransPayment as TP On T.Transid=TP.Transid  Inner Join  " + BranchAlias + ".OLUsermaster as U on T.Userid=U.Userid " +
            " Where Date(TP.PayDate) Between '" + txtStartDt.Text + "' and '" + txtEndDt.Text + "' And DATE_FORMAT(T.DeliveryDate, '%Y-%m-%d') <= '" + txtEndDt.Text + "' And  T.Transstatus=2  And T.olStatus Is Null";

            MySqlDataAdapter Ada = new MySqlDataAdapter(sCmd, Cn);
            ds = new DataSet();
            Ada.Fill(Dt1);
            GridView1.DataSource = Dt1;
            //gridview totals
            GridView1.DataBind();
        }


        protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "EditDetails")
            {
                GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
                Label lblTransid = (Label)row.Cells[0].FindControl("lblTransid");
                string Transids = lblTransid.Text.Trim();
                Response.Redirect("~/OnlineKDSDetails.aspx?Transid=" + Encrypt_QueryString(Transids.ToString().Trim()));

            }
        }


        protected void LoadCompletedList(string BranchAlias, string D1, string D2)
        {
            System.Threading.Thread.Sleep(1000);
            MySqlConnection Cn = new MySqlConnection(ConStr_Rds);
            Cn.Open();
            string sCmd;

            //sCmd = "Select T.TransID as TransID, T.TransNo as TransNo, T.TransStatus as TStatus, DATE_FORMAT(T.TransDate,'%Y-%m-%d') as TDate, T.LastDate as LDate, T.CashierName as CName, T.SalesPersonName as SPName," +
            //    " Format(T.SubTotal,2) as SubTotal, Format((T.DiscAmount+T.MemberDiscAmount+T.BirthDayDiscAmount),2) as Disc, Format(T.TaxAmount1,2) as Tax1, Format(T.TaxAmount2,2) as Tax2, Format(T.Total,2) as Total " +
            //    " From " + BranchAlias + ".Trans T " +
            //    " Where T.BusinessDate Between '" + txtFromDt.Text + "' and '" + txtToDt.Text + "' ";

            sCmd = "Select T.Transid As TransID,T.Transno As TransNo, TP.PayDate As PayDate,T.DeliveryDate As DeliveryDate, Round(TP.PaymentAmount,2) as PayAmt, Tp.PaymentType As PaymentType, " +
            " T.Userid as UserID,IFNULL(T.olStatus,'Pending')  as Olstatus " +
            " From  " + BranchAlias + ".Trans as T   Join   " + BranchAlias + ".TransPayment as TP On T.Transid=TP.Transid  Inner Join  " + BranchAlias + ".OLUsermaster as U on T.Userid=U.Userid " +
            " Where Date(TP.PayDate) Between '" + txtStartDt.Text + "' and '" + txtEndDt.Text + "' And  T.Transstatus=2  And T.olStatus ='Prepared' ";

            MySqlDataAdapter Ada1 = new MySqlDataAdapter(sCmd, Cn);
            ds = new DataSet();
            Ada1.Fill(Dt2);
            GridView2.DataSource = Dt2;
            //gridview totals
            GridView2.DataBind();
        }

        protected void GridView2_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "EditDetails")
            {
                GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
                Label lblTransid = (Label)row.Cells[0].FindControl("lblTransid");
                string Transids = lblTransid.Text.Trim();
                Response.Redirect("~/OnlineKDSDetails.aspx?Transid=" + Encrypt_QueryString(Transids.ToString().Trim()));

            }
        }

        protected void LoadCancelledList(string BranchAlias, string D1, string D2)
        {
            System.Threading.Thread.Sleep(1000);
            MySqlConnection Cn = new MySqlConnection(ConStr_Rds);
            Cn.Open();
            string sCmd;

            //sCmd = "Select T.TransID as TransID, T.TransNo as TransNo, T.TransStatus as TStatus, DATE_FORMAT(T.TransDate,'%Y-%m-%d') as TDate, T.LastDate as LDate, T.CashierName as CName, T.SalesPersonName as SPName," +
            //    " Format(T.SubTotal,2) as SubTotal, Format((T.DiscAmount+T.MemberDiscAmount+T.BirthDayDiscAmount),2) as Disc, Format(T.TaxAmount1,2) as Tax1, Format(T.TaxAmount2,2) as Tax2, Format(T.Total,2) as Total " +
            //    " From " + BranchAlias + ".Trans T " +
            //    " Where T.BusinessDate Between '" + txtFromDt.Text + "' and '" + txtToDt.Text + "' ";

            sCmd = "Select T.Transid As TransID,T.Transno As TransNo, TP.PayDate As PayDate,T.DeliveryDate As DeliveryDate, Round(TP.PaymentAmount,2) as PayAmt, Tp.PaymentType As PaymentType, " +
            " T.Userid as UserID,IFNULL(T.olStatus,'Pending')  as Olstatus " +
            " From  " + BranchAlias + ".Trans as T   Join   " + BranchAlias + ".TransPayment as TP On T.Transid=TP.Transid  Inner Join  " + BranchAlias + ".OLUsermaster as U on T.Userid=U.Userid " +
            " Where Date(TP.PayDate) Between '" + txtStartDt.Text + "' and '" + txtEndDt.Text + "' And  T.Transstatus=2  And T.olStatus ='Cancel' ";

            MySqlDataAdapter Ada2 = new MySqlDataAdapter(sCmd, Cn);
            ds = new DataSet();
            Ada2.Fill(Dt3);
            GridView3.DataSource = Dt3;
            //gridview totals
            GridView3.DataBind();
        }

        protected void GridView3_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "EditDetails")
            {
                GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
                Label lblTransid = (Label)row.Cells[0].FindControl("lblTransid");
                string Transids = lblTransid.Text.Trim();
                Response.Redirect("~/OnlineKDSDetails.aspx?Transid=" + Encrypt_QueryString(Transids.ToString().Trim()));

            }
        }


        protected void LoadAdvanceBooking(string BranchAlias, string D1, string D2)
        {
            System.Threading.Thread.Sleep(1000);
            MySqlConnection Cn = new MySqlConnection(ConStr_Rds);
            Cn.Open();
            string sCmd;

            //sCmd = "Select T.TransID as TransID, T.TransNo as TransNo, T.TransStatus as TStatus, DATE_FORMAT(T.TransDate,'%Y-%m-%d') as TDate, T.LastDate as LDate, T.CashierName as CName, T.SalesPersonName as SPName," +
            //    " Format(T.SubTotal,2) as SubTotal, Format((T.DiscAmount+T.MemberDiscAmount+T.BirthDayDiscAmount),2) as Disc, Format(T.TaxAmount1,2) as Tax1, Format(T.TaxAmount2,2) as Tax2, Format(T.Total,2) as Total " +
            //    " From " + BranchAlias + ".Trans T " +
            //    " Where T.BusinessDate Between '" + txtFromDt.Text + "' and '" + txtToDt.Text + "' ";

            sCmd = "Select T.Transid As TransID,T.Transno As TransNo, TP.PayDate As PayDate,T.DeliveryDate As DeliveryDate, Round(TP.PaymentAmount,2) as PayAmt, Tp.PaymentType As PaymentType, " +
            " T.Userid as UserID,IFNULL(T.olStatus,'Pending')  as Olstatus " +
            " From  " + BranchAlias + ".Trans as T   Join   " + BranchAlias + ".TransPayment as TP On T.Transid=TP.Transid  Inner Join  " + BranchAlias + ".OLUsermaster as U on T.Userid=U.Userid " +
            //" Where Date(TP.PayDate) Between '" + txtStartDt.Text + "' and '" + txtEndDt.Text + "' And  T.Transstatus=2  And T.olStatus Is Null";
            " Where Date(TP.PayDate) < Date(T.DeliveryDate) And  T.Transstatus=2  And T.olStatus Is Null Order by DeliveryDate, TransID";

            MySqlDataAdapter Ada = new MySqlDataAdapter(sCmd, Cn);
            ds = new DataSet();
            Ada.Fill(Dt4);
            GridView4.DataSource = Dt4;
            //gridview totals
            GridView4.DataBind();
        }


        protected void GridView4_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName == "EditDetails")
            {
                GridViewRow row = (GridViewRow)(((Button)e.CommandSource).NamingContainer);
                Label lblTransid = (Label)row.Cells[0].FindControl("lblTransid");
                string Transids = lblTransid.Text.Trim();
                Response.Redirect("~/OnlineKDSDetails.aspx?Transid=" + Encrypt_QueryString(Transids.ToString().Trim()));

            }
        }

        protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
        {

        }

        protected void GridView1_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {


            if (cmbBranches.Visible == false)
            {
                GridView1.PageIndex = e.NewPageIndex;

                LoadOrderList(Session["Branch_HQ"].ToString(), txtStartDt.Text, txtEndDt.Text);
                
            }
            else
            {

                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 )
                GridView1.PageIndex = e.NewPageIndex;
                LoadOrderList(Cmb_BranchName, txtStartDt.Text, txtEndDt.Text);
               

            }


        }

        protected void GridView2_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {


            if (cmbBranches.Visible == false)
            {
                GridView1.PageIndex = e.NewPageIndex;

              
                LoadCompletedList(Session["Branch_HQ"].ToString(), txtStartDt.Text, txtEndDt.Text);
              

            }
            else
            {

                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 )
                GridView1.PageIndex = e.NewPageIndex;
              
                LoadCompletedList(Cmb_BranchName, txtStartDt.Text, txtEndDt.Text);
              


            }


        }


        protected void GridView3_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {


            if (cmbBranches.Visible == false)
            {
                GridView1.PageIndex = e.NewPageIndex;

                LoadCancelledList(Session["Branch_HQ"].ToString(), txtStartDt.Text, txtEndDt.Text);

            }
            else
            {

                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 )
                GridView1.PageIndex = e.NewPageIndex;
                LoadCancelledList(Cmb_BranchName, txtStartDt.Text, txtEndDt.Text);


            }


        }


        protected void GridView4_PageIndexChanging(object sender, GridViewPageEventArgs e)
        {


            if (cmbBranches.Visible == false)
            {
                GridView4.PageIndex = e.NewPageIndex;

                LoadAdvanceBooking(Session["Branch_HQ"].ToString(), txtStartDt.Text, txtEndDt.Text);

            }
            else
            {

                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 )
                GridView4.PageIndex = e.NewPageIndex;
                LoadAdvanceBooking(Cmb_BranchName, txtStartDt.Text, txtEndDt.Text);


            }


        }


        protected void cmbBranches_SelectedIndexChanged(object sender, EventArgs e)
        {
            System.Threading.Thread.Sleep(1000);
            if (cmbBranches.SelectedIndex == 0)
            {
                Response.Redirect("OnlineKDS.aspx");
            }
            else
            {
                DT = ObjUserBL.GetPageRightsDetailsPIDNew(Session["UserId"].ToString(), PID, cmbBranches.SelectedItem.Value);
                if (DT.Rows.Count > 0)
                {
                    Page_Acess = DT.Rows[0]["Acess_status"].ToString();
                    Read_Acess = DT.Rows[0]["Read_Access"].ToString();
                    Write_Acess = DT.Rows[0]["Write_Access"].ToString();
                    Isdowld_Acess = DT.Rows[0]["IDwld_Access"].ToString();

                    Session["Page_Acess"] = Page_Acess;
                    Session["Read_Acess"] = Read_Acess;
                    Session["Write_Acess"] = Write_Acess;
                    Session["Isdowld_Acess_7"] = Isdowld_Acess;
                }

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

                if (ISHQ != "")
                {
                    ActiveCallvalue = ObjSel.GetFirstBranch(Session["Branch_HQ"].ToString());
                    UPDATEBRANCH(ActiveCallvalue);
                }
                else
                {
                    BranchFullName = cmbBranches.SelectedItem.Text;    // This will Return Branch FullName 
                    Cmb_BranchName = ObjUserBL.GetBranchRealValue(Session["Branch_HQ"].ToString(), Session["UserId"].ToString(), BranchFullName);  // This will Return BranchName( Actual Database Name )
                    Rcd_id = ObjMain.ExecuteScalar("select cd_id from portaldb.companydetails where cd_branchid=" + cmbBranches.SelectedItem.Value + " and cd_branchalias='" + Cmb_BranchName + "';");
                    RPortalid = ObjMain.ExecuteScalar("select portaltypeid  from portaldb.invoicedetails where cd_id=" + Rcd_id + ";");
                    DtLicense = ObjUserBL.GetLicenseDetails(RPortalid);

                }

                if (DtLicense.Rows.Count > 0)
                {

                    L_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
                {

                    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 )
                   
                    LoadOrderList(Cmb_BranchName, txtStartDt.Text, txtEndDt.Text);
                    LoadCompletedList(Cmb_BranchName, txtStartDt.Text, txtEndDt.Text);
                    LoadCancelledList(Cmb_BranchName, txtStartDt.Text, txtEndDt.Text);
                    UPDATEBRANCH(Cmb_BranchName);
                    ShowHideDive();
                   
                }

            }

            // Update the current Branch Selection in db
            UPDATEBRANCH(Cmb_BranchName);
            



        }

        public void ShowHideDive()
        {


            string QueryCal = "select ActiveValue from portaldb.usermaster  where Userid=" + Session["UserId"].ToString() + " ";
            ActiveCallvalue = ObjMain.ExecuteScalar(QueryCal);

            OrderCnt = ObjMain.ExecuteScalar("select count(*) as Cnt from   " + ActiveCallvalue + ".olkdsnotification where Status=0");

            if (OrderCnt == "")
            {
                System.Web.UI.HtmlControls.HtmlGenericControl OrderCntDiv = (System.Web.UI.HtmlControls.HtmlGenericControl)Master.FindControl("dvOrderCnt");
                OrderCntDiv.Visible = false;


            }
            else
            {

                if (Convert.ToInt32(OrderCnt) != 0)
                {

                    System.Web.UI.HtmlControls.HtmlGenericControl OrderCntDiv = (System.Web.UI.HtmlControls.HtmlGenericControl)Master.FindControl("dvOrderCnt");
                    Label lblOrderCnt = this.Master.FindControl("lblOrderCnt") as Label;
                    OrderCntDiv.Visible =true;
                    lblOrderCnt.Text = OrderCnt;
                     System.Media.SoundPlayer player = new System.Media.SoundPlayer(@"D:\KARTHIK\Developement\SUNWEB\SUNWEB\IMG\Sample.wav");
                    //System.Media.SoundPlayer player = new System.Media.SoundPlayer(@"C:\inetpub\wwwroot\TEST\IMG\Sample.wav");
                    player.Play();

                }
                else
                {

                    System.Web.UI.HtmlControls.HtmlGenericControl OrderCntDiv = (System.Web.UI.HtmlControls.HtmlGenericControl)Master.FindControl("dvOrderCnt");
                    OrderCntDiv.Visible = false;
                    
                }

               
            }
           
            
        
        }
        
        //Encryption  Code 

        public static string Encrypt_QueryString(string str)
        {
            string EncrptKey = "2013;[pnuLIT)WebCodeExpert";
            byte[] byKey = { };
            byte[] IV = { 18, 52, 86, 120, 144, 171, 205, 239 };
            byKey = System.Text.Encoding.UTF8.GetBytes(EncrptKey.Substring(0, 8));
            DESCryptoServiceProvider des = new DESCryptoServiceProvider();
            byte[] inputByteArray = Encoding.UTF8.GetBytes(str);
            MemoryStream ms = new MemoryStream();
            CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);
            cs.Write(inputByteArray, 0, inputByteArray.Length);
            cs.FlushFinalBlock();
            return Convert.ToBase64String(ms.ToArray());
        }


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





    }
}