Imports Microsoft.Office.Interop
Imports VERAG_PROG_ALLGEMEIN

Public Class frmEssensbestellungenAdministration

    Dim dt As DataTable
    Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL

    Private Sub frmEssensbestellungenAdministration_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        lblWarning.Text = ""
        txtBestellDat.Text = Today.ToShortDateString 'Date.Parse("01.01.2001")
        txtBestellDatBis.Text = Today.AddDays(7).ToShortDateString
        btnMonat.Text = MONAT.ToString("MMMM")
        btnJahr.Text = JAHR.Year

        txtMitarbeiter.Text = ""
        'cboGebaeude.changeItem("")
        'cboAbteilung.changeItem("")
        cbxStornos.Checked = False
        cbxAbgerechnet.Checked = False

        cboGebaeude.fillWithSQL("SELECT DISTINCT(eb_gebaeude) FROM [tblEssensbestellungen] where eb_archiviert = 0", False, "AVISO", True)
        cboGebaeude.changeItem("")

        cboAbteilung.fillWithSQL("SELECT DISTINCT(eb_abteilung) FROM [tblEssensbestellungen] where eb_archiviert = 0", False, "AVISO", True)

        'changeYear()

        cbKW.fillWithSQL("SELECT DISTINCT(eb_kw) FROM [tblEssensbestellungen] where eb_archiviert = 0 UNION SELECT (REPLACE(MenuTitel,'Wochenkarte ','')) + ' - ' +  Convert(varchar, Year(MenuDateVon)) as kwDateNew FROM [tblEBMenu] where MenuDateVon > GETDATE() ORDER BY eb_kw desc", False, "AVISO", True)

        cbxMailKW.fillWithSQL("SELECT DISTINCT(eb_kw) FROM [tblEssensbestellungen] where eb_archiviert = 0  ORDER BY eb_kw desc", False, "AVISO", True)
        cbxMailKW.changeItem("")

        cbxMailGebäude.changeItem("")
        cbxMailGebäude.Items.AddRange(cboGebaeude.Items.Cast(Of VERAG_PROG_ALLGEMEIN.MyListItem).ToArray())

        setMDM()

        loadBestellungen()

    End Sub


    Private Sub loadBestellungen()


        Dim SQLString As String = "SELECT [eb_mitid] , [eb_mitname] ,[eb_firma] , [eb_kw] , [eb_gebaeude],[eb_abteilung],[eb_montag],[eb_dienstag],[eb_mittwoch],
                                    [eb_donnerstag] ,[eb_freitag],[eb_datum],[eb_preis], [eb_anmerkung],[eb_storniert],[eb_storniert_am],[eb_abgerechnet],[eb_abgerechnet_am], [eb_gesendet], [eb_gesendet_am]  
                                    FROM 
                                    [tblEssensbestellungen] WHERE 1=1 "

        SQLString &= IIf(cAllgemein.MITARBEITER.getFirma = "UNISPED", " And eb_firma = '" & cAllgemein.MITARBEITER.getFirma & "'", "") 'UNISPED-Bestellungen!

        dgvBestellungen.SET_SQL(SQLString & bestellungenWhereClause() & " Order by eb_datum, eb_mitid", "AVISO", ,)
        dgvBestellungen.LOAD()


        With dgvBestellungen
            If .RowCount = 0 Then Me.Cursor = Cursors.Default : Exit Sub
            .RowHeadersVisible = False
            .ReadOnly = True
            .SelectionMode = DataGridViewSelectionMode.FullRowSelect

            .RowHeadersWidth = 10
            .Columns("eb_kw").HeaderText = "KW"
            .Columns("eb_kw").Width = 80
            .Columns("eb_mitid").HeaderText = "MID"
            .Columns("eb_mitid").HeaderText = "MID"
            .Columns("eb_mitid").Width = 40
            .Columns("eb_mitid").HeaderText = "MID"
            .Columns("eb_mitid").Visible = False
            .Columns("eb_mitname").HeaderText = "Mitarbeiter"
            .Columns("eb_mitname").AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
            .Columns("eb_abteilung").Visible = False
            .Columns("eb_firma").Width = 80
            .Columns("eb_firma").HeaderText = "Firma"
            .Columns("eb_datum").Width = 80
            .Columns("eb_datum").HeaderText = "Datum"
            .Columns("eb_montag").Width = 80
            .Columns("eb_montag").HeaderText = "Montag"
            .Columns("eb_montag").Width = 80
            .Columns("eb_dienstag").HeaderText = "Dienstag"
            .Columns("eb_dienstag").Width = 80
            .Columns("eb_mittwoch").HeaderText = "Mittwoch"
            .Columns("eb_mittwoch").Width = 80
            .Columns("eb_donnerstag").HeaderText = "Donnerstag"
            .Columns("eb_donnerstag").Width = 80
            .Columns("eb_freitag").HeaderText = "Freitag"
            .Columns("eb_freitag").Width = 80
            .Columns("eb_gebaeude").HeaderText = "Gebäude"
            .Columns("eb_gebaeude").Width = 100
            .Columns("eb_preis").HeaderText = "Preis"
            .Columns("eb_preis").Width = 40
            .Columns("eb_preis").DefaultCellStyle.Format = "N"
            .Columns("eb_storniert_am").HeaderText = "Storniert am"
            .Columns("eb_storniert_am").Width = 80
            .Columns("eb_abgerechnet_am").HeaderText = "Abgerechnet am"
            .Columns("eb_abgerechnet_am").Width = 80
            .Columns("eb_gesendet_am").HeaderText = "Gesendet am"
            .Columns("eb_gesendet_am").Width = 80
            .Columns("eb_storniert").Visible = False
            .Columns("eb_abgerechnet").Visible = False
            .Columns("eb_gesendet").Visible = False
            .Columns("eb_anmerkung").HeaderText = "Anmerkung"
        End With


        For Each row As DataGridViewRow In dgvBestellungen.Rows

            If Not IsDBNull(row.Cells("eb_gesendet").Value) Then
                If row.Cells("eb_gesendet").Value Then row.DefaultCellStyle.BackColor = Color.LightYellow
            End If

            If Not IsDBNull(row.Cells("eb_storniert").Value) Then
                If row.Cells("eb_storniert").Value Then
                    row.DefaultCellStyle.BackColor = Color.IndianRed
                End If
            End If
            If Not IsDBNull(row.Cells("eb_abgerechnet").Value) Then
                If row.Cells("eb_abgerechnet").Value Then row.DefaultCellStyle.BackColor = Color.LightGreen
            End If

        Next

        txtAnzahlDS.Text = dgvBestellungen.Rows.Count
        calcSumme()

    End Sub

    Private Function bestellungenWhereClause() As String

        Dim SQLwhere = ""

        If cboGebaeude._value IsNot "" Then SQLwhere &= " AND [eb_gebaeude] = '" & cboGebaeude._value.ToString & "'"
        If cboAbteilung._value IsNot "" Then
            SQLwhere &= " AND ([eb_abteilung] = '" & cboAbteilung._value.ToString & "'"
            If cboAbteilung._value = "MDM" Then
                SQLwhere &= " Or [eb_abteilung] = 'GF')"
            Else
                SQLwhere &= ")"
            End If
        End If
        If txtMitarbeiter.Text <> "" Then SQLwhere &= " AND [eb_mitname] like '%" & txtMitarbeiter.Text & "%'"

        If cbxAlleAnzeigen.Checked = False Then

            If cbxStornos.Checked Then
                SQLwhere &= " AND [eb_storniert] = '1'"
            Else
                SQLwhere &= " AND ISNULL([eb_storniert],0) = '0'"
            End If

            If cbxAbgerechnet.Checked Then
                SQLwhere &= " AND [eb_abgerechnet] = '1'"
            Else
                SQLwhere &= " AND ISNULL([eb_abgerechnet],0) = '0'"
            End If

            If cbxNichtAbgeschickt.Checked Then
                SQLwhere &= " AND ISNULL([eb_gesendet],0) = '0'"
            Else
                'SQLwhere &= " AND [eb_gesendet] = '1'"
            End If

        End If



        If txtBestellDat._value <> Nothing AndAlso txtBestellDatBis._value <> Nothing Then
            SQLwhere &= " AND [eb_datum] BETWEEN '" & txtBestellDat._value & "' AND '" & txtBestellDatBis._value & "'"
        End If

        Return SQLwhere

    End Function

    Private Sub DateTimePicker1_ValueChanged(sender As Object, e As EventArgs) Handles DateTimePicker1.ValueChanged
        txtBestellDat._value = CDate(sender.value).ToShortDateString
    End Sub

    Private Sub DateTimePicker2_ValueChanged(sender As Object, e As EventArgs) Handles DateTimePicker2.ValueChanged
        txtBestellDatBis._value = CDate(sender.value).ToShortDateString
    End Sub

    Private Sub btnMonat_Click(sender As Object, e As EventArgs) Handles btnMonat.Click
        initBtns("Monat")
    End Sub

    Dim MONAT As Date = CDate("01." & Now.Month & "." & Now.Year)


    Dim JAHR As Date = CDate("01.01." & Now.Year)

    Sub initBtns(MonatJahr)
        btnMonat.Text = MONAT.ToString("MMMM")
        btnJahr.Text = JAHR.Year
        Select Case MonatJahr
            Case "Monat"
                DateTimePicker1.Value = MONAT
                DateTimePicker2.Value = MONAT.AddMonths(1).AddDays(-1)
            Case "Jahr"
                DateTimePicker1.Value = JAHR
                DateTimePicker2.Value = JAHR.AddYears(1).AddDays(-1)
            Case ""
                DateTimePicker1.Value = ("01." & Now.Month & "." & Now.Year)
                DateTimePicker2.Value = Now
        End Select

    End Sub

    Private Sub btnJahr_Click(sender As Object, e As EventArgs) Handles btnJahr.Click
        initBtns("Jahr")
    End Sub

    Private Sub btnBisMonat_Click(sender As Object, e As EventArgs) Handles btnBisMonat.Click
        MONAT = MONAT.AddMonths(1)
        initBtns("Monat")
    End Sub

    Private Sub btnVonMonat_Click(sender As Object, e As EventArgs) Handles btnVonMonat.Click
        MONAT = MONAT.AddMonths(-1)
        initBtns("Monat")
    End Sub

    Private Sub btnBisJahr_Click(sender As Object, e As EventArgs) Handles btnBisJahr.Click
        JAHR = JAHR.AddYears(1)
        initBtns("Jahr")
    End Sub

    Private Sub btnVonJahr_Click(sender As Object, e As EventArgs) Handles btnVonJahr.Click
        JAHR = JAHR.AddYears(-1)
        initBtns("Jahr")
    End Sub

    Private Sub txtMitarbeiter_KeyDown(sender As Object, e As KeyEventArgs) Handles txtMitarbeiter.KeyDown
        If e.KeyCode = Keys.Enter Then

            Me.loadBestellungen()
            e.Handled = True

        End If
    End Sub

    Private Sub btnSuche_Click(sender As Object, e As EventArgs) Handles btnSuche.Click, cbxAbgerechnet.CheckedChanged, cbxStornos.CheckedChanged, cbxNichtAbgeschickt.CheckedChanged, cbxAlleAnzeigen.CheckedChanged

        If cbxAlleAnzeigen.Checked Then
            cbxAbgerechnet.Checked = Not cbxAlleAnzeigen.Checked
            cbxNichtAbgeschickt.Checked = Not cbxAlleAnzeigen.Checked
            cbxStornos.Checked = Not cbxAlleAnzeigen.Checked
        End If


        loadBestellungen()
    End Sub

    Private Sub FlatButton7_Click(sender As Object, e As EventArgs) Handles FlatButton7.Click
        cbKW.changeItem("")
        txtMitarbeiter.Text = ""
        cboGebaeude.changeItem("")
        cboAbteilung.changeItem("")
        cbxStornos.Checked = False
        cbxAbgerechnet.Checked = False
        txtBestellDat.Text = Date.Parse("01.01.2001")
        txtBestellDatBis.Text = Now.AddDays(7).ToShortDateString 'Um die aktuellen EB für nächste Woche zu sehen

        setMDM()

        Me.btnSuche.PerformClick()

    End Sub

    Private Sub calcSumme()

        Dim countSumme As Double = 0


        For i As Integer = 0 To dgvBestellungen.Rows.Count - 1
            countSumme += CDbl(dgvBestellungen.Rows(i).Cells("eb_preis").Value)

        Next

        txtSumme._value = countSumme.ToString

    End Sub

    Private Sub BearbeitenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles BearbeitenToolStripMenuItem.Click

        If dgvBestellungen.SelectedRows.Count < 1 Then Exit Sub

        Dim bestellung As New cEssensbestellung(dgvBestellungen.SelectedRows(0).Cells("eb_kw").Value, dgvBestellungen.SelectedRows(0).Cells("eb_mitid").Value)

        Using UserControl1 As SDL.UsrCntlessensbestellungen = New SDL.UsrCntlessensbestellungen(bestellung)
            Using tmpForm As Form = New Form()
                tmpForm.Width = UserControl1.Width
                tmpForm.Height = UserControl1.Height + 40
                tmpForm.Text = bestellung.eb_kw.ToString & " - " & bestellung.eb_mitname.ToString
                tmpForm.StartPosition = tmpForm.StartPosition.CenterParent
                tmpForm.Controls.Add(UserControl1)
                If tmpForm.ShowDialog() = DialogResult.OK Then
                    dgvBestellungen.GetOrder()
                    loadBestellungen()
                    dgvBestellungen.SetOrder()
                End If

            End Using
        End Using
    End Sub

    Private Sub AbgerechnetToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles AbgerechnetToolStripMenuItem.Click, StornierenToolStripMenuItem.Click, AnHigway118SchickenToolStripMenuItem.Click
        If dgvBestellungen.SelectedRows.Count = 0 Then Exit Sub

        Select Case sender.Text
            Case "abrechnen"
                Select Case dgvBestellungen.SelectedRows.Count
                    Case 1
                        If vbYes = MsgBox("Möchten Sie die Essensbestellung '" & dgvBestellungen.SelectedRows(0).Cells("eb_kw").Value & " von Mitarbeiter " & dgvBestellungen.SelectedRows(0).Cells("eb_mitname").Value & " abrechnen", vbYesNoCancel) Then
                            bestellungenAbrechnen(True)
                        Else
                            Exit Sub
                        End If
                    Case Else
                        If vbYes = MsgBox("Möchten Sie diese " & dgvBestellungen.SelectedRows.Count & " Essensbestellungen abrechnen", vbYesNoCancel) Then
                            bestellungenAbrechnen(True)
                        Else
                            Exit Sub

                        End If


                End Select


            Case "stornieren"
                Select Case dgvBestellungen.SelectedRows.Count
                    Case 1
                        If vbYes = MsgBox("Möchten Sie die Essensbestellung '" & dgvBestellungen.SelectedRows(0).Cells("eb_kw").Value & " von Mitarbeiter " & dgvBestellungen.SelectedRows(0).Cells("eb_mitname").Value & " wirklich stornieren", vbYesNoCancel) Then
                            bestellungenStornieren(True)
                        Else
                            Exit Sub
                        End If
                    Case Else

                        If vbYes = MsgBox("Möchten Sie diese " & dgvBestellungen.SelectedRows.Count & " Essensbestellungen wirklich stornieren", vbYesNoCancel) Then
                            bestellungenStornieren(True)
                        Else
                            Exit Sub
                        End If


                End Select


            Case "markierte Bestellungen per Mail senden"
                Select Case dgvBestellungen.SelectedRows.Count
                    Case 1
                        If vbYes = MsgBox("Möchten Sie die Essensbestellung '" & dgvBestellungen.SelectedRows(0).Cells("eb_kw").Value & " von Mitarbeiter " & dgvBestellungen.SelectedRows(0).Cells("eb_mitname").Value & " abschicken?", vbYesNoCancel) Then
                            bestellungenSenden(True)
                            generateEMailforHighway(sender, e)
                        Else
                            Exit Sub
                        End If
                    Case Else

                        If vbYes = MsgBox("Möchten Sie diese " & dgvBestellungen.SelectedRows.Count & " Essensbestellungen abschicken", vbYesNoCancel) Then
                            bestellungenSenden(True)
                            generateEMailforHighway(sender, e)
                        Else
                            Exit Sub
                        End If


                End Select


        End Select
        loadBestellungen()

    End Sub
    Private Sub bestellungenStornieren(stornieren As Boolean)


        For Each row As DataGridViewRow In dgvBestellungen.SelectedRows

            Dim bestellung As New cEssensbestellung(row.Cells("eb_kw").Value, row.Cells("eb_mitid").Value)

            bestellung.eb_storniert = True
            If stornieren Then
                bestellung.eb_storniert_am = Now
            Else
                bestellung.eb_storniert_am = DBNull.Value

            End If

            bestellung.eb_preis = 0

            bestellung.SAVE()


        Next

        dgvBestellungen.GetOrder()
        dgvBestellungen.LOAD()
        dgvBestellungen.SetOrder()

    End Sub

    Private Sub bestellungenAbrechnen(abrechnen As Boolean)


        For Each row As DataGridViewRow In dgvBestellungen.SelectedRows

            Dim bestellung As New cEssensbestellung(row.Cells("eb_kw").Value, row.Cells("eb_mitid").Value)

            bestellung.eb_abgerechnet = abrechnen
            If abrechnen Then
                bestellung.eb_abgerechnet_am = Now
            Else
                bestellung.eb_abgerechnet_am = DBNull.Value

            End If


            bestellung.SAVE()

        Next


        dgvBestellungen.GetOrder()
        dgvBestellungen.LOAD()
        dgvBestellungen.SetOrder()

    End Sub

    Private Sub bestellungenSenden(senden As Boolean)


        For Each row As DataGridViewRow In dgvBestellungen.SelectedRows

            Dim bestellung As New cEssensbestellung(row.Cells("eb_kw").Value, row.Cells("eb_mitid").Value)

            bestellung.eb_gesendet = senden
            If senden Then
                bestellung.eb_gesendet_am = Now
            Else
                bestellung.eb_gesendet_am = DBNull.Value

            End If

            bestellung.SAVE()

        Next

        If dgvBestellungen.RowCount > 0 Then

            dgvBestellungen.GetOrder()
            dgvBestellungen.LOAD()
            dgvBestellungen.SetOrder()

        End If

    End Sub

    Private Sub generateEMailforHighway(sender As Object, e As EventArgs)

        Me.Cursor = Cursors.WaitCursor
        Try
            Dim kw As String = ""
            Dim gebaeude As String = ""
            Dim TextHTMLtable = ""

            TextHTMLtable &= "<table border=1>"
            TextHTMLtable &= "<tr><td>Mitarbeiter</td><td>Montag</td><td>Dienstag</td><td>Mittwoch</td><td>Donnerstag</td><td>Freitag</td><td>Gebäude</td><td>Anmerkung</td><td>Firma</td></tr>"

            If sender.Text = "Email" Then

                Dim dtBestellungenMail = generateDTBestellungen()
                kw = cbxMailKW._value
                gebaeude = cbxMailGebäude._value
                If dtBestellungenMail.Rows.Count = 0 Then
                    Me.Cursor = Cursors.Default
                    Exit Sub
                End If
                For Each row As DataRow In dtBestellungenMail.Rows

                    TextHTMLtable &= "<tr>"
                    TextHTMLtable &= "<td><b>" & row("Name") & "</b></td>"
                    TextHTMLtable &= "<td><b>" & row("Montag") & "</b></td>"
                    TextHTMLtable &= "<td><b>" & row("Dienstag") & "</b></td>"
                    TextHTMLtable &= "<td><b>" & row("Mittwoch") & "</b></td>"
                    TextHTMLtable &= "<td><b>" & row("Donnerstag") & "</b></td>"
                    TextHTMLtable &= "<td><b>" & row("Freitag") & "</b></td>"
                    TextHTMLtable &= "<td><b>" & row("Gebaeude") & "</b></td>"
                    TextHTMLtable &= "<td><b>" & row("Anmerkung") & "</b></td>"
                    TextHTMLtable &= "<td><b>" & row("Firma") & "</b></td>"
                    TextHTMLtable &= "</tr>"

                    If row("ID") <> 0 Then
                        Dim bestellung As New cEssensbestellung(row("KW"), row("ID"))

                        bestellung.eb_gesendet = True
                        bestellung.eb_gesendet_am = Now
                        bestellung.SAVE()
                    End If
                Next

                dgvBestellungen.LOAD()

            Else
                If dgvBestellungen.SelectedRows.Count = 0 Then
                    lblWarning.Text = "keine Bestellungen markiert!"
                    Me.Cursor = Cursors.Default
                    Exit Sub
                End If
                For Each row In dgvBestellungen.SelectedRows

                    TextHTMLtable &= "<tr>"
                    TextHTMLtable &= "<td><b>" & row.Cells("eb_mitname").Value & "</b></td>"
                    TextHTMLtable &= "<td><b>" & row.Cells("eb_montag").Value & "</b></td>"
                    TextHTMLtable &= "<td><b>" & row.Cells("eb_dienstag").Value & "</b></td>"
                    TextHTMLtable &= "<td><b>" & row.Cells("eb_mittwoch").Value & "</b></td>"
                    TextHTMLtable &= "<td><b>" & row.Cells("eb_donnerstag").Value & "</b></td>"
                    TextHTMLtable &= "<td><b>" & row.Cells("eb_freitag").Value & "</b></td>"
                    TextHTMLtable &= "<td><b>" & row.Cells("eb_gebaeude").Value & "</b></td>"
                    TextHTMLtable &= "<td><b>" & row.Cells("eb_anmerkung").Value & "</b></td>"
                    TextHTMLtable &= "<td><b>" & row.Cells("eb_firma").Value & "</b></td>"
                    TextHTMLtable &= "</tr>"

                Next

            End If


            lblWarning.Text = ""

            Dim outl As New Outlook.Application
            Dim Mail As Microsoft.Office.Interop.Outlook.MailItem


            Mail = outl.CreateItem(0)
            Mail.To = "info@highway-118.de; service@highway-118.de"


            Mail.Subject = "Essensbestellung: " & IIf(kw <> "", kw, "") & " " & IIf(gebaeude <> "", gebaeude, "")

            Dim DETextHTML = ""
            DETextHTML &= "Hallo,<br>"
            DETextHTML &= "<br>"
            DETextHTML &= "Anbei ist die Essensbestellung " & IIf(kw <> "", "für " & kw, "") & ".<br>"

            TextHTMLtable &= "</table>"

            Dim EndTextHTML = ""

            EndTextHTML &= "<br>"
            EndTextHTML &= "<br>"
            EndTextHTML &= "Bitte um kurze Bestätigung nach Erhalt der Mail, danke. <br>"
            EndTextHTML &= "<br>"
            EndTextHTML &= "Mit freundlichen Grüßen/Best regards<br>"
            EndTextHTML &= VERAG_PROG_ALLGEMEIN.cAllgemein.USRNAME & "<br>"
            EndTextHTML &= "<br>"

            Mail.HTMLBody = "<div style=""font-family:Calibri, Arial;font-size:15px;"">" & DETextHTML & TextHTMLtable & EndTextHTML & SDL.cFakturierung.getSignature("DE", cAllgemein.FIRMA_ID, True, True) & "</div>"
            Mail.Display()

        Catch ex As Exception

            VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name,, "Fehler beim Öffnen der Mail!")
        End Try


        Me.Cursor = Cursors.Default


    End Sub

    Private Sub cbKW_SelectedValueChanged(sender As Object, e As EventArgs) Handles cbKW.SelectedValueChanged

        If cbKW._value Is Nothing Or cbKW._value = "" Then
            txtBestelllimit.Text = ""

            Exit Sub
        End If
        btnBestelllimit.Enabled = True

        If dt IsNot Nothing Then
            dt.Clear()
        End If

        dt = SQL.loadDgvBySql("SELECT Top 1 * from (SELECT (REPLACE(MenuTitel,'Wochenkarte ','')) + ' - ' +  Convert(varchar, Year(MenuDateVon)) as kwDate, MenuDateVon, MenuDateBis, MenuBestellungBisTageVorher FROM tblEBMenu) kwDate where kwDate = '" & cbKW._value & "'", "AVISO", 100, True)

        txtBestelllimit.Text = ""

        If dt.Rows.Count > 0 Then
            txtBestelllimit.Text = dt.Rows(0).Item("MenuBestellungBisTageVorher").ToString
            txtBestellDat.Text = CDate(dt.Rows(0).Item("MenuDateVon")).ToString("dd.MM.yyyy")
            txtBestellDatBis.Text = CDate(dt.Rows(0).Item("MenuDateBis")).ToString("dd.MM.yyyy")
            btnSuche.PerformClick()
        End If



    End Sub

    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click, Button2.Click
        lblWarning.Text = ""

        If cbxMailKW._value = "" Then
            lblWarning.Text = "Kalenderwoche auswählen!"
            Exit Sub
        End If

        If cbxMailGebäude._value = "" Then
            lblWarning.Text = "Gebäude auswählen!"
            Exit Sub
        End If


        Select Case sender.Text

            Case "Email"

                generateEMailforHighway(sender, e)

            Case "Excel"

                SDL.cProgramFunctions.genExcelFromDT_NEW(generateDTBestellungen(True),,,,,, True)

        End Select

    End Sub


    Private Function generateDTBestellungen(Optional exportToExcel As Boolean = False) As DataTable


        Dim dtBestellungen As DataTable

        Dim sqlWhere = ""

        If cAllgemein.MITARBEITER.getFirma = "UNISPED" Then
            sqlWhere &= " And eb_firma = '" & cAllgemein.MITARBEITER.getFirma & "' "
        Else
            sqlWhere &= " And (eb_firma = 'VERAG'  OR eb_firma = 'IMEX' OR eb_firma = 'FRONTOFFICE')"
        End If

        Dim SQLStringBEstellungen As String = ""
        SQLStringBEstellungen = "SELECT  [eb_mitname] as Name ,[eb_mitid] as ID , [eb_kw] as KW , [eb_gebaeude] as Gebaeude ,[eb_abteilung] as Abteilung ,[eb_montag] As Montag ,[eb_dienstag] As Dienstag,[eb_mittwoch] As Mittwoch,  
        [eb_donnerstag] As Donnerstag , [eb_freitag] As Freitag, [eb_anmerkung] As Anmerkung , [eb_datum] As Datum , [eb_storniert] as Storniert,  [eb_firma] as Firma, eb_MenuID
                                    FROM [tblEssensbestellungen] left join tblEBMenu on tblEBMenu.MenuID = eb_MenuID
        WHERE eb_kw = '" & cbxMailKW._value & "' AND eb_gebaeude = '" & cbxMailGebäude._value & "' AND ISNULL(eb_storniert,1)=0 " & sqlWhere & " Order by eb_datum"

        dtBestellungen = SQL.loadDgvBySql(SQLStringBEstellungen, "AVISO", 100, True)

        If dtBestellungen.Rows.Count = 0 Then
            lblWarning.Text = "Keine Bestellungen vorhanden!"
            Me.Cursor = Cursors.Default
            Return dtBestellungen
        End If




        Dim uniqueMenusMontag = dtBestellungen.AsEnumerable() _
                        .GroupBy(Function(row) _
                        New With
                        {
                        Key .Montag = row.Field(Of String)("Montag")
                       }
                   )


        Dim uniqueMenusDienstag = dtBestellungen.AsEnumerable() _
                        .GroupBy(Function(row) _
                        New With
                        {
                            Key .Dienstag = row.Field(Of String)("Dienstag")
                       }
                   )

        Dim uniqueMenusMittwoch = dtBestellungen.AsEnumerable() _
                        .GroupBy(Function(row) _
                        New With
                        {
                            Key .Mittwoch = row.Field(Of String)("Mittwoch")
                       }
                   )


        Dim uniqueMenusDonnerstag = dtBestellungen.AsEnumerable() _
                        .GroupBy(Function(row) _
                        New With
                        {
                            Key .Donnerstag = row.Field(Of String)("Donnerstag")
                       }
                   )

        Dim uniqueMenusFreitag = dtBestellungen.AsEnumerable() _
                        .GroupBy(Function(row) _
                        New With
                        {
                            Key .Freitag = row.Field(Of String)("Freitag")
                       }
                   )



        Dim resultMontag, resultDienstag, resultMittwoch, resultDonnerstag, resultFreitag As String


        For Each el In uniqueMenusMontag
            resultMontag &= IIf(el.Key.Montag <> "", String.Format("{1}x {0}, " & vbNewLine, el.Key.Montag, el.Count()), "")
        Next

        For Each el In uniqueMenusDienstag
            resultDienstag &= IIf(el.Key.Dienstag <> "", String.Format("{1}x {0}, " & vbNewLine, el.Key.Dienstag, el.Count()), "")
        Next

        For Each el In uniqueMenusMittwoch
            resultMittwoch &= IIf(el.Key.Mittwoch <> "", String.Format("{1}x {0}, " & vbNewLine, el.Key.Mittwoch, el.Count()), "")
        Next

        For Each el In uniqueMenusDonnerstag
            resultDonnerstag &= IIf(el.Key.Donnerstag <> "", String.Format("{1}x {0}, " & vbNewLine, el.Key.Donnerstag, el.Count()), "")
        Next
        For Each el In uniqueMenusFreitag
            resultFreitag &= IIf(el.Key.Freitag <> "", String.Format("{1}x {0}, " & vbNewLine, el.Key.Freitag, el.Count()), "")
        Next

        If exportToExcel AndAlso cbxMenudrucken.Checked Then

            Dim displayView = New DataView(dtBestellungen, "eb_MenuID is not null", "eb_MenuID", DataViewRowState.CurrentRows)
            Dim distinctDT_CSV As DataTable = displayView.ToTable(True, "eb_MenuID")
            Dim dtMenu As DataTable

            If distinctDT_CSV.Rows.Count > 0 Then

                Dim SQLMenu As String = "SELECT MenuEssenMo, MenuEssenDi, MenuEssenMi, MenuEssenDo, MenuEssenFr FROM [tblEBMenu] WHERE menuID='" & distinctDT_CSV.Rows(0).Item("eb_MenuID") & "'"
                dtMenu = SQL.loadDgvBySql(SQLMenu, "AVISO", 100, True)

                If dtMenu.Rows.Count = 1 Then

                    Dim menuRow As DataRow = dtBestellungen.NewRow
                    menuRow("ID") = "0"
                    menuRow("KW") = "-"
                    menuRow("Name") = "MENU"
                    menuRow("Gebaeude") = "-"
                    menuRow("Abteilung") = "-"
                    menuRow("Anmerkung") = DBNull.Value
                    menuRow("Datum") = DBNull.Value
                    menuRow("Storniert") = DBNull.Value
                    menuRow("Firma") = DBNull.Value
                    menuRow("Montag") = setLineBreaks(dtMenu.Rows(0).Item("MenuEssenMo"))
                    menuRow("Dienstag") = setLineBreaks(dtMenu.Rows(0).Item("MenuEssenDi"))
                    menuRow("Mittwoch") = setLineBreaks(dtMenu.Rows(0).Item("MenuEssenMi"))
                    menuRow("Donnerstag") = setLineBreaks(dtMenu.Rows(0).Item("MenuEssenDo"))
                    menuRow("Freitag") = setLineBreaks(dtMenu.Rows(0).Item("MenuEssenFr"))
                    menuRow("eb_MenuID") = ""
                    dtBestellungen.Rows.InsertAt(menuRow, 0)
                End If
            End If


        End If

        Dim R As DataRow = dtBestellungen.NewRow
        R("ID") = "0"
        R("KW") = "-"
        R("Name") = "SUMME"
        R("Gebaeude") = "-"
        R("Abteilung") = "-"
        R("Anmerkung") = DBNull.Value
        R("Datum") = DBNull.Value
        R("Storniert") = DBNull.Value
        R("Firma") = DBNull.Value
        R("Montag") = String.Join(" ", resultMontag)
        R("Dienstag") = String.Join(" ", resultDienstag)
        R("Mittwoch") = String.Join(" ", resultMittwoch)
        R("Donnerstag") = String.Join(" ", resultDonnerstag)
        R("Freitag") = String.Join(" ", resultFreitag)
        R("eb_MenuID") = ""
        dtBestellungen.Rows.Add(R)



        If exportToExcel Then

            dtBestellungen.Columns.Remove("ID")
            dtBestellungen.Columns.Remove("Datum")
            dtBestellungen.Columns.Remove("Storniert")
            dtBestellungen.Columns.Remove("Gebaeude")
            dtBestellungen.Columns.Remove("Abteilung")

        End If

        dtBestellungen.Columns.Remove("eb_MenuID")

        Return dtBestellungen

    End Function

    Private Sub btnNew_Click(sender As Object, e As EventArgs) Handles btnNew.Click


        Using UserControl1 As UsrCntlessensbestellungen = New UsrCntlessensbestellungen()
            Using tmpForm As Form = New Form()
                tmpForm.Width = UserControl1.Width
                tmpForm.Height = UserControl1.Height + 60
                tmpForm.Text = "NEUE BESTELLUNG"
                tmpForm.StartPosition = tmpForm.StartPosition.CenterParent
                tmpForm.Controls.Add(UserControl1)
                If tmpForm.ShowDialog() = DialogResult.OK Then
                    dgvBestellungen.GetOrder()
                    loadBestellungen()
                    dgvBestellungen.SetOrder()
                End If

            End Using
        End Using


    End Sub

    Private Sub dgvBestellungen_SelectionChanged(sender As Object, e As EventArgs) Handles dgvBestellungen.SelectionChanged
        lblWarning.Text = ""

        Dim countSumme As Double = 0

        If dgvBestellungen.SelectedRows.Count > 0 Then

            For i As Integer = 0 To dgvBestellungen.SelectedRows.Count - 1
                countSumme += CDbl(dgvBestellungen.SelectedRows(i).Cells("eb_preis").Value)

            Next

        End If

        txtMarkierteDS._value = countSumme.ToString
    End Sub




    'Private Sub txtBestelllimit_KeyDown(sender As Object, e As KeyEventArgs) Handles txtBestelllimit.KeyDown

    '    If e.KeyCode = Keys.Enter Then

    '        If IsNumeric(txtBestelllimit.Text) And txtBestelllimit.Text > 0 Then
    '            SQL.doSQL("UPDATE tblEBMenu SET MenuBestellungBisTageVorher='" & txtBestelllimit.Text & "' WHERE  MenuDateVon = '" & dt.Rows(0).Item("MenuDateVon").ToString() & "'", "AVISO")
    '            e.Handled = True
    '        End If

    '    End If

    'End Sub

    Private Sub txtBestelllimit_ValueChanged() Handles txtBestelllimit.TextChanged
        If cbKW._value Is Nothing Or cbKW._value = "" Then
            txtBestelllimit.Enabled = False
            btnBestelllimit.Enabled = False
            Exit Sub
        End If

        If txtBestelllimit.Text = "" Then
            btnBestelllimit.Enabled = False
            Exit Sub
        End If

        If dt.Rows.Count > 0 AndAlso IsNumeric(txtBestelllimit.Text) Then

            calcBestellLimit()
            If CDate(dt.Rows(0).Item("MenuDateVon")).ToString("dd.MM.yyyy") < Today Then

                txtBestelllimit.Enabled = False
                btnBestelllimit.Enabled = False
            Else
                txtBestelllimit.Enabled = True
                btnBestelllimit.Enabled = True
            End If
        End If


    End Sub

    Private Sub btnBestelllimit_Click(sender As Object, e As EventArgs) Handles btnBestelllimit.Click
        If IsNumeric(txtBestelllimit.Text) And txtBestelllimit.Text > 0 Then
            SQL.doSQL("UPDATE tblEBMenu SET MenuBestellungBisTageVorher='" & txtBestelllimit.Text & "' WHERE  MenuDateVon = '" & dt.Rows(0).Item("MenuDateVon").ToString() & "'", "AVISO")
            btnBestelllimit.Enabled = False
            calcBestellLimit()
        End If
    End Sub

    Private Sub calcBestellLimit()
        Dim startMenu = Date.Parse(dt.Rows(0).Item("MenuDateVon"))
        Dim newTime As New TimeSpan(14, 30, 0)
        Dim tageBisBestellende = txtBestelllimit.Text * -1

        Dim timeToOrderLimit = startMenu.AddDays(tageBisBestellende) + newTime
        lblBestellungBis.Text = "Bestellung möglich bis: " & timeToOrderLimit.ToShortDateString & " - " & timeToOrderLimit.ToShortTimeString

    End Sub

    Private Sub ExcelToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles ExcelToolStripMenuItem.Click
        Me.Cursor =
            Cursors.WaitCursor
        Try
            If dgvBestellungen.SelectedRows.Count = 0 Then
                lblWarning.Text = "keine Bestellungen markiert!"
                Me.Cursor = Cursors.Default
                Exit Sub
            End If



            Dim dtSource As DataTable
            dtSource = CType(dgvBestellungen.DataSource, DataTable)
            Dim dt = dtSource.Clone()

            For Each row As DataGridViewRow In dgvBestellungen.SelectedRows

                dt.ImportRow(dtSource.Rows(row.Index))

            Next

            dt.DefaultView.Sort = "eb_mitid ASC, eb_kw ASC"
            dt = dt.DefaultView.ToTable

            Dim drFirst = dt.NewRow
            drFirst.Item("eb_mitname") = "Bestellungen von " & txtBestellDat.Text & " bis " & txtBestellDatBis.Text
            drFirst.Item("eb_mitId") = 0
            drFirst.Item("eb_kw") = " "
            drFirst.Item("eb_gebaeude") = " "
            drFirst.Item("eb_abteilung") = " "
            drFirst.Item("eb_preis") = 0
            drFirst.Item("eb_firma") = " "

            dt.Rows.InsertAt(drFirst, 0)

            Dim drLast = dt.NewRow
            drLast.Item("eb_mitname") = "Gesamtsumme: "
            drLast.Item("eb_mitId") = 0
            drLast.Item("eb_kw") = " "
            drLast.Item("eb_gebaeude") = " "
            drLast.Item("eb_abteilung") = " "
            drLast.Item("eb_preis") = txtMarkierteDS.Text.Replace("€", "")
            drLast.Item("eb_firma") = " "
            dt.Rows.InsertAt(drLast, dt.Rows.Count)

            dt.Columns.Remove("eb_mitid")

            SDL.cProgramFunctions.genExcelFromDT_NEW(dt)

            Me.Cursor = Cursors.Default
        Catch ex As Exception
            MsgBox(ex.Message)
        End Try
    End Sub

    Private Sub setMDM()

        If cAllgemein.MITARBEITER.mit_abteilung = "MDM" Then 'Verag360 darf nur seine Bestellungen sehen!
            cboAbteilung.changeItem("MDM")

            cboAbteilung.Enabled = False

            cboGebaeude.changeItem("Maut")
            cbxMailGebäude.changeItem("Maut")
            cboGebaeude.Enabled = False
            cbxMailGebäude.Enabled = False

        Else

            cboAbteilung.changeItem("")
            cboAbteilung.Enabled = True

            cboGebaeude.changeItem("")
            cboGebaeude.Enabled = True
            cbxMailGebäude.Enabled = True
        End If


    End Sub


    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        If txtarchivieren.Text <> "" AndAlso IsNumeric(txtarchivieren.Text) AndAlso txtarchivieren.TextLength = 4 Then

            Try
                Dim year = CInt(txtarchivieren.Text)
                Dim bottomYear = 2022
                Dim currentYear = CInt(DateTime.Now().Year)
                If Not (2022 <= year AndAlso year < currentYear) Then
                    MsgBox("Es können nur Bestellungen zwischen " & bottomYear & " und " & currentYear - 1 & " archiviert werden!")
                Else
                    If vbYes = MsgBox("Möchten Sie alle Bestellungen aus dem Jahr " & year & " archivieren?" & vbNewLine & "Die Bestellungen aus diesem Jahr werden dann ausgeblendet!", vbYesNoCancel) Then
                        If SQL.doSQL("UPDATE [tblEssensbestellungen] SET eb_archiviert=1 WHERE Year(eb_datum)  = '" & year & "'", "AVISO") Then
                            MsgBox("Archivierung erfolgreich durchgeführt!")
                            txtarchivieren.Text = ""
                            loadBestellungen()
                        End If
                    End If
                End If



            Catch ex As Exception
                VERAG_PROG_ALLGEMEIN.cErrorHandler.ERR(ex.Message, ex.StackTrace, System.Reflection.MethodInfo.GetCurrentMethod.Name)
            End Try

        End If
    End Sub

    Private Sub txtarchivieren_TextChanged(sender As Object, e As EventArgs) Handles txtarchivieren.TextChanged
        If txtarchivieren.Text <> "" AndAlso IsNumeric(txtarchivieren.Text) AndAlso txtarchivieren.TextLength = 4 Then
            Button3.Enabled = True
        End If
    End Sub



    'Private Sub cbxCurrenyear_CheckedChanged(sender As Object, e As EventArgs) Handles cbxCurrenyear.CheckedChanged
    '    changeYear()
    'End Sub

    'Private Sub changeYear()

    '    Dim sqlwhere = "WHERE "
    '    sqlwhere &= IIf(cbxCurrenyear.Checked, "Year(MenuDateVon) = Year(getdate()) and MenuDateVon > GETDATE()", "MenuDateVon > GETDATE()")
    '    cbKW.fillWithSQL("SELECT DISTINCT(eb_kw) FROM [tblEssensbestellungen]  UNION SELECT (REPLACE(MenuTitel,'Wochenkarte ','')) + ' - ' +  Convert(varchar, Year(MenuDateVon)) as kwDateNew FROM [tblEBMenu] " & sqlwhere & " ORDER BY eb_kw desc", False, "AVISO", True)


    '    Dim sqlwhere2 = "WHERE "
    '    sqlwhere2 &= IIf(cbxCurrenyear.Checked, "Year([eb_datum]) = Year(getdate()) and [eb_datum] <= GETDATE()", "[eb_datum] <= GETDATE()")
    '    cbxMailKW.fillWithSQL("SELECT DISTINCT(eb_kw) FROM [tblEssensbestellungen] " & sqlwhere2 & " ORDER BY eb_kw desc", False, "AVISO", True)


    'End Sub

    Private Function setLineBreaks(s As String) As String

        s.Trim()
        Dim startIndex = 0
        Dim EndINdex = 19
        For index As Integer = 20 * (s.Length \ 19) To 0 Step -20

            s = ReplaceFirst(s, " ", vbNewLine, startIndex + 5, 19)
            startIndex = startIndex + 19

        Next

        Return s

    End Function

    Private Function ReplaceFirst(text As String, search As String, replace As String, startIndex As Integer, EndIndex As Integer) As String

        If startIndex + EndIndex > (text.Length - 1) Then Return text

        Dim pos As Integer = text.IndexOf(search, startIndex, IIf(startIndex + EndIndex > text.Length - 1, text.Length - startIndex - 1, EndIndex))
        If (pos < 0) Then Return text

        Return text.Substring(0, pos) + replace + text.Substring(pos + search.Length)

    End Function


End Class