' Copyright (C) 2025  P4pillon.org
'
' This program is free software: you can redistribute it and/or modify
' it under the terms of the GNU Affero General Public License as
' published by the Free Software Foundation, either version 3 of the
' License, or (at your option) any later version.
'
' This program is distributed in the hope that it will be useful,
' but WITHOUT ANY WARRANTY; without even the implied warranty of
' MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
' GNU Affero General Public License for more details.
'
' You should have received a copy of the GNU Affero General Public License
' along with this program.  If not, see <https://www.gnu.org/licenses/>.
Imports System.IO
Imports System.Text

Public Class Inventaire

    Public Nom_Inventaire As String


    Private Function add_prod() As Boolean
        For r = 0 To Scan_DataGridView.Rows.Count - 1
            Try
                CInt(Scan_DataGridView.Item(Column_Quantité_inventaire.Index, r).Value).ToString()
            Catch ex As Exception
                MyMsg_Box.Presentation("Officine", "Quantité numérique entière", False, "", False, "", True, "OK")
                MyMsg_Box.ShowDialog()
                Return False
            End Try
        Next
        Dim déja_dans_tab As Boolean = False
        For r = 0 To Scan_DataGridView.Rows.Count - 1
            If ProduitsDataGridView.Item(DataGridViewTextBoxColumn1.Index, ProduitsDataGridView.CurrentRow.Index).Value = Scan_DataGridView.Item(Column_CIP.Index, r).Value And _
                ProduitsDataGridView.Item(DataGridViewTextBoxColumn2.Index, ProduitsDataGridView.CurrentRow.Index).Value = Scan_DataGridView.Item(Column_EAN13.Index, r).Value And _
                   ProduitsDataGridView.Item(DataGridViewTextBoxColumn3.Index, ProduitsDataGridView.CurrentRow.Index).Value = Scan_DataGridView.Item(Column_CAB.Index, r).Value And _
                   ProduitsDataGridView.Item(DataGridViewTextBoxColumn4.Index, ProduitsDataGridView.CurrentRow.Index).Value = Scan_DataGridView.Item(Column_produit.Index, r).Value Then
                déja_dans_tab = True
                Scan_DataGridView.Item(Column_Quantité_inventaire.Index, r).Value = Quantité_produit_TextBox.Text
                Scan_DataGridView.FirstDisplayedScrollingRowIndex = r
                Controle_quantité_inventaire_stock(r)
                Exit For
            End If
        Next
        If déja_dans_tab = False Then
            Scan_DataGridView.Rows.Add()
            Scan_DataGridView.Item(Column_CIP.Index, Scan_DataGridView.Rows.Count - 1).Value = ProduitsDataGridView.Item(DataGridViewTextBoxColumn1.Index, ProduitsDataGridView.CurrentRow.Index).Value
            Scan_DataGridView.Item(Column_EAN13.Index, Scan_DataGridView.Rows.Count - 1).Value = ProduitsDataGridView.Item(DataGridViewTextBoxColumn2.Index, ProduitsDataGridView.CurrentRow.Index).Value
            Scan_DataGridView.Item(Column_CAB.Index, Scan_DataGridView.Rows.Count - 1).Value = ProduitsDataGridView.Item(DataGridViewTextBoxColumn3.Index, ProduitsDataGridView.CurrentRow.Index).Value
            Scan_DataGridView.Item(Column_produit.Index, Scan_DataGridView.Rows.Count - 1).Value = ProduitsDataGridView.Item(DataGridViewTextBoxColumn4.Index, ProduitsDataGridView.CurrentRow.Index).Value
            Scan_DataGridView.Item(Column_Stock_avant_inventaire.Index, Scan_DataGridView.Rows.Count - 1).Value = ProduitsDataGridView.Item(StockDataGridViewTextBoxColumn.Index, ProduitsDataGridView.CurrentRow.Index).Value
            Scan_DataGridView.Item(Column_Quantité_inventaire.Index, Scan_DataGridView.Rows.Count - 1).Value = Quantité_produit_TextBox.Text
            Scan_DataGridView.FirstDisplayedScrollingRowIndex = Scan_DataGridView.RowCount - 1
            Scan_DataGridView.CurrentCell = Scan_DataGridView.Item(0, Scan_DataGridView.RowCount - 1)
            affiche_dus(Scan_DataGridView.RowCount - 1)
            Controle_quantité_inventaire_stock(Scan_DataGridView.RowCount - 1)
        End If


        Scan_produit_TextBox.Text = ""
        Quantité_produit_TextBox.Text = ""

        Return True
    End Function

    Private Sub affiche_dus(ByVal rowindex As Integer)
        Application.DoEvents()
        Dim code_prod As String = ""

        If Scan_DataGridView.Item(Column_EAN13.Index, rowindex).Value <> "" Then
            code_prod = Scan_DataGridView.Item(Column_EAN13.Index, rowindex).Value
        ElseIf Scan_DataGridView.Item(Column_CIP.Index, rowindex).Value <> "" Then
            code_prod = Scan_DataGridView.Item(Column_CIP.Index, rowindex).Value
        ElseIf Scan_DataGridView.Item(Column_CAB.Index, rowindex).Value <> "" Then
            code_prod = Scan_DataGridView.Item(Column_CAB.Index, rowindex).Value
        End If

        Dim dus = BDD.DusTableAdapter.GetDataBy_CIP_Soldé(code_prod, False)
        Dim du_qtt = 0
        For rr = 0 To dus.Rows.Count - 1
            du_qtt = du_qtt + dus(rr).Quantité_Du
        Next
        Scan_DataGridView.Item(Column_Du.Index, rowindex).Value = du_qtt

    End Sub

    Private Sub Controle_quantité_inventaire_stock(ByVal rowindex As Integer)
        If Val(Scan_DataGridView.Item(Column_Quantité_inventaire.Index, rowindex).Value) <> _
            Val(Scan_DataGridView.Item(Column_Stock_avant_inventaire.Index, rowindex).Value) + Val(Scan_DataGridView.Item(Column_Du.Index, rowindex).Value) Then
            Scan_DataGridView.Rows.Item(rowindex).DefaultCellStyle.ForeColor = Color.Red
            Scan_DataGridView.Rows.Item(rowindex).DefaultCellStyle.BackColor = Color.LightGray
            Scan_produit_TextBox.BackColor = Color.Red
            Scan_DataGridView.FirstDisplayedScrollingRowIndex = rowindex

        Else

            Scan_DataGridView.Rows.Item(rowindex).DefaultCellStyle.ForeColor = Color.Green
            Scan_DataGridView.Rows.Item(rowindex).DefaultCellStyle.BackColor = Color.White


        End If
    End Sub


    Private Sub Scan_produit_TextBox_KeyDown(sender As Object, e As KeyEventArgs) Handles Scan_produit_TextBox.KeyDown
        If e.KeyCode = Keys.Enter And Scan_produit_TextBox.Text <> "" Then
            Quantité_produit_TextBox.Focus()

        End If
    End Sub


    Private Sub Scan_produit_TextBox_Validated(sender As Object, e As EventArgs) Handles Scan_produit_TextBox.Validated
        Try
            If Mid(Scan_produit_TextBox.Text, 1, 1) = "$" Then
                Scan_produit_TextBox.Text = Mid(Scan_produit_TextBox.Text, 2)
            End If
        Catch ex As Exception

        End Try
        recherche_produit()
    End Sub
    Private Function recherche_produit() As Integer

        If Scan_produit_TextBox.Text = "" Then Return 0

        Dim is_datamatrix As Boolean = False
        Dim string_searched As String = Scan_produit_TextBox.Text
        Dim num_lot As String = "*"
        Dim date_peremption As Date
        Dim date_string = ""
        If Mid(string_searched, 1, 2) = "01" And Mid(string_searched, 17, 2) = "17" And Mid(string_searched, 25, 2) = "10" Then
            is_datamatrix = True
            num_lot = Mid(string_searched, 27)
            date_string = (Mid(string_searched, 23, 2) & "/" & Mid(string_searched, 21, 2) & "/" & "20" & Mid(string_searched, 19, 2))
        ElseIf Mid(string_searched, 1, 2) = "01" And Mid(string_searched, 17, 2) = "11" And Mid(string_searched, 25, 2) = "17" And Mid(string_searched, 33, 2) = "10" Then
            is_datamatrix = True
            num_lot = Mid(string_searched, 35)
            date_string = (Mid(string_searched, 31, 2) & "/" & Mid(string_searched, 29, 2) & "/" & "20" & Mid(string_searched, 27, 2))
        ElseIf Mid(string_searched, 1, 3) = "010" And string_searched.Length >= 16 Then
            string_searched = Mid(string_searched, 4, 13)
        End If
        If is_datamatrix = True Then

            While InStr(date_string, "00/") <> 0
                date_string = Replace(date_string, "00/", "01/")
            End While
            date_peremption = Convert.ToDateTime(date_string, Nothing)
            string_searched = Mid(string_searched, 4, 13)
            If date_peremption.Subtract(Now).Days < Val(warning_peremption_TextBox.Text) Then
                MyMsg_Box.Presentation("Officine", "DATE DE PEREMPTION" + Chr(10) + date_peremption.ToLongDateString, False, "", False, "", True, "OK")
                MyMsg_Box.ShowDialog()
            End If
        End If

        Dim x As Decimal = Me.ProduitsTableAdapter.selectcountproduit(string_searched, string_searched, string_searched, string_searched)
        Select Case x
            Case 1 '1 produit correspondant trouvé dans la base
                Me.ProduitsTableAdapter.selectproduit(Me.PharmaDataSet.Produits, string_searched, string_searched, string_searched, string_searched)
                Scan_produit_TextBox.BackColor = Color.LightGreen
                Return 1

            Case 0 'aucun produit correspondant trouvée dans la base
                Scan_produit_TextBox.Focus()
                Scan_produit_TextBox.SelectAll()
                Scan_produit_TextBox.BackColor = Color.Red
                Return 0

            Case Else 'Plusieurs CAB correspondant trouvés dans la base

                Me.ProduitsTableAdapter.selectproduit(Me.PharmaDataSet.Produits, string_searched, string_searched, string_searched, string_searched)
                Scan_produit_TextBox.BackColor = Color.Orange
                Return 2

        End Select

    End Function

    Private Sub Quantité_produit_TextBox_Enter(sender As Object, e As EventArgs) Handles Quantité_produit_TextBox.Enter
        If Quantité_produit_TextBox.Text = "" Then
            Quantité_produit_TextBox.Text = "1"
        End If

    End Sub



    Private Sub Quantité_produit_TextBox_KeyDown(sender As Object, e As KeyEventArgs) Handles Quantité_produit_TextBox.KeyDown
        If e.KeyCode = Keys.Enter Then

            Try
                CInt(Quantité_produit_TextBox.Text).ToString()
            Catch ex As Exception
                MyMsg_Box.Presentation("Officine", "Quantité numérique entière", False, "", False, "", True, "OK")
                MyMsg_Box.ShowDialog()
                Exit Sub
            End Try
            add_prod()



            Scan_produit_TextBox.Focus()

        End If



    End Sub

    Private Sub ProduitsDataGridView_CellClick(sender As Object, e As DataGridViewCellEventArgs) Handles ProduitsDataGridView.CellClick
        Quantité_produit_TextBox.Focus()
        Quantité_produit_TextBox.SelectAll()
    End Sub



    Private Sub ProduitsDataGridView_KeyDown(sender As Object, e As KeyEventArgs) Handles ProduitsDataGridView.KeyDown
        If e.KeyCode = Keys.Enter And Scan_produit_TextBox.Text <> "" Then
            Quantité_produit_TextBox.Focus()
        End If
    End Sub






    Private Sub Inventaire_Load(sender As Object, e As EventArgs) Handles Me.Load
        Me.Text = "Inventaire: " & Nom_Inventaire
    End Sub

    Private Sub LinkLabel1_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel1.LinkClicked
        For r = 0 To Scan_DataGridView.Rows.Count - 1
            Dim déja = BDD.InventaireTableAdapter.GetData_ligne(Nom_Inventaire, _
                                                          Scan_DataGridView.Item(Column_CIP.Index, r).Value, _
                                                          Scan_DataGridView.Item(Column_EAN13.Index, r).Value, _
                                                           Scan_DataGridView.Item(Column_CAB.Index, r).Value, _
                                                          Scan_DataGridView.Item(Column_produit.Index, r).Value)
            If déja.Rows.Count > 0 Then
                BDD.InventaireTableAdapter.Update_ligne(Now, Val(Scan_DataGridView.Item(Column_Quantité_inventaire.Index, r).Value) - Val(Scan_DataGridView.Item(Column_Du.Index, r).Value), _
                                                         current_User.ID, Nom_Inventaire, _
                                                        Scan_DataGridView.Item(Column_CIP.Index, r).Value, _
                                                          Scan_DataGridView.Item(Column_EAN13.Index, r).Value, _
                                                           Scan_DataGridView.Item(Column_CAB.Index, r).Value, _
                                                          Scan_DataGridView.Item(Column_produit.Index, r).Value)
            Else
                BDD.InventaireTableAdapter.Insert(Nom_Inventaire, Scan_DataGridView.Item(Column_CIP.Index, r).Value, _
                                                         Scan_DataGridView.Item(Column_EAN13.Index, r).Value, _
                                                          Scan_DataGridView.Item(Column_CAB.Index, r).Value, _
                                                         Scan_DataGridView.Item(Column_produit.Index, r).Value, Now,
                                                        Val(Scan_DataGridView.Item(Column_Quantité_inventaire.Index, r).Value) - Val(Scan_DataGridView.Item(Column_Du.Index, r).Value),
                                                        Val(Scan_DataGridView.Item(Column_Stock_avant_inventaire.Index, r).Value), current_User.ID)
            End If
            Dim cip As String = ""
            If Scan_DataGridView.Item(Column_EAN13.Index, r).Value <> "" Then
                cip = Scan_DataGridView.Item(Column_EAN13.Index, r).Value
            Else
                cip = Scan_DataGridView.Item(Column_CIP.Index, r).Value
            End If
            ProduitsTableAdapter.Set_Stock(CDec(Scan_DataGridView.Item(Column_Quantité_inventaire.Index, r).Value), cip, Scan_DataGridView.Item(Column_CAB.Index, r).Value, Scan_DataGridView.Item(Column_produit.Index, r).Value)
        Next
        Me.Dispose()

    End Sub

    Private Sub Scan_DataGridView_CellEndEdit(sender As Object, e As DataGridViewCellEventArgs) Handles Scan_DataGridView.CellEndEdit
        If e.ColumnIndex = Column_Quantité_inventaire.Index Then
            If Not IsNumeric(Scan_DataGridView.Item(e.ColumnIndex, e.RowIndex).Value) Then
                Scan_DataGridView.Item(e.ColumnIndex, e.RowIndex).Value = 0
                Scan_DataGridView.CurrentCell = Scan_DataGridView.Item(e.ColumnIndex, e.RowIndex)
                Scan_DataGridView.Focus()
                Scan_DataGridView.BeginEdit(True)
            End If
            Controle_quantité_inventaire_stock(e.RowIndex)
        End If
    End Sub




    Private Sub ProduitsDataGridView_SelectionChanged(sender As Object, e As EventArgs) Handles ProduitsDataGridView.SelectionChanged
        If ProduitsDataGridView.Rows.Count = 0 Then Exit Sub
        Dim déja = BDD.InventaireTableAdapter.GetData_ligne(Nom_Inventaire, _
                                                            ProduitsDataGridView.Item(DataGridViewTextBoxColumn1.Index, ProduitsDataGridView.CurrentRow.Index).Value, _
                                                           ProduitsDataGridView.Item(DataGridViewTextBoxColumn2.Index, ProduitsDataGridView.CurrentRow.Index).Value, _
                                                           ProduitsDataGridView.Item(DataGridViewTextBoxColumn3.Index, ProduitsDataGridView.CurrentRow.Index).Value, _
                                                           ProduitsDataGridView.Item(DataGridViewTextBoxColumn4.Index, ProduitsDataGridView.CurrentRow.Index).Value)
        If déja.Rows.Count > 0 Then
            Déja_inventorié_Label.Visible = True
        Else
            Déja_inventorié_Label.Visible = False
        End If
    End Sub





    Private Sub LinkLabel2_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel2.LinkClicked
        Dim Détails_inventaire_form As New Détails_inventaire
        Détails_inventaire_form.nom_inventaire = Nom_Inventaire
        Détails_inventaire_form.Visible = True
        Détails_inventaire_form.Afficher_prod_non_inventoriés()
        Détails_inventaire_form.Afficher_prod_inventoriés()
        Détails_inventaire_form.BringToFront()

    End Sub

    Private Sub LinkLabel3_LinkClicked(sender As Object, e As LinkLabelLinkClickedEventArgs) Handles LinkLabel3.LinkClicked
        Scan_DataGridView.Rows.Clear()

        OpenFileDialog1.ShowDialog()

        Dim sr As New StreamReader(OpenFileDialog1.FileName, True)
        Dim line = sr.ReadLine
        While Not line Is Nothing
            Scan_produit_TextBox.Text = line
            If recherche_produit() = 1 Then
                Quantité_produit_TextBox.Text = sr.ReadLine
                If add_prod() = True Then
                    line = sr.ReadLine
                Else
                    sr.Close()
                    MyMsg_Box.Presentation("Officine !", Scan_produit_TextBox.Text & vbCrLf & vbCrLf & "Impossible d'ajouter à la liste" & vbCrLf & vbCrLf & "PROCESSUS INTEROMPU", False, "", False, "", True, "OK")
                    MyMsg_Box.ShowDialog()
                    Exit Sub
                End If
            Else
                sr.Close()
                MyMsg_Box.Presentation("Officine !", Scan_produit_TextBox.Text & vbCrLf & vbCrLf & "code inconnu ou plusieurs resultats" & vbCrLf & vbCrLf & "PROCESSUS INTEROMPU", False, "", False, "", True, "OK")
                MyMsg_Box.ShowDialog()
                Exit Sub
            End If



        End While
    End Sub



    Private Sub Scan_produit_TextBox_TextChanged(sender As Object, e As EventArgs) Handles Scan_produit_TextBox.TextChanged

    End Sub
End Class