' ============================================
' frmJard - الجرد الدوري
' ============================================

Option Explicit
Private countItems As Collection
Private countNumber As String
Private isApproved As Boolean

Private Sub UserForm_Initialize()
    Set countItems = New Collection
    isApproved = False
    txtCountDate.Value = Date
    txtCountNo.Value = GetNewStockCountNumber
    countNumber = txtCountNo.Value
    lblItemName.Caption = ""
    txtActualQty.Value = ""
End Sub

' تحميل الأصناف
Private Sub btnload_Click()
    Dim tbl As ListObject
    Dim i As Long
    Dim r As Long
    
    ListBox1.Clear
    ListBox1.ColumnCount = 6
    ListBox1.ColumnWidths = "100;100;100;100;100;100"
    
    ' صف العناوين
    ListBox1.AddItem "رقم الصنف"
    r = ListBox1.ListCount - 1
    ListBox1.List(r, 1) = "اسم الصنف"
    ListBox1.List(r, 2) = "الرصيد الدفتري"
    ListBox1.List(r, 3) = "الرصيد الفعلي"
    ListBox1.List(r, 4) = "الفرق"
    ListBox1.List(r, 5) = "نوع الفرق"
    
    Set tbl = GetTableByName("tlbInventory")
    If tbl Is Nothing Then
        MsgBox "لا توجد بيانات مخزون", vbExclamation
        Exit Sub
    End If
    
    Set countItems = New Collection
    
    For i = 1 To tbl.ListRows.count
        Dim itemData(1 To 4) As Variant
        itemData(1) = tbl.ListRows(i).Range(1).Value ' رقم الصنف
        itemData(2) = tbl.ListRows(i).Range(2).Value ' اسم الصنف
        itemData(3) = CDbl(tbl.ListRows(i).Range(7).Value) ' الرصيد الدفتري
        itemData(4) = CDbl(tbl.ListRows(i).Range(7).Value) ' الرصيد الفعلي (افتراضي = الدفتري)
        
        countItems.Add itemData
        
        ListBox1.AddItem itemData(1)
        r = ListBox1.ListCount - 1
        ListBox1.List(r, 1) = itemData(2)
        ListBox1.List(r, 2) = Format(itemData(3), "#,##0.00")
        ListBox1.List(r, 3) = Format(itemData(4), "#,##0.00")
        ListBox1.List(r, 4) = Format(itemData(4) - itemData(3), "#,##0.00")
        ListBox1.List(r, 5) = "مطابق"
    Next i
    
    MsgBox "تم تحميل " & countItems.count & " صنف", vbInformation
End Sub

' عند اختيار صنف من ListBox1
Private Sub ListBox1_Click()
    If ListBox1.ListIndex < 0 Or ListBox1.ListIndex = 0 Then Exit Sub
    
    Dim productCode As String
    Dim i As Long
    
    productCode = ListBox1.List(ListBox1.ListIndex, 0)
    lblItemName.Caption = ListBox1.List(ListBox1.ListIndex, 1)
    txtActualQty.Value = ListBox1.List(ListBox1.ListIndex, 3)
    
    ' البحث عن الصنف في Collection
    For i = 1 To countItems.count
        Dim itemData As Variant
        itemData = countItems(i)
        If UCase(Trim(itemData(1))) = UCase(Trim(productCode)) Then
            txtActualQty.Value = Format(itemData(4), "#,##0.00")
            Exit For
        End If
    Next i
End Sub

' تحديث الكمية الفعلية
Private Sub btnUpdateQty_Click()
    If ListBox1.ListIndex < 0 Or ListBox1.ListIndex = 0 Then
        MsgBox "يرجى اختيار صنف من القائمة", vbExclamation
        Exit Sub
    End If
    
    If Not IsNumeric(txtActualQty.Value) Then
        MsgBox "يرجى إدخال كمية صحيحة", vbExclamation
        Exit Sub
    End If
    
    Dim productCode As String
    Dim actualQty As Double
    Dim bookQty As Double
    Dim diff As Double
    Dim diffType As String
    Dim i As Long
    Dim idx As Long
    
    idx = ListBox1.ListIndex
    productCode = ListBox1.List(idx, 0)
    actualQty = CDbl(txtActualQty.Value)
    bookQty = CDbl(ListBox1.List(idx, 2))
    diff = actualQty - bookQty
    
    ' تحديد نوع الفرق
    If diff = 0 Then
        diffType = "مطابق"
    ElseIf diff < 0 Then
        diffType = "عجز"
    Else
        diffType = "زيادة"
    End If
    
    ' تحديث Collection
    For i = 1 To countItems.count
        Dim itemData As Variant
        itemData = countItems(i)
        If UCase(Trim(itemData(1))) = UCase(Trim(productCode)) Then
            itemData(4) = actualQty
            countItems.Remove i
            countItems.Add itemData, , i - 1
            Exit For
        End If
    Next i
    
    ' تحديث ListBox1
    ListBox1.List(idx, 3) = Format(actualQty, "#,##0.00")
    ListBox1.List(idx, 4) = Format(diff, "#,##0.00")
    ListBox1.List(idx, 5) = diffType
    
    MsgBox "تم تحديث الكمية", vbInformation
End Sub

' حفظ الجرد
Private Sub btnSave_Click()
    If countItems.count = 0 Then
        MsgBox "يرجى تحميل الأصناف أولاً", vbExclamation
        Exit Sub
    End If
    
    If isApproved Then
        MsgBox "الجرد معتمد ولا يمكن تعديله", vbExclamation
        Exit Sub
    End If
    
    Dim tblHeader As ListObject
    Dim tblDetail As ListObject
    Dim i As Long
    Dim totalItems As Long
    Dim totalDeficit As Double
    Dim totalSurplus As Double
    Dim headerRow As ListRow
    Dim detailRow As ListRow
    
    Set tblHeader = GetTableByName("tlbStockCountHeader")
    Set tblDetail = GetTableByName("tlbStockCount")
    
    If tblHeader Is Nothing Or tblDetail Is Nothing Then
        MsgBox "لا توجد جداول الجرد", vbExclamation
        Exit Sub
    End If
    
    ' حذف البيانات القديمة للجرد نفسه إن وجدت
    DeleteStockCountData countNumber
    
    ' حساب الإجماليات
    totalItems = countItems.count
    totalDeficit = 0
    totalSurplus = 0
    
    For i = 1 To countItems.count
        Dim itemData As Variant
        itemData = countItems(i)
        Dim diff As Double
        diff = itemData(4) - itemData(3) ' الفرق = الفعلي - الدفتري
        
        If diff < 0 Then
            totalDeficit = totalDeficit + Abs(diff)
        ElseIf diff > 0 Then
            totalSurplus = totalSurplus + diff
        End If
    Next i
    
    ' حفظ Header
    Set headerRow = tblHeader.ListRows.Add
    headerRow.Range(1).Value = countNumber
    headerRow.Range(2).Value = txtCountDate.Value
    headerRow.Range(3).Value = totalItems
    headerRow.Range(4).Value = totalDeficit
    headerRow.Range(5).Value = totalSurplus
    headerRow.Range(6).Value = "مسودة"
    headerRow.Range(7).Value = ""
    headerRow.Range(8).Value = ""
    headerRow.Range(9).Value = ""
    
    ' حفظ التفاصيل
    For i = 1 To countItems.count
        itemData = countItems(i)
        diff = itemData(4) - itemData(3)
        
        Dim diffType As String
        If diff = 0 Then
            diffType = "مطابق"
        ElseIf diff < 0 Then
            diffType = "عجز"
        Else
            diffType = "زيادة"
        End If
        
        Set detailRow = tblDetail.ListRows.Add
        detailRow.Range(1).Value = countNumber
        detailRow.Range(2).Value = txtCountDate.Value
        detailRow.Range(3).Value = itemData(1)
        detailRow.Range(4).Value = itemData(2)
        detailRow.Range(5).Value = itemData(3)
        detailRow.Range(6).Value = itemData(4)
        detailRow.Range(7).Value = diff
        detailRow.Range(8).Value = diffType
        detailRow.Range(9).Value = "" ' المخزن
        detailRow.Range(10).Value = "" ' تم بواسطة
        detailRow.Range(11).Value = "" ' ملاحظات
    Next i
    
    MsgBox "تم حفظ الجرد بنجاح", vbInformation
End Sub

' اعتماد الجرد
Private Sub btnApprove_Click()
    If countItems.count = 0 Then
        MsgBox "يرجى تحميل وحفظ الجرد أولاً", vbExclamation
        Exit Sub
    End If
    
    Dim response As VbMsgBoxResult
    response = MsgBox("هل أنت متأكد من اعتماد الجرد؟ سيتم إنشاء حركات تلقائية.", vbYesNo + vbQuestion, "اعتماد الجرد")
    
    If response = vbNo Then Exit Sub
    
    Dim userName As String
    userName = InputBox("أدخل اسم المستخدم للاعتماد:", "اعتماد الجرد")
    If userName = "" Then Exit Sub
    
    Dim tblHeader As ListObject
    Dim tblDetail As ListObject
    Dim i As Long
    Dim transactionNum As String
    
    Set tblHeader = GetTableByName("tlbStockCountHeader")
    Set tblDetail = GetTableByName("tlbStockCount")
    
    ' تحديث Header
    For i = 1 To tblHeader.ListRows.count
        If UCase(Trim(tblHeader.ListRows(i).Range(1).Value)) = UCase(Trim(countNumber)) Then
            tblHeader.ListRows(i).Range(6).Value = "معتمد"
            tblHeader.ListRows(i).Range(7).Value = userName
            tblHeader.ListRows(i).Range(8).Value = Date
            Exit For
        End If
    Next i
    
    ' إنشاء حركات تلقائية
    Set tblDetail = GetTableByName("tlbStockCount")
    For i = 1 To tblDetail.ListRows.count
        If UCase(Trim(tblDetail.ListRows(i).Range(1).Value)) = UCase(Trim(countNumber)) Then
            Dim productCode As String
            Dim productName As String
            Dim bookQty As Double
            Dim actualQty As Double
            Dim diff As Double
            Dim diffType As String
            
            productCode = tblDetail.ListRows(i).Range(3).Value
            productName = tblDetail.ListRows(i).Range(4).Value
            bookQty = CDbl(tblDetail.ListRows(i).Range(5).Value)
            actualQty = CDbl(tblDetail.ListRows(i).Range(6).Value)
            diff = actualQty - bookQty
            diffType = tblDetail.ListRows(i).Range(8).Value
            
            If diffType <> "مطابق" Then
                transactionNum = GetNewTransactionNumber
                Dim transTbl As ListObject
                Set transTbl = GetTableByName("tlbTransaction")
                
                Dim newRow As ListRow
                Set newRow = transTbl.ListRows.Add
                newRow.Range(1).Value = transactionNum
                newRow.Range(2).Value = Date
                
                If diffType = "عجز" Then
                    newRow.Range(3).Value = "صادر"
                    newRow.Range(6).Value = Abs(diff)
                    newRow.Range(7).Value = 0 ' سعر الصفر للجرد
                    newRow.Range(8).Value = 0
                    UpdateInventory productCode, 0, Abs(diff)
                ElseIf diffType = "زيادة" Then
                    newRow.Range(3).Value = "وارد"
                    newRow.Range(6).Value = diff
                    newRow.Range(7).Value = 0 ' سعر الصفر للجرد
                    newRow.Range(8).Value = 0
                    UpdateInventory productCode, diff, 0
                End If
                
                newRow.Range(4).Value = productCode
                newRow.Range(5).Value = productName
                newRow.Range(9).Value = ""
                newRow.Range(10).Value = "جرد دوري"
                newRow.Range(11).Value = "JRD-" & countNumber
                newRow.Range(12).Value = userName
                newRow.Range(13).Value = "جرد دوري - " & countNumber
            Else
                ' تحديث آخر حركة فقط
                UpdateInventory productCode, 0, 0
            End If
        End If
    Next i
    
    ' تحديث Inventory - تحديث المخزون الحالي من StockCount
    Set tblDetail = GetTableByName("tlbStockCount")
    For i = 1 To tblDetail.ListRows.count
        If UCase(Trim(tblDetail.ListRows(i).Range(1).Value)) = UCase(Trim(countNumber)) Then
            Dim productCode As String
            Dim actualQty As Double
            productCode = tblDetail.ListRows(i).Range(3).Value
            actualQty = CDbl(tblDetail.ListRows(i).Range(6).Value)
            UpdateInventoryToActual productCode, actualQty
        End If
    Next i
    
    isApproved = True
    MsgBox "تم اعتماد الجرد بنجاح وتم إنشاء الحركات التلقائية", vbInformation
End Sub

' تحديث المخزون إلى القيمة الفعلية
Private Sub UpdateInventoryToActual(productCode As String, actualQty As Double)
    Dim tbl As ListObject
    Dim i As Long
    
    Set tbl = GetTableByName("tlbInventory")
    If tbl Is Nothing Then Exit Sub
    
    For i = 1 To tbl.ListRows.count
        If UCase(Trim(tbl.ListRows(i).Range(1).Value)) = UCase(Trim(productCode)) Then
            tbl.ListRows(i).Range(7).Value = actualQty ' المخزون الحالي
            tbl.ListRows(i).Range(9).Value = Date ' آخر حركة
            Exit For
        End If
    Next i
End Sub

' حذف بيانات الجرد
Private Sub DeleteStockCountData(countNum As String)
    Dim tblHeader As ListObject
    Dim tblDetail As ListObject
    Dim i As Long
    
    Set tblHeader = GetTableByName("tlbStockCountHeader")
    Set tblDetail = GetTableByName("tlbStockCount")
    
    ' حذف التفاصيل
    If Not tblDetail Is Nothing Then
        For i = tblDetail.ListRows.count To 1 Step -1
            If UCase(Trim(tblDetail.ListRows(i).Range(1).Value)) = UCase(Trim(countNum)) Then
                tblDetail.ListRows(i).Delete
            End If
        Next i
    End If
    
    ' حذف Header
    If Not tblHeader Is Nothing Then
        For i = tblHeader.ListRows.count To 1 Step -1
            If UCase(Trim(tblHeader.ListRows(i).Range(1).Value)) = UCase(Trim(countNum)) Then
                tblHeader.ListRows(i).Delete
            End If
        Next i
    End If
End Sub

' تصدير HTML
Private Sub btnHTMLopen_Click()
    If countNumber = "" Then
        MsgBox "يرجى حفظ الجرد أولاً", vbExclamation
        Exit Sub
    End If
    
    GenerateStockCountReport countNumber
End Sub

' إغلاق
Private Sub btnClose_Click()
    Me.Hide
End Sub



