Imports System.ComponentModel
Imports System.Net
Imports System.Text
Imports Mysqlx.XDevAPI.CRUD
Imports VERAG_PROG_ALLGEMEIN



Public Class usrCntlMitarbeiter


    Dim ConnStr As String
    Private UID As New cMitarbeiter
    Private cOptionenDAL As New cOptionenDAL
    Private Grid_aktiv As Boolean = False
    Private Anzahl As Integer
    Private locZeilen As Integer = -1
    Public mid As Integer = -1
    Dim FUNC = New cProgramFunctions
    Dim dt As New DataTable()

    Private Sub uctrlMitarbeiter_Load(sender As Object, e As EventArgs) Handles MyBase.Load
        ConnStr = frmMain.ConnStr

        Try
            '  Me.Size = My.Settings.frmMainSize
            ' Me.Location = My.Settings.frmMainPosition
        Catch ex As Exception
        Catch ex As Exception
            'nix tun - Standardgröße wird somit automatisch gesetzt
        End Try

        Grid_aktiv = True
        Tabelle_anzeigen()
        txtSuche.Focus()
    End Sub

    Public Sub Tabelle_anzeigen()

        btnUEZ_ausz.Visible = False
        lblAktiv.Text = ""

        If TabControl1.SelectedIndex = 0 Then
            showVERAGATILLA("VERAG")
        ElseIf TabControl1.SelectedIndex = 1 Then
            showVERAGATILLA("ATILLA")
        ElseIf TabControl1.SelectedIndex = 2 Then
            showVERAGATILLA("IMEX")
        ElseIf TabControl1.SelectedIndex = 3 Then
            showVERAGATILLA("UNISPED")
        ElseIf TabControl1.SelectedIndex = 4 Then
            showVERAGATILLA("AMBAR")
        ElseIf TabControl1.SelectedIndex = 5 Then
            showVERAGATILLA("FRONTOFFICE")
        ElseIf TabControl1.SelectedIndex = 6 Then
            showVERAGATILLA("VERIMEX")
        ElseIf TabControl1.SelectedIndex = 7 Then
            showVERAGATILLA("DURMAZ")
        ElseIf TabControl1.SelectedIndex = 8 Then
            btnUEZ_ausz.Visible = True
            If dgvTimasNew IsNot Nothing Then
                showTIMAS(False)
            End If
        End If

    End Sub

    Public Sub showVERAGATILLA(firma)
        'Paint wieder reaktivieren
        locZeilen = -1
        If Not Grid_aktiv Then Exit Sub



        Dim sql As String = "SELECT mit_id,mit_username,mit_vname, mit_nname ,mit_niederlassung,mit_abteilung,mit_email,cast (case when mit_timasId is null then 0 else 1 end as bit) mit_ze, cast (case when isnull([mit_DAKOSY_SB],'')<> '' and isnull([mit_DAKOSY_SBFull],'')<>'' then 1 else 0 end as bit) mit_DAKOSY, mit_durchwahl,mit_gekuendigt, isnull(mit_foto_DocId,'') as mit_foto_DocId  FROM tblMitarbeiter WHERE (mit_firma='" & firma & "' OR (mit_firma='ALL' AND mit_FirmaHaupt='" & firma & "' )) "

        If txtSuche.Text <> "" Then
            sql &= " AND (mit_username LIKE '%" & txtSuche.Text & "%' OR mit_nname LIKE '%" & txtSuche.Text & "%' OR mit_vname LIKE '%" & txtSuche.Text & "%') "
        End If

        If cbx.CheckState <> CheckState.Indeterminate Then
            sql &= " AND mit_gekuendigt=" & IIf(cbx.Checked, 1, 0)
        End If

        If cbxZE.CheckState <> CheckState.Indeterminate Then
            sql &= IIf(cbxZE.Checked, " AND mit_timasId is not null", " AND mit_timasId is null")
        End If

        If cbxDakosy.CheckState <> CheckState.Indeterminate Then
            sql &= IIf(cbxDakosy.Checked, " AND (isnull([mit_DAKOSY_SB],'')<> '' AND isnull([mit_DAKOSY_SBFull],'')<>'')", " AND ((isnull([mit_DAKOSY_SB],'')= '' OR isnull([mit_DAKOSY_SBFull],'')=''))")
        End If

        If firma = "VERAG" Then

            ' dgvVERAG.DataSource = UID.AnzeigeTabelleFirma(sql)

            c.SET_SQL(sql, "ADMIN")
            c.LOAD()
            'Tabelle Kommt/Geht bereinigen
            If c.RowCount = 0 Then
                c.DataSource = Nothing
            Else
                sortDGV(c)
                'Eintraege_festlegen()
                'AL: Sortierung nach Ausfahrt (Zeit)
                c.Sort(c.Columns(3), ListSortDirection.Ascending)
            End If
        ElseIf firma = "ATILLA" Then
            ' dgvATILLA.DataSource = UID.AnzeigeTabelleFirma(sql)

            dgvATILLA.SET_SQL(sql, "ADMIN")
            dgvATILLA.LOAD()

            'Tabelle Kommt/Geht bereinigen
            If dgvATILLA.RowCount = 0 Then
                dgvATILLA.DataSource = Nothing
            Else
                sortDGV(dgvATILLA)
                'Eintraege_festlegen()
                'AL: Sortierung nach Ausfahrt (Zeit)
                dgvATILLA.Sort(dgvATILLA.Columns(3), ListSortDirection.Ascending)
            End If
        ElseIf firma = "IMEX" Then
            ' dgvATILLA.DataSource = UID.AnzeigeTabelleFirma(sql)

            dgvIMEX.SET_SQL(sql, "ADMIN")
            dgvIMEX.LOAD()

            'Tabelle Kommt/Geht bereinigen
            If dgvIMEX.RowCount = 0 Then
                dgvIMEX.DataSource = Nothing
            Else
                sortDGV(dgvIMEX)
                'Eintraege_festlegen()
                'AL: Sortierung nach Ausfahrt (Zeit)
                dgvIMEX.Sort(dgvIMEX.Columns(3), ListSortDirection.Ascending)
            End If
        ElseIf firma = "UNISPED" Then
            ' dgvATILLA.DataSource = UID.AnzeigeTabelleFirma(sql)

            dgvUNISPED.SET_SQL(sql, "ADMIN")
            dgvUNISPED.LOAD()

            'Tabelle Kommt/Geht bereinigen
            If dgvUNISPED.RowCount = 0 Then
                dgvUNISPED.DataSource = Nothing
            Else
                sortDGV(dgvUNISPED)
                'Eintraege_festlegen()
                'AL: Sortierung nach Ausfahrt (Zeit)
                dgvUNISPED.Sort(dgvUNISPED.Columns(3), ListSortDirection.Ascending)
            End If
        ElseIf firma = "AMBAR" Then
            ' dgvATILLA.DataSource = UID.AnzeigeTabelleFirma(sql)

            dgvAMBAR.SET_SQL(sql, "ADMIN")
            dgvAMBAR.LOAD()

            'Tabelle Kommt/Geht bereinigen
            If dgvAMBAR.RowCount = 0 Then
                dgvAMBAR.DataSource = Nothing
            Else
                sortDGV(dgvAMBAR)
                'Eintraege_festlegen()
                'AL: Sortierung nach Ausfahrt (Zeit)
                dgvAMBAR.Sort(dgvAMBAR.Columns(3), ListSortDirection.Ascending)
            End If

        ElseIf firma = "FRONTOFFICE" Then
            ' dgvATILLA.DataSource = UID.AnzeigeTabelleFirma(sql)

            dgvFRONTOFFICE.SET_SQL(sql, "ADMIN")
            dgvFRONTOFFICE.LOAD()

            'Tabelle Kommt/Geht bereinigen
            If dgvFRONTOFFICE.RowCount = 0 Then
                dgvFRONTOFFICE.DataSource = Nothing
            Else
                sortDGV(dgvFRONTOFFICE)
                'Eintraege_festlegen()
                'AL: Sortierung nach Ausfahrt (Zeit)
                dgvFRONTOFFICE.Sort(dgvFRONTOFFICE.Columns(3), ListSortDirection.Ascending)

            End If


        ElseIf firma = "VERIMEX" Then
            ' dgvATILLA.DataSource = UID.AnzeigeTabelleFirma(sql)

            dgvVERIMEX.SET_SQL(sql, "ADMIN")
            dgvVERIMEX.LOAD()

            'Tabelle Kommt/Geht bereinigen
            If dgvVERIMEX.RowCount = 0 Then
                dgvVERIMEX.DataSource = Nothing
            Else
                sortDGV(dgvVERIMEX)
                'Eintraege_festlegen()
                'AL: Sortierung nach Ausfahrt (Zeit)
                dgvVERIMEX.Sort(dgvVERIMEX.Columns(3), ListSortDirection.Ascending)

            End If
        ElseIf firma = "DURMAZ" Then
            ' dgvATILLA.DataSource = UID.AnzeigeTabelleFirma(sql)

            dgvDURMAZ.SET_SQL(sql, "ADMIN")
            dgvDURMAZ.LOAD()

            'Tabelle Kommt/Geht bereinigen
            If dgvDURMAZ.RowCount = 0 Then
                dgvDURMAZ.DataSource = Nothing
            Else
                sortDGV(dgvDURMAZ)
                'Eintraege_festlegen()
                'AL: Sortierung nach Ausfahrt (Zeit)
                dgvDURMAZ.Sort(dgvDURMAZ.Columns(3), ListSortDirection.Ascending)

            End If
        End If

    End Sub



    Public Sub showTIMAS(refresh As Boolean)
        locZeilen = -1
        If Not Grid_aktiv Then Exit Sub

        If dt.Columns.Count > 0 And Not refresh Then

            If txtSuche.Text <> "" Then
                dt.DefaultView.RowFilter = "Vorname like '%" & txtSuche.Text & "%'  or Nachname like '%" & txtSuche.Text & "%' or 'Personal-Nr (Lohn)' like '%" & txtSuche.Text & "%'  or Info like '%" & txtSuche.Text & "%'"
            Else
                dt.DefaultView.RowFilter = Nothing
            End If

            dgvTimasNew.DataSource = dt

        Else
            Dim timas As New cTimasAPI("timas")
            timas.getEmployeeList(dt)

            Dim dt_onlyActive As New DataTable
            dt_onlyActive = dt.Select("[Ausweis-Nr] <> 0 and Vorname <> '' and Nachname <> ''").CopyToDataTable
            dgvTimasNew.DataSource = dt_onlyActive
            lblAktiv.Text = "AKTIV: " & dt_onlyActive.Rows.Count & "/" & dt.Rows.Count
            ' MsgBox("ALLE:" & dt.Rows.Count & vbNewLine & "AKIVE:" & dt_onlyActive.Rows.Count)

        End If
        With dgvTimasNew

            .RowTemplate.Height = 20
            .RowTemplate.DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopLeft
            .AllowUserToAddRows = False
            .AllowUserToDeleteRows = False
            .AllowUserToOrderColumns = False
            .AllowUserToResizeColumns = False
            .AllowUserToResizeRows = False
            .RowTemplate.ReadOnly = True
            .RowHeadersVisible = False
            .SelectionMode = DataGridViewSelectionMode.FullRowSelect
            .AllowUserToOrderColumns = True
            If .ColumnCount > 5 Then .Columns(6).AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill
        End With


    End Sub


    Private Sub sortDGV(dgv As DataGridView)
        With dgv
            .RowTemplate.Height = 20
            .RowTemplate.DefaultCellStyle.Alignment = DataGridViewContentAlignment.TopLeft
            .AllowUserToAddRows = False
            .AllowUserToDeleteRows = False
            .AllowUserToOrderColumns = False
            .AllowUserToResizeColumns = False
            .AllowUserToResizeRows = False
            .RowTemplate.ReadOnly = True
            .RowHeadersVisible = False
            .SelectionMode = DataGridViewSelectionMode.FullRowSelect

            .AllowUserToOrderColumns = True

            .Columns("mit_id").Visible = False     'ID nicht anzeigen

            .Columns("mit_username").Width = 150
            .Columns("mit_username").HeaderText = "Username"
            .Columns("mit_username").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter

            .Columns("mit_vname").Width = 100
            .Columns("mit_vname").HeaderText = "Vorname"

            .Columns("mit_nname").Width = 130
            .Columns("mit_nname").HeaderText = "Nachname"

            .Columns("mit_niederlassung").Width = 85
            .Columns("mit_niederlassung").HeaderText = "Niederlassung"

            .Columns("mit_abteilung").Width = 85
            .Columns("mit_abteilung").HeaderText = "Abteilung"

            .Columns("mit_email").Width = 120
            .Columns("mit_email").HeaderText = "Email"

            .Columns("mit_ze").Width = 50
            .Columns("mit_ze").HeaderText = "Zeiterf."
            .Columns("mit_ze").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter


            .Columns("mit_durchwahl").Width = 120
            .Columns("mit_durchwahl").HeaderText = "TelefonNr."

            .Columns("mit_gekuendigt").Width = 70
            .Columns("mit_gekuendigt").HeaderText = "Gekünd."
            .Columns("mit_gekuendigt").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter

            .Columns("mit_DAKOSY").Width = 100
            .Columns("mit_DAKOSY").HeaderText = "DY-Zugang"
            .Columns("mit_DAKOSY").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight



            .Columns("mit_foto_DocId").Width = 70
            .Columns("mit_foto_DocId").HeaderText = "FotoID"



            '.AutoGenerateColumns = False


            '.Columns(9).Visible = False

        End With

    End Sub
    Private Sub Button3_Click(sender As Object, e As EventArgs) Handles Button3.Click
        Dim Firma = ""
        Select Case TabControl1.SelectedIndex
            Case 0 : Firma = "VERAG"
            Case 1 : Firma = "ATILLA"
            Case 2 : Firma = "IMEX"
            Case 3 : Firma = "UNISPED"
            Case 4 : Firma = "AMBAR"
            Case 5 : Firma = "FRONTOFFICE"
            Case 6 : Firma = "VERIMEX"
            Case 7 : Firma = "DURMAZ"
        End Select
        Dim frmMitarbDetails As New frmMitarbDetails(Firma)
        frmMitarbDetails.Show()
        AddHandler frmMitarbDetails.FormClosing, AddressOf handleClose
    End Sub

    Private Sub Button4_Click(sender As Object, e As EventArgs) Handles Button4.Click
        Dim frmMitarbDetails As New frmMitarbDetails
        frmMitarbDetails.mid = c.CurrentRow.Cells(0).Value
        frmMitarbDetails.Show()
        AddHandler frmMitarbDetails.FormClosing, AddressOf handleClose
    End Sub

    Private Sub Button5_Click(sender As Object, e As EventArgs) Handles Button5.Click
        If TabControl1.SelectedIndex = 0 Then
            Select Case MsgBox("Soll der Mitarbeiter '" & c.CurrentRow.Cells(1).Value & "' wirklich gelöscht werden?", vbQuestion Or vbYesNo Or vbDefaultButton2, "Löschen?")
                Case vbYes
                    UID.delData(Convert.ToInt32(c.CurrentRow.Cells(0).Value))
                    Tabelle_anzeigen()
                Case vbNo

            End Select
        ElseIf TabControl1.SelectedIndex = 1 Then
            Select Case MsgBox("Soll der Mitarbeiter '" & dgvATILLA.CurrentRow.Cells(1).Value & "' wirklich gelöscht werden?", vbQuestion Or vbYesNo Or vbDefaultButton2, "Löschen?")
                Case vbYes
                    UID.delData(Convert.ToInt32(dgvATILLA.CurrentRow.Cells(0).Value))
                    Tabelle_anzeigen()
                Case vbNo

            End Select
        ElseIf TabControl1.SelectedIndex = 2 Then
            Select Case MsgBox("Soll der Mitarbeiter '" & dgvIMEX.CurrentRow.Cells(1).Value & "' wirklich gelöscht werden?", vbQuestion Or vbYesNo Or vbDefaultButton2, "Löschen?")
                Case vbYes
                    UID.delData(Convert.ToInt32(dgvIMEX.CurrentRow.Cells(0).Value))
                    Tabelle_anzeigen()
                Case vbNo

            End Select
        ElseIf TabControl1.SelectedIndex = 3 Then
            Select Case MsgBox("Soll der Mitarbeiter '" & dgvUNISPED.CurrentRow.Cells(1).Value & "' wirklich gelöscht werden?", vbQuestion Or vbYesNo Or vbDefaultButton2, "Löschen?")
                Case vbYes
                    UID.delData(Convert.ToInt32(dgvUNISPED.CurrentRow.Cells(0).Value))
                    Tabelle_anzeigen()
                Case vbNo

            End Select
        ElseIf TabControl1.SelectedIndex = 4 Then
            Select Case MsgBox("Soll der Mitarbeiter '" & dgvAMBAR.CurrentRow.Cells(1).Value & "' wirklich gelöscht werden?", vbQuestion Or vbYesNo Or vbDefaultButton2, "Löschen?")
                Case vbYes
                    UID.delData(Convert.ToInt32(dgvAMBAR.CurrentRow.Cells(0).Value))
                    Tabelle_anzeigen()
                Case vbNo

            End Select

        ElseIf TabControl1.SelectedIndex = 5 Then
            Select Case MsgBox("Soll der Mitarbeiter '" & dgvFRONTOFFICE.CurrentRow.Cells(1).Value & "' wirklich gelöscht werden?", vbQuestion Or vbYesNo Or vbDefaultButton2, "Löschen?")
                Case vbYes
                    UID.delData(Convert.ToInt32(dgvFRONTOFFICE.CurrentRow.Cells(0).Value))
                    Tabelle_anzeigen()
                Case vbNo

            End Select
        ElseIf TabControl1.SelectedIndex = 6 Then
            Select Case MsgBox("Soll der Mitarbeiter '" & dgvVERIMEX.CurrentRow.Cells(1).Value & "' wirklich gelöscht werden?", vbQuestion Or vbYesNo Or vbDefaultButton2, "Löschen?")
                Case vbYes
                    UID.delData(Convert.ToInt32(dgvVERIMEX.CurrentRow.Cells(0).Value))
                    Tabelle_anzeigen()
                Case vbNo

            End Select
        ElseIf TabControl1.SelectedIndex = 7 Then
            Select Case MsgBox("Soll der Mitarbeiter '" & dgvDURMAZ.CurrentRow.Cells(1).Value & "' wirklich gelöscht werden?", vbQuestion Or vbYesNo Or vbDefaultButton2, "Löschen?")
                Case vbYes
                    UID.delData(Convert.ToInt32(dgvDURMAZ.CurrentRow.Cells(0).Value))
                    Tabelle_anzeigen()
                Case vbNo

            End Select
        End If

    End Sub

    Private Sub Button6_Click(sender As Object, e As EventArgs) Handles Button6.Click
        Dim l As IList(Of VERAG_PROG_ALLGEMEIN.cMitarbeiter)
        l = cOptionenDAL.getDataMitarb()
        frmPrintView.Show()
        frmPrintView.BefüllenMitarb(l)
    End Sub


    Private Sub handleClose()
        Tabelle_anzeigen()
        frmMain.BringToFront()
    End Sub



    Private Sub dgvIMEX_CellContentClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvIMEX.CellDoubleClick, dgvUNISPED.CellDoubleClick, dgvAMBAR.CellDoubleClick, c.CellDoubleClick, dgvATILLA.CellDoubleClick, dgvFRONTOFFICE.CellDoubleClick, dgvVERIMEX.CellDoubleClick, dgvDURMAZ.CellDoubleClick
        Me.Cursor = Cursors.Default
        Dim frmMitarbDetails As New frmMitarbDetails
        frmMitarbDetails.mid = sender.CurrentRow.Cells(0).Value
        frmMitarbDetails.Show(Me)
        sender.RELOAD()
        Me.Cursor = Cursors.Default
        ' AddHandler frmMitarbDetails.FormClosing, AddressOf handleClose
    End Sub

    Private Sub TabControl1_SelectedIndexChanged(sender As Object, e As EventArgs) Handles TabControl1.SelectedIndexChanged
        txtSuche.Focus()
        Tabelle_anzeigen()
    End Sub



    Private Sub txtSuche_KeyDown(sender As Object, e As KeyEventArgs) Handles txtSuche.KeyDown

        Dim dgv As DataGridView = Nothing

        Select Case TabControl1.SelectedIndex
            Case 0 : dgv = c
            Case 1 : dgv = dgvATILLA
            Case 2 : dgv = dgvIMEX
            Case 3 : dgv = dgvUNISPED
            Case 4 : dgv = dgvAMBAR
            Case 5 : dgv = dgvFRONTOFFICE
            Case 6 : dgv = dgvVERIMEX
            Case 7 : dgv = dgvDURMAZ
            Case 8 : dgv = dgvTimasNew
        End Select

        If e.KeyCode = Keys.Return Then
            If dgv.SelectedRows.Count > 0 Then
                dgvIMEX_CellContentClick(dgv, New DataGridViewCellEventArgs(0, dgv.SelectedRows(0).Index))
            End If

        End If
    End Sub

    Private Sub txtSuche_TextChanged(sender As Object, e As EventArgs) Handles txtSuche.TextChanged
        Tabelle_anzeigen()
    End Sub

    Private Sub cbx_CheckedChanged(sender As Object, e As EventArgs) Handles cbx.CheckStateChanged
        Tabelle_anzeigen()
    End Sub

    Private Sub UserKopierenToolStripMenuItem_Click(sender As Object, e As EventArgs) Handles UserKopierenToolStripMenuItem.Click, BerechtigungenSetzenToolStripMenuItem.Click

        Dim copyUserName As String = "UserKopierenToolStripMenuItem"
        Dim setPermissionsName As String = "BerechtigungenSetzenToolStripMenuItem"

        If TabControl1.SelectedIndex = 0 Then

            If c.SelectedRows.Count <> 1 Then Exit Sub

            Select Case sender.Name
                Case copyUserName
                    copyUser(c.CurrentRow.Cells(0).Value)
                Case setPermissionsName
                    Dim frm As New frmBenutzerBerGruppenKopieren(c.CurrentRow.Cells(0).Value)
                    frm.Show(Me)
            End Select



        ElseIf TabControl1.SelectedIndex = 1 Then
            If dgvATILLA.SelectedRows.Count <> 1 Then Exit Sub
            Select Case sender.Name
                Case copyUserName
                    copyUser(dgvATILLA.CurrentRow.Cells(0).Value)
                Case setPermissionsName
                    Dim frm As New frmBenutzerBerGruppenKopieren(dgvATILLA.CurrentRow.Cells(0).Value)
                    frm.Show(Me)
            End Select

        ElseIf TabControl1.SelectedIndex = 2 Then
            If dgvIMEX.SelectedRows.Count <> 1 Then Exit Sub
            Select Case sender.Name
                Case copyUserName
                    copyUser(dgvIMEX.CurrentRow.Cells(0).Value)
                Case setPermissionsName
                    Dim frm As New frmBenutzerBerGruppenKopieren(dgvIMEX.CurrentRow.Cells(0).Value)
                    frm.Show(Me)
            End Select
        ElseIf TabControl1.SelectedIndex = 3 Then

            If dgvUNISPED.SelectedRows.Count <> 1 Then Exit Sub
            Select Case sender.Name
                Case copyUserName
                    copyUser(dgvUNISPED.CurrentRow.Cells(0).Value)
                Case setPermissionsName
                    Dim frm As New frmBenutzerBerGruppenKopieren(dgvUNISPED.CurrentRow.Cells(0).Value)
                    frm.Show(Me)
            End Select

        ElseIf TabControl1.SelectedIndex = 4 Then

            If dgvAMBAR.SelectedRows.Count <> 1 Then Exit Sub
            Select Case sender.Name
                Case copyUserName
                    copyUser(dgvAMBAR.CurrentRow.Cells(0).Value)
                Case setPermissionsName
                    Dim frm As New frmBenutzerBerGruppenKopieren(dgvAMBAR.CurrentRow.Cells(0).Value)
                    frm.Show(Me)
            End Select

        ElseIf TabControl1.SelectedIndex = 5 Then

            If dgvFRONTOFFICE.SelectedRows.Count <> 1 Then Exit Sub
            Select Case sender.Name
                Case copyUserName
                    copyUser(dgvFRONTOFFICE.CurrentRow.Cells(0).Value)
                Case setPermissionsName
                    Dim frm As New frmBenutzerBerGruppenKopieren(dgvFRONTOFFICE.CurrentRow.Cells(0).Value)
                    frm.Show(Me)
            End Select

        ElseIf TabControl1.SelectedIndex = 6 Then

            If dgvVERIMEX.SelectedRows.Count <> 1 Then Exit Sub
            Select Case sender.Name
                Case copyUserName
                    copyUser(dgvVERIMEX.CurrentRow.Cells(0).Value)
                Case setPermissionsName
                    Dim frm As New frmBenutzerBerGruppenKopieren(dgvVERIMEX.CurrentRow.Cells(0).Value)
                    frm.Show(Me)
            End Select

        ElseIf TabControl1.SelectedIndex = 7 Then

            If dgvDURMAZ.SelectedRows.Count <> 1 Then Exit Sub
            Select Case sender.Name
                Case copyUserName
                    copyUser(dgvDURMAZ.CurrentRow.Cells(0).Value)
                Case setPermissionsName
                    Dim frm As New frmBenutzerBerGruppenKopieren(dgvDURMAZ.CurrentRow.Cells(0).Value)
                    frm.Show(Me)
            End Select

        End If
    End Sub

    Private Sub dgvVerag_CellMouseDown(ByVal sender As Object, ByVal e As DataGridViewCellMouseEventArgs) Handles c.CellMouseDown, dgvVERIMEX.CellMouseDown, dgvUNISPED.CellMouseDown, dgvIMEX.CellMouseDown, dgvFRONTOFFICE.CellMouseDown, dgvATILLA.CellMouseDown, dgvAMBAR.CellMouseDown, dgvDURMAZ.CellMouseDown

        If e.Button = Windows.Forms.MouseButtons.Right AndAlso e.RowIndex > -1 Then
            Dim rowClicked As DataGridView.HitTestInfo
            Select Case sender.name
                Case "dgvVERAG"
                    rowClicked = c.HitTest(e.X, e.Y)
                    c.ClearSelection()
                    Me.c.Rows(e.RowIndex).Selected = True

                Case "dgvVERIMEX"
                    rowClicked = dgvVERIMEX.HitTest(e.X, e.Y)
                    dgvVERIMEX.ClearSelection()
                    Me.dgvVERIMEX.Rows(e.RowIndex).Selected = True

                Case "dgvUNISPED"
                    rowClicked = dgvUNISPED.HitTest(e.X, e.Y)
                    dgvUNISPED.ClearSelection()
                    Me.dgvUNISPED.Rows(e.RowIndex).Selected = True

                Case "dgvIMEX"
                    rowClicked = dgvIMEX.HitTest(e.X, e.Y)
                    dgvIMEX.ClearSelection()
                    Me.dgvIMEX.Rows(e.RowIndex).Selected = True

                Case "dgvFRONTOFFICE"
                    rowClicked = dgvFRONTOFFICE.HitTest(e.X, e.Y)
                    dgvFRONTOFFICE.ClearSelection()
                    Me.dgvFRONTOFFICE.Rows(e.RowIndex).Selected = True

                Case "dgvATILLA"
                    rowClicked = dgvATILLA.HitTest(e.X, e.Y)
                    dgvATILLA.ClearSelection()
                    Me.dgvATILLA.Rows(e.RowIndex).Selected = True

                Case "dgvVERIMEX"

                    rowClicked = dgvVERIMEX.HitTest(e.X, e.Y)
                    dgvVERIMEX.ClearSelection()
                    Me.dgvVERIMEX.Rows(e.RowIndex).Selected = True

                Case "dgvDURMAZ"

                    rowClicked = dgvDURMAZ.HitTest(e.X, e.Y)
                    dgvDURMAZ.ClearSelection()
                    Me.dgvDURMAZ.Rows(e.RowIndex).Selected = True

            End Select

            ContextMenuStrip1.Show(MousePosition.X, MousePosition.Y)

        End If

    End Sub
    Private Sub copyUser(id As Integer)


        Me.Cursor = Cursors.WaitCursor
        Dim frmMitarbDetails As New frmMitarbDetails()
        frmMitarbDetails.mid = id
        frmMitarbDetails.Show(Me)
        frmMitarbDetails.isUpdate = False
        frmMitarbDetails.Label1.Text = "Mitarbeiter kopieren"

        frmMitarbDetails.txtVname.Text = "Kopie von " & frmMitarbDetails.txtVname.Text
        frmMitarbDetails.txtNname.Text = "Kopie von " & frmMitarbDetails.txtNname.Text
        frmMitarbDetails.Label48.Text = "00"

        'ZUordnungen zu ext. Prog entfernen
        frmMitarbDetails.txtPwd.Text = ""
        frmMitarbDetails.txtCSPW.Text = ""
        frmMitarbDetails.txtCSUser.Text = ""
        frmMitarbDetails.txtPwd.Text = ""
        'frmMitarbDetails.cboALIASDomain.changeItem("")
        frmMitarbDetails.cboALIASDomain2.changeItem("")
        frmMitarbDetails.cboPersonal.changeItem("")
        frmMitarbDetails.txtALIASUser.Text = ""
        frmMitarbDetails.txtALIASUser2.Text = ""
        frmMitarbDetails.txtDakosySB.Text = ""
        frmMitarbDetails.txtTelotecSB.Text = ""

        If frmMitarbDetails.mitarbeiter IsNot Nothing Then
            frmMitarbDetails.mitarbeiter.mit_EZOLL_SB = -1
            frmMitarbDetails.mitarbeiter.mit_ATLAS_SB = ""
        End If

        frmMitarbDetails.txtDyFullName.Text = ""
        Me.Cursor = Cursors.Default


    End Sub

    Private Sub copyToClipboardWIKI()
        Try
            Me.Cursor = Cursors.WaitCursor
            Dim SQL As New VERAG_PROG_ALLGEMEIN.SQL
            Dim sqlstr As String = "SELECT '|' + mit_vname + '|' + mit_nname + '|' + isnull(mit_niederlassung,'-') + '|' + isnull(mit_abteilung,'-') + '|' + isnull(mit_email,'-') + '|' + isnull(mit_durchwahl,'-') + '|' + CASE WHEN mit_firma='ALL' THEN mit_firmaHaupt ELSE mit_firma + '|'  END as Firma FROM tblMitarbeiter WHERE  mit_gekuendigt=0 AND [mit_TESTonly]=0 AND [mit_pseudoUser]=0 And isnull(mit_niederlassung,'')<>'' and  isnull(mit_abteilung,'')<>'' and isnull(mit_nname,'') <>'' And isnull(mit_vname,'') <>'' Order by mit_id"
            Dim sqlstrpic As String = "SELECT isnull(mit_foto_DocId,0) as MAfoto FROM tblMitarbeiter WHERE mit_gekuendigt=0 AND [mit_TESTonly]=0 AND [mit_pseudoUser]=0 And isnull(mit_niederlassung,'') <>'' and  isnull(mit_abteilung,'')<>'' and isnull(mit_nname,'') <>'' And isnull(mit_vname,'') <>'' Order by mit_id"
            Dim dt As DataTable = SQL.loadDgvBySql_Param(sqlstr, "ADMIN")
            Dim dt2 As DataTable = SQL.loadDgvBySql_Param(sqlstrpic, "ADMIN")

            dt2.Columns.Add("path", GetType(String))
            For Each row As DataRow In dt2.Rows

                Dim filename As String
                If row.Item("MAfoto") > 0 Then
                    Dim filePath = New StringBuilder()
                    Dim file = VERAG_PROG_ALLGEMEIN.cDATENSERVER.GET_PDFPath_BY_DocID(row(0))
                    Dim filenameFull = New IO.FileInfo(file).Name.ToLower
                    filePath.Append("|![")
                    filePath.Append(filenameFull)
                    filePath.Append("](/mitarbeiterfotos/")
                    filePath.Append(filenameFull)
                    filePath.Append(")")
                    filename = filePath.ToString
                Else
                    filename = "|-"
                End If
                row.Item("path") = filename
            Next

            Dim content = New StringBuilder()

            content.Append("|Foto|Name|Nachname|Niederlassung|Abteilung|EMail|Telefonnummer|Firma|" & vbNewLine)
            content.Append("|-|-|-|-|-|-|-|-|" & vbNewLine)


            For Each row As DataRow In dt.Rows
                Dim index = dt.Rows.IndexOf(row)
                content.Append(dt2.Rows(index).Item("path"))
                content.Append(row(0))
                content.Append(vbNewLine)
            Next
            content.Append("{.interactive-table}")

            Dim data As New DataObject()
            data.SetData(DataFormats.Text, content)
            Clipboard.SetDataObject(data)
            Me.Cursor = Cursors.Default
            MsgBox("Daten in Zwischenablage gespeichert")


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


    End Sub

    Private Sub mnuItem_Clicked(sender As Object, e As EventArgs)
        ContextMenuStrip1.Hide()
        Dim item As ToolStripMenuItem = TryCast(sender, ToolStripMenuItem)

        If item IsNot Nothing Then
            If item.Name = "uploadPuctureToWiki" Then
                uploadToWiki()

            ElseIf item.Name = "copyToClipboard" Then
                copyToClipboardWIKI()
            Else
                MsgBox("Funktion nicht implementiert!")
            End If

        End If

    End Sub



    Private Sub Button9_Click(sender As Object, e As EventArgs) Handles Button9.Click
        If Not ContextMenuStrip2.Items.ContainsKey("uploadPuctureToWiki") Then
            Dim uploadPictures = New ToolStripMenuItem() With {.Text = "Bilder ins WIKI hochladen", .Name = "uploadPuctureToWiki", .Font = New Font(Me.Font.FontFamily, Me.Font.Size)}
            ContextMenuStrip2.Items.Add(uploadPictures)
            AddHandler uploadPictures.Click, AddressOf mnuItem_Clicked
        End If


        If Not ContextMenuStrip2.Items.ContainsKey("copyToClipboard") Then
            Dim copyToClipboard = New ToolStripMenuItem() With {.Text = "In Zwischenablage kopieren", .Name = "copyToClipboard", .Font = New Font(Me.Font.FontFamily, Me.Font.Size)}
            AddHandler copyToClipboard.Click, AddressOf mnuItem_Clicked
            ContextMenuStrip2.Items.Add(copyToClipboard)
        End If



        ContextMenuStrip2.Show(Cursor.Position)
    End Sub


    Private Sub uploadToWiki()

        Me.Cursor = Cursors.WaitCursor
        Dim dgv As New DataGridView

        If TabControl1.SelectedIndex = 0 Then

            dgv = c

        ElseIf TabControl1.SelectedIndex = 1 Then

            dgv = dgvATILLA

        ElseIf TabControl1.SelectedIndex = 2 Then

            dgv = dgvIMEX

        ElseIf TabControl1.SelectedIndex = 3 Then

            dgv = dgvUNISPED

        ElseIf TabControl1.SelectedIndex = 4 Then

            dgv = dgvAMBAR

        ElseIf TabControl1.SelectedIndex = 5 Then

            dgv = dgvFRONTOFFICE

        ElseIf TabControl1.SelectedIndex = 6 Then

            dgv = dgvVERIMEX

        ElseIf TabControl1.SelectedIndex = 7 Then

            dgv = dgvDURMAZ

        End If

        Dim SQL As New SQL
        Dim API As New DataTable
        Dim apiSettingsloaded As Boolean = False
        Dim API_STRING

        API = SQL.loadDgvBySql("SELECT top(1) * FROM tblAPIEinstellungen WHERE api_program='WIKI' and api_productive ='" & IIf(VERAG_PROG_ALLGEMEIN.cAllgemein.TESTSYSTEM, "0", "1") & "'", "ADMIN")
        If API.Rows.Count = 0 Then
            MsgBox("keine gültigen API-Einstellungen für WIKI gefunden!")
        Else
            apiSettingsloaded = True
            API_STRING = API.Rows(0).Item("api_url")
        End If

        If apiSettingsloaded = False Then Exit Sub

        For Each row As DataGridViewRow In dgv.Rows
            If row.Cells("mit_foto_DocId").Value > 0 Then
                Dim file = VERAG_PROG_ALLGEMEIN.cDATENSERVER.GET_PDFPath_BY_DocID(row.Cells("mit_foto_DocId").Value)
                Dim succeess = uploadPictureToWIKI(API, 4, file) 'Folder 4 -> Mitarbeiterfotos
            End If

        Next
        Me.Cursor = Cursors.Default
        Try

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

    End Sub



    Private Function uploadPictureToWIKI(API As DataTable, folderIDx As Integer, image As String) As String
        Try

            VERAG_PROG_ALLGEMEIN.cChilkat_Helper.UnlockCilkat()

            Dim API_String = API.Rows(0).Item("api_url")

            Dim rest As New Chilkat.Rest
            Dim success As Boolean
            Dim failureDesc As String

            rest.VerboseLogging = True
            Dim bTls As Boolean = True
            Dim port As Integer = 443
            Dim bAutoReconnect As Boolean = True
            success = rest.Connect(API_String, port, bTls, bAutoReconnect)
            If (success <> True) Then
                Debug.WriteLine("ConnectFailReason: " & rest.ConnectFailReason)
                Debug.WriteLine(rest.LastErrorText)
                failureDesc = rest.LastErrorText
                Return failureDesc
            End If

            API_String &= "/u"

            rest.AddHeader("Authorization", "Bearer " & API.Rows(0).Item("api_token"))
            rest.AddHeader("Content-Type", "multipart/form-data")

            Dim filename = New IO.FileInfo(image).Name

            Dim fileStream As New Chilkat.Stream
            fileStream.SourceFile = image

            rest.PartSelector = "1"
            rest.AddHeader("Content-Disposition", "form-data; name=""mediaUpload""")
            rest.AddHeader("Content-Type", "text")
            Dim json As New Chilkat.JsonObject
            success = json.AddIntAt(-1, "folderId", folderIDx)
            Debug.WriteLine(json.Emit())
            success = rest.SetMultipartBodyString(json.Emit())

            rest.PartSelector = "2"
            rest.AddHeader("Content-Disposition", "form-data; name=""mediaUpload""; filename=""" & filename & """")
            rest.AddHeader("Content-Type", "image/jpeg")
            success = rest.SetMultipartBodyStream(fileStream)

            Dim responseBody As String = rest.FullRequestMultipart("POST", API_String)
            If (rest.LastMethodSuccess <> True) Then
                Debug.WriteLine(rest.LastErrorText)
                Return rest.LastErrorText
            End If

            If (rest.ResponseStatusCode <> 200) Then
                Debug.WriteLine(rest.ResponseHeader)
                Return rest.ResponseStatusCode & " " & rest.ResponseStatusText
            Else
                Debug.WriteLine("File uploaded")
                MsgBox("Bilder wurden hochgeladen")
            End If

            rest.ClearAllHeaders()
            rest.ClearAllParts()
            rest.PartSelector = ""




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


    Private Sub dgvTimasNew_CellDoubleClick(sender As Object, e As DataGridViewCellEventArgs) Handles dgvTimasNew.CellDoubleClick
        Me.Cursor = Cursors.WaitCursor
        'neue GUI für Änderungen im Timas
        Dim frmMitarbDetails As New frmMitarbTimas()

        frmMitarbDetails.mid = sender.CurrentRow.Cells(0).Value
        'frmMitarbDetails.Show(Me)
        If frmMitarbDetails.ShowDialog() = DialogResult.OK Then
            sender.RELOAD()
            showTIMAS(True)
            dgvTimasNew.Refresh()
        End If



        Me.Cursor = Cursors.Default
    End Sub

    Private Sub cbxZE_CheckStateChanged(sender As Object, e As EventArgs) Handles cbxZE.CheckStateChanged, cbxDakosy.CheckStateChanged
        Tabelle_anzeigen()
    End Sub

    Private Sub Button7_Click(sender As Object, e As EventArgs) Handles btnUEZ_ausz.Click

        If dgvTimasNew.Rows.Count = 0 Then Exit Sub

        Try


            Dim dt_Accounts As New DataTable
            dt_Accounts.Columns.Add("accountid", GetType(Integer))

            Dim ROW_ACC As DataRow = dt_Accounts.NewRow
            ROW_ACC("accountid") = "993" 'Auszahlungen ÜS!
            dt_Accounts.Rows.Add(ROW_ACC)

            'Dim ROW_ACC1 As DataRow = dt_Accounts.NewRow
            'ROW_ACC1("accountid") = "1598" 'Auszahlungen ÜS!
            'dt_Accounts.Rows.Add(ROW_ACC1)

            'Dim ROW_ACC2 As DataRow = dt_Accounts.NewRow
            'ROW_ACC2("accountid") = "1235" 'Auszahlungen ÜS!
            'dt_Accounts.Rows.Add(ROW_ACC2)


            Dim dt_Employee As New DataTable
            dt_Employee.Columns.Add("employeeId", GetType(Integer))
            dt_Employee.Columns.Add("Vorname", GetType(String))
            dt_Employee.Columns.Add("Nachname", GetType(String))

            Dim dt_result As New DataTable

            Dim dateStart As New Date("2025", "01", "01")
            Dim dateEnd = Today()

            For Each r As DataGridViewRow In dgvTimasNew.Rows
                Dim ROW As DataRow = dt_Employee.NewRow
                ROW("employeeId") = r.Cells("Id").Value
                ROW("Vorname") = r.Cells("Vorname").Value
                ROW("Nachname") = r.Cells("Nachname").Value
                dt_Employee.Rows.Add(ROW)
            Next



            Dim timas As New cTimasAPI("timas")
            timas.getTimeAccounts(dateStart, dateEnd, 0, dt_Accounts, dt_result, dt_Employee)

            If dt_result.Rows.Count > 0 Then


                Dim dt_falschAusbezahlt As New DataTable

                dt_falschAusbezahlt = dt_result.Select("multiplier = '-'", "date").CopyToDataTable

                If dt_falschAusbezahlt.Rows.Count = 0 Then
                    MsgBox("keine falsch ausbezahlten Überstunden vorhanden!" & vbNewLine & "Es wird nur geprüft, ob die ausbezahlten Überstunden NICHT negativ sind!")
                    Exit Sub
                Else

                    ' VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dt_falschAusbezahlt,,,,,,,, True)

                    Dim query = From fa In dt_falschAusbezahlt.AsEnumerable()
                                Join emp In dt_Employee.AsEnumerable() On fa.Field(Of Integer)("employeeId") Equals emp.Field(Of Integer)("employeeId")
                                Select result = fa.ItemArray.Concat({emp.Field(Of String)("Vorname"), emp.Field(Of String)("Nachname")}).ToArray()

                    ' Neue Tabelle erstellen (Struktur erweitern)
                    Dim dt_merged As New DataTable

                    ' Alte Spalten übernehmen
                    For Each col As DataColumn In dt_falschAusbezahlt.Columns
                        dt_merged.Columns.Add(col.ColumnName, col.DataType)
                    Next

                    ' Neue Spalten hinzufügen
                    dt_merged.Columns.Add("Vorname", GetType(String))
                    dt_merged.Columns.Add("Nachname", GetType(String))

                    ' Daten einfügen
                    For Each row In query
                        dt_merged.Rows.Add(row)
                    Next

                    If dt_merged.Rows.Count > 0 Then
                        VERAG_PROG_ALLGEMEIN.cProgramFunctions.genExcelFromDT_NEW(dt_merged,,, "falsch ausbezahlte Überstunden (ÜS sind negativ -> Erhöhen den Saldo)",,,,, True)
                    End If
                End If


            End If

        Catch ex As Exception

        End Try


    End Sub


End Class
