
' ============================================
' Module HTML Reports - تقارير HTML
' ============================================

Option Explicit

' ============================================
' تقرير المخزون الحالي
' ============================================
Public Sub GenerateStockNowReport()
    Dim html As String
    Dim tbl As ListObject
    Dim i As Long
    Dim totalValue As Double
    
    Set tbl = GetTableByName("tlbInventory")
    If tbl Is Nothing Then Exit Sub
    
    html = GetHTMLHeader("تقرير المخزون الحالي")
    html = html & "<div class='container'>"
    html = html & "<h1>تقرير المخزون الحالي</h1>"
    html = html & "<p><strong>التاريخ:</strong> " & Format(Date, "yyyy/mm/dd") & "</p>"
    html = html & "<table class='data-table'>"
    html = html & "<thead><tr>"
    html = html & "<th>رقم الصنف</th>"
    html = html & "<th>اسم الصنف</th>"
    html = html & "<th>المخزون الحالي</th>"
    html = html & "<th>قيمة المخزون</th>"
    html = html & "<th>آخر حركة</th>"
    html = html & "<th>الحالة</th>"
    html = html & "</tr></thead><tbody>"
    
    totalValue = 0
    For i = 1 To tbl.ListRows.count
        html = html & "<tr>"
        html = html & "<td>" & tbl.ListRows(i).Range(1).Value & "</td>"
        html = html & "<td>" & tbl.ListRows(i).Range(2).Value & "</td>"
        html = html & "<td>" & Format(tbl.ListRows(i).Range(7).Value, "#,##0.00") & "</td>"
        html = html & "<td>" & Format(tbl.ListRows(i).Range(8).Value, "#,##0.00") & "</td>"
        html = html & "<td>" & Format(tbl.ListRows(i).Range(9).Value, "yyyy/mm/dd") & "</td>"
        html = html & "<td>" & tbl.ListRows(i).Range(11).Value & "</td>"
        html = html & "</tr>"
        totalValue = totalValue + CDbl(tbl.ListRows(i).Range(8).Value)
    Next i
    
    html = html & "</tbody></table>"
    html = html & "<div class='summary'><h2>إجمالي قيمة المخزون: " & Format(totalValue, "#,##0.00") & " ريال</h2></div>"
    html = html & "</div>" & GetHTMLFooter
    
    SaveAndOpenHTML html, "StockNowReport"
End Sub

' ============================================
' تقرير الوارد والصادر
' ============================================
Public Sub GenerateInOutReport()
    Dim html As String
    Dim tbl As ListObject
    Dim i As Long
    Dim totalIn As Double
    Dim totalOut As Double
    
    Set tbl = GetTableByName("tlbTransaction")
    If tbl Is Nothing Then Exit Sub
    
    html = GetHTMLHeader("تقرير الوارد والصادر")
    html = html & "<div class='container'>"
    html = html & "<h1>تقرير الوارد والصادر</h1>"
    html = html & "<p><strong>التاريخ:</strong> " & Format(Date, "yyyy/mm/dd") & "</p>"
    html = html & "<table class='data-table'>"
    html = html & "<thead><tr>"
    html = html & "<th>رقم الحركة</th>"
    html = html & "<th>التاريخ</th>"
    html = html & "<th>نوع الحركة</th>"
    html = html & "<th>اسم الصنف</th>"
    html = html & "<th>الكمية</th>"
    html = html & "<th>سعر الوحدة</th>"
    html = html & "<th>الإجمالي</th>"
    html = html & "<th>العميل/المورد</th>"
    html = html & "<th>رقم الفاتورة</th>"
    html = html & "</tr></thead><tbody>"
    
    totalIn = 0
    totalOut = 0
    For i = 1 To tbl.ListRows.count
        html = html & "<tr>"
        html = html & "<td>" & tbl.ListRows(i).Range(1).Value & "</td>"
        html = html & "<td>" & Format(tbl.ListRows(i).Range(2).Value, "yyyy/mm/dd") & "</td>"
        html = html & "<td>" & tbl.ListRows(i).Range(3).Value & "</td>"
        html = html & "<td>" & tbl.ListRows(i).Range(5).Value & "</td>"
        html = html & "<td>" & Format(tbl.ListRows(i).Range(6).Value, "#,##0.00") & "</td>"
        html = html & "<td>" & Format(tbl.ListRows(i).Range(7).Value, "#,##0.00") & "</td>"
        html = html & "<td>" & Format(tbl.ListRows(i).Range(8).Value, "#,##0.00") & "</td>"
        html = html & "<td>" & tbl.ListRows(i).Range(10).Value & "</td>"
        html = html & "<td>" & tbl.ListRows(i).Range(11).Value & "</td>"
        html = html & "</tr>"
        
        If UCase(tbl.ListRows(i).Range(3).Value) = "وارد" Then
            totalIn = totalIn + CDbl(tbl.ListRows(i).Range(8).Value)
        ElseIf UCase(tbl.ListRows(i).Range(3).Value) = "صادر" Then
            totalOut = totalOut + CDbl(tbl.ListRows(i).Range(8).Value)
        End If
    Next i
    
    html = html & "</tbody></table>"
    html = html & "<div class='summary'>"
    html = html & "<h2>إجمالي الوارد: " & Format(totalIn, "#,##0.00") & " ريال</h2>"
    html = html & "<h2>إجمالي الصادر: " & Format(totalOut, "#,##0.00") & " ريال</h2>"
    html = html & "<h2>الفرق: " & Format(totalIn - totalOut, "#,##0.00") & " ريال</h2>"
    html = html & "</div>"
    html = html & "</div>" & GetHTMLFooter
    
    SaveAndOpenHTML html, "InOutReport"
End Sub

' ============================================
' تقرير الجرد الدوري
' ============================================
Public Sub GenerateStockCountReport(countNumber As String)
    Dim html As String
    Dim tblHeader As ListObject
    Dim tblDetail As ListObject
    Dim i As Long
    Dim j As Long
    Dim countDate As Date
    Dim totalItems As Long
    Dim totalDeficit As Double
    Dim totalSurplus As Double
    
    Set tblHeader = GetTableByName("tlbStockCountHeader")
    Set tblDetail = GetTableByName("tlbStockCount")
    
    If tblHeader Is Nothing Or tblDetail Is Nothing Then Exit Sub
    
    ' البحث عن الجرد
    For i = 1 To tblHeader.ListRows.count
        If UCase(Trim(tblHeader.ListRows(i).Range(1).Value)) = UCase(Trim(countNumber)) Then
            countDate = tblHeader.ListRows(i).Range(2).Value
            totalItems = tblHeader.ListRows(i).Range(3).Value
            totalDeficit = tblHeader.ListRows(i).Range(4).Value
            totalSurplus = tblHeader.ListRows(i).Range(5).Value
            Exit For
        End If
    Next i
    
    html = GetHTMLHeader("تقرير الجرد الدوري")
    html = html & "<div class='container'>"
    html = html & "<h1>تقرير الجرد الدوري</h1>"
    html = html & "<p><strong>رقم الجرد:</strong> " & countNumber & "</p>"
    html = html & "<p><strong>تاريخ الجرد:</strong> " & Format(countDate, "yyyy/mm/dd") & "</p>"
    html = html & "<table class='data-table'>"
    html = html & "<thead><tr>"
    html = html & "<th>رقم الصنف</th>"
    html = html & "<th>اسم الصنف</th>"
    html = html & "<th>الرصيد الدفتري</th>"
    html = html & "<th>الرصيد الفعلي</th>"
    html = html & "<th>الفرق</th>"
    html = html & "<th>نوع الفرق</th>"
    html = html & "</tr></thead><tbody>"
    
    For j = 1 To tblDetail.ListRows.count
        If UCase(Trim(tblDetail.ListRows(j).Range(1).Value)) = UCase(Trim(countNumber)) Then
            html = html & "<tr>"
            html = html & "<td>" & tblDetail.ListRows(j).Range(3).Value & "</td>"
            html = html & "<td>" & tblDetail.ListRows(j).Range(4).Value & "</td>"
            html = html & "<td>" & Format(tblDetail.ListRows(j).Range(5).Value, "#,##0.00") & "</td>"
            html = html & "<td>" & Format(tblDetail.ListRows(j).Range(6).Value, "#,##0.00") & "</td>"
            html = html & "<td>" & Format(tblDetail.ListRows(j).Range(7).Value, "#,##0.00") & "</td>"
            html = html & "<td>" & tblDetail.ListRows(j).Range(8).Value & "</td>"
            html = html & "</tr>"
        End If
    Next j
    
    html = html & "</tbody></table>"
    html = html & "<div class='summary'>"
    html = html & "<h2>إجمالي الأصناف: " & totalItems & "</h2>"
    html = html & "<h2>إجمالي العجز: " & Format(totalDeficit, "#,##0.00") & "</h2>"
    html = html & "<h2>إجمالي الزيادة: " & Format(totalSurplus, "#,##0.00") & "</h2>"
    html = html & "</div>"
    html = html & "</div>" & GetHTMLFooter
    
    SaveAndOpenHTML html, "StockCount_" & countNumber
End Sub

' ============================================
' فاتورة الوارد
' ============================================
Public Sub GenerateInvoiceIn(invoiceNumber As String)
    Dim html As String
    Dim tbl As ListObject
    Dim i As Long
    Dim supplierName As String
    Dim invoiceDate As Date
    Dim totalAmount As Double
    Dim items As Collection
    Dim item As Variant
    
    Set tbl = GetTableByName("tlbTransaction")
    If tbl Is Nothing Then Exit Sub
    
    Set items = New Collection
    totalAmount = 0
    
    ' جمع بيانات الفاتورة
    For i = 1 To tbl.ListRows.count
        If UCase(Trim(tbl.ListRows(i).Range(11).Value)) = UCase(Trim(invoiceNumber)) Then
            If UCase(tbl.ListRows(i).Range(3).Value) = "وارد" Then
                If supplierName = "" Then
                    supplierName = tbl.ListRows(i).Range(10).Value
                    invoiceDate = tbl.ListRows(i).Range(2).Value
                End If
                Dim itemData(1 To 4) As Variant
                itemData(1) = tbl.ListRows(i).Range(5).Value ' اسم الصنف
                itemData(2) = tbl.ListRows(i).Range(6).Value ' الكمية
                itemData(3) = tbl.ListRows(i).Range(7).Value ' سعر الوحدة
                itemData(4) = tbl.ListRows(i).Range(8).Value ' الإجمالي
                items.Add itemData
                totalAmount = totalAmount + CDbl(tbl.ListRows(i).Range(8).Value)
            End If
        End If
    Next i
    
    If items.count = 0 Then Exit Sub
    
    html = GetHTMLHeader("فاتورة وارد")
    html = html & "<div class='container invoice'>"
    html = html & "<div class='invoice-header'>"
    html = html & "<h1>" & GetCompanySetting("COMPANYNAME") & "</h1>"
    html = html & "<p>" & GetCompanySetting("ADDRESS") & "</p>"
    html = html & "<p>هاتف: " & GetCompanySetting("PHONE") & " | بريد: " & GetCompanySetting("EMAIL") & "</p>"
    html = html & "</div>"
    html = html & "<div class='invoice-info'>"
    html = html & "<h2>فاتورة وارد</h2>"
    html = html & "<p><strong>رقم الفاتورة:</strong> " & invoiceNumber & "</p>"
    html = html & "<p><strong>التاريخ:</strong> " & Format(invoiceDate, "yyyy/mm/dd") & "</p>"
    html = html & "<p><strong>المورد:</strong> " & supplierName & "</p>"
    html = html & "</div>"
    html = html & "<table class='invoice-table'>"
    html = html & "<thead><tr>"
    html = html & "<th>اسم الصنف</th>"
    html = html & "<th>الكمية</th>"
    html = html & "<th>سعر الوحدة</th>"
    html = html & "<th>الإجمالي</th>"
    html = html & "</tr></thead><tbody>"
    
    For Each item In items
        html = html & "<tr>"
        html = html & "<td>" & item(1) & "</td>"
        html = html & "<td>" & Format(item(2), "#,##0.00") & "</td>"
        html = html & "<td>" & Format(item(3), "#,##0.00") & "</td>"
        html = html & "<td>" & Format(item(4), "#,##0.00") & "</td>"
        html = html & "</tr>"
    Next item
    
    html = html & "</tbody>"
    html = html & "<tfoot><tr><td colspan='3'><strong>الإجمالي</strong></td><td><strong>" & Format(totalAmount, "#,##0.00") & " ريال</strong></td></tr></tfoot>"
    html = html & "</table>"
    html = html & "</div>" & GetHTMLFooter
    
    SaveAndOpenHTML html, "InvoiceIn_" & invoiceNumber
End Sub

' ============================================
' فاتورة الصادر
' ============================================
Public Sub GenerateInvoiceOut(invoiceNumber As String)
    Dim html As String
    Dim tbl As ListObject
    Dim i As Long
    Dim customerName As String
    Dim invoiceDate As Date
    Dim totalAmount As Double
    Dim items As Collection
    Dim item As Variant
    
    Set tbl = GetTableByName("tlbTransaction")
    If tbl Is Nothing Then Exit Sub
    
    Set items = New Collection
    totalAmount = 0
    
    ' جمع بيانات الفاتورة
    For i = 1 To tbl.ListRows.count
        If UCase(Trim(tbl.ListRows(i).Range(11).Value)) = UCase(Trim(invoiceNumber)) Then
            If UCase(tbl.ListRows(i).Range(3).Value) = "صادر" Then
                If customerName = "" Then
                    customerName = tbl.ListRows(i).Range(10).Value
                    invoiceDate = tbl.ListRows(i).Range(2).Value
                End If
                Dim itemData(1 To 4) As Variant
                itemData(1) = tbl.ListRows(i).Range(5).Value ' اسم الصنف
                itemData(2) = tbl.ListRows(i).Range(6).Value ' الكمية
                itemData(3) = tbl.ListRows(i).Range(7).Value ' سعر الوحدة
                itemData(4) = tbl.ListRows(i).Range(8).Value ' الإجمالي
                items.Add itemData
                totalAmount = totalAmount + CDbl(tbl.ListRows(i).Range(8).Value)
            End If
        End If
    Next i
    
    If items.count = 0 Then Exit Sub
    
    html = GetHTMLHeader("فاتورة صادر")
    html = html & "<div class='container invoice'>"
    html = html & "<div class='invoice-header'>"
    html = html & "<h1>" & GetCompanySetting("COMPANYNAME") & "</h1>"
    html = html & "<p>" & GetCompanySetting("ADDRESS") & "</p>"
    html = html & "<p>هاتف: " & GetCompanySetting("PHONE") & " | بريد: " & GetCompanySetting("EMAIL") & "</p>"
    html = html & "</div>"
    html = html & "<div class='invoice-info'>"
    html = html & "<h2>فاتورة صادر</h2>"
    html = html & "<p><strong>رقم الفاتورة:</strong> " & invoiceNumber & "</p>"
    html = html & "<p><strong>التاريخ:</strong> " & Format(invoiceDate, "yyyy/mm/dd") & "</p>"
    html = html & "<p><strong>العميل:</strong> " & customerName & "</p>"
    html = html & "</div>"
    html = html & "<table class='invoice-table'>"
    html = html & "<thead><tr>"
    html = html & "<th>اسم الصنف</th>"
    html = html & "<th>الكمية</th>"
    html = html & "<th>سعر الوحدة</th>"
    html = html & "<th>الإجمالي</th>"
    html = html & "</tr></thead><tbody>"
    
    For Each item In items
        html = html & "<tr>"
        html = html & "<td>" & item(1) & "</td>"
        html = html & "<td>" & Format(item(2), "#,##0.00") & "</td>"
        html = html & "<td>" & Format(item(3), "#,##0.00") & "</td>"
        html = html & "<td>" & Format(item(4), "#,##0.00") & "</td>"
        html = html & "</tr>"
    Next item
    
    html = html & "</tbody>"
    html = html & "<tfoot><tr><td colspan='3'><strong>الإجمالي</strong></td><td><strong>" & Format(totalAmount, "#,##0.00") & " ريال</strong></td></tr></tfoot>"
    html = html & "</table>"
    html = html & "</div>" & GetHTMLFooter
    
    SaveAndOpenHTML html, "InvoiceOut_" & invoiceNumber
End Sub

' ============================================
' تقرير الأصناف الأكثر مبيعاً
' ============================================
Public Sub GenerateTopSellingProducts()
    Dim html As String
    Dim tbl As ListObject
    Dim i As Long
    Dim products As Object
    Dim productCode As String
    Dim productName As String
    Dim qty As Double
    Dim key As Variant
    
    Set tbl = GetTableByName("tlbTransaction")
    If tbl Is Nothing Then Exit Sub
    
    Set products = CreateObject("Scripting.Dictionary")
    
    ' جمع بيانات المبيعات
    For i = 1 To tbl.ListRows.count
        If UCase(tbl.ListRows(i).Range(3).Value) = "صادر" Then
            productCode = tbl.ListRows(i).Range(4).Value
            productName = tbl.ListRows(i).Range(5).Value
            qty = CDbl(tbl.ListRows(i).Range(6).Value)
            
            If products.exists(productCode) Then
                products(productCode) = products(productCode) + qty
            Else
                products.Add productCode, qty
            End If
        End If
    Next i
    
    ' ترتيب حسب الكمية
    html = GetHTMLHeader("الأصناف الأكثر مبيعاً")
    html = html & "<div class='container'>"
    html = html & "<h1>الأصناف الأكثر مبيعاً</h1>"
    html = html & "<p><strong>التاريخ:</strong> " & Format(Date, "yyyy/mm/dd") & "</p>"
    html = html & "<table class='data-table'>"
    html = html & "<thead><tr>"
    html = html & "<th>رقم الصنف</th>"
    html = html & "<th>اسم الصنف</th>"
    html = html & "<th>إجمالي الكمية المباعة</th>"
    html = html & "</tr></thead><tbody>"
    
    ' ترتيب بسيط (يمكن تحسينه)
    Dim sortedProducts As Collection
    Set sortedProducts = New Collection
    For Each key In products.keys
        sortedProducts.Add Array(key, products(key))
    Next key
    
    ' عرض أول 20 صنف
    Dim count As Long
    count = 0
    For Each key In sortedProducts
        If count >= 20 Then Exit For
        Dim productInfo As Variant
        productInfo = key
        html = html & "<tr>"
        html = html & "<td>" & productInfo(0) & "</td>"
        html = html & "<td>" & GetProductNameByCode(CStr(productInfo(0))) & "</td>"
        html = html & "<td>" & Format(productInfo(1), "#,##0.00") & "</td>"
        html = html & "</tr>"
        count = count + 1
    Next key
    
    html = html & "</tbody></table>"
    html = html & "</div>" & GetHTMLFooter
    
    SaveAndOpenHTML html, "TopSellingProducts"
End Sub

' ============================================
' تقرير الأصناف المنخفضة
' ============================================
Public Sub GenerateLowStockReport()
    Dim html As String
    Dim tbl As ListObject
    Dim i As Long
    
    Set tbl = GetTableByName("tlbInventory")
    If tbl Is Nothing Then Exit Sub
    
    html = GetHTMLHeader("الأصناف المنخفضة")
    html = html & "<div class='container'>"
    html = html & "<h1>الأصناف المنخفضة في المخزون</h1>"
    html = html & "<p><strong>التاريخ:</strong> " & Format(Date, "yyyy/mm/dd") & "</p>"
    html = html & "<table class='data-table'>"
    html = html & "<thead><tr>"
    html = html & "<th>رقم الصنف</th>"
    html = html & "<th>اسم الصنف</th>"
    html = html & "<th>المخزون الحالي</th>"
    html = html & "<th>حد التنبية</th>"
    html = html & "<th>الحالة</th>"
    html = html & "</tr></thead><tbody>"
    
    For i = 1 To tbl.ListRows.count
        If UCase(Trim(tbl.ListRows(i).Range(11).Value)) = "منخفض" Then
            html = html & "<tr>"
            html = html & "<td>" & tbl.ListRows(i).Range(1).Value & "</td>"
            html = html & "<td>" & tbl.ListRows(i).Range(2).Value & "</td>"
            html = html & "<td>" & Format(tbl.ListRows(i).Range(7).Value, "#,##0.00") & "</td>"
            html = html & "<td>" & Format(tbl.ListRows(i).Range(10).Value, "#,##0.00") & "</td>"
            html = html & "<td>" & tbl.ListRows(i).Range(11).Value & "</td>"
            html = html & "</tr>"
        End If
    Next i
    
    html = html & "</tbody></table>"
    html = html & "</div>" & GetHTMLFooter
    
    SaveAndOpenHTML html, "LowStockReport"
End Sub

' ============================================
' تقرير الأرباح والخسائر
' ============================================
Public Sub GenerateProfitLossReport()
    Dim html As String
    Dim tbl As ListObject
    Dim i As Long
    Dim products As Object
    Dim productCode As String
    Dim purchasePrice As Double
    Dim salePrice As Double
    Dim qty As Double
    Dim key As Variant
    Dim totalProfit As Double
    
    Set tbl = GetTableByName("tlbTransaction")
    If tbl Is Nothing Then Exit Sub
    
    Set products = CreateObject("Scripting.Dictionary")
    
    ' جمع بيانات المبيعات والمشتريات
    For i = 1 To tbl.ListRows.count
        productCode = tbl.ListRows(i).Range(4).Value
        
        If UCase(tbl.ListRows(i).Range(3).Value) = "صادر" Then
            salePrice = CDbl(tbl.ListRows(i).Range(7).Value)
            qty = CDbl(tbl.ListRows(i).Range(6).Value)
            
            If products.exists(productCode) Then
                Dim profitData As Variant
                profitData = products(productCode)
                profitData(2) = profitData(2) + (salePrice * qty) ' إجمالي المبيعات
                profitData(4) = profitData(4) + qty ' الكمية المباعة
                products(productCode) = profitData
            Else
                Dim productInfo As Variant
                productInfo = GetProductByCode(productCode)
                If Not IsEmpty(productInfo) Then
                    ' استخدام Average Cost بدلاً من سعر الشراء
                    purchasePrice = GetAverageCost(productCode)
                    If purchasePrice = 0 Then purchasePrice = CDbl(productInfo(4)) ' إذا لم يوجد Average Cost، استخدم سعر الشراء
                    products.Add productCode, Array(productCode, productInfo(2), salePrice * qty, purchasePrice, qty, 0)
                End If
            End If
        End If
    Next i
    
    html = GetHTMLHeader("تقرير الأرباح والخسائر")
    html = html & "<div class='container'>"
    html = html & "<h1>تقرير الأرباح والخسائر</h1>"
    html = html & "<p><strong>التاريخ:</strong> " & Format(Date, "yyyy/mm/dd") & "</p>"
    html = html & "<table class='data-table'>"
    html = html & "<thead><tr>"
    html = html & "<th>رقم الصنف</th>"
    html = html & "<th>اسم الصنف</th>"
    html = html & "<th>متوسط التكلفة</th>"
    html = html & "<th>سعر البيع</th>"
    html = html & "<th>الكمية المباعة</th>"
    html = html & "<th>إجمالي المبيعات</th>"
    html = html & "<th>تكلفة الشراء</th>"
    html = html & "<th>الربح</th>"
    html = html & "<th>هامش الربح %</th>"
    html = html & "</tr></thead><tbody>"
    
    totalProfit = 0
    For Each key In products.keys
        Dim prodData As Variant
        prodData = products(key)
        Dim avgSalePrice As Double
        Dim totalSales As Double
        Dim totalCost As Double
        Dim profit As Double
        Dim margin As Double
        
        totalSales = prodData(2)
        ' استخدام Average Cost الحالي للصنف
        purchasePrice = GetAverageCost(CStr(prodData(0)))
        If purchasePrice = 0 Then purchasePrice = prodData(3) ' إذا لم يوجد، استخدم القيمة المحفوظة
        qty = prodData(4)
        avgSalePrice = totalSales / qty
        totalCost = purchasePrice * qty
        profit = totalSales - totalCost
        If totalSales > 0 Then
            margin = (profit / totalSales) * 100
        Else
            margin = 0
        End If
        
        html = html & "<tr>"
        html = html & "<td>" & prodData(0) & "</td>"
        html = html & "<td>" & prodData(1) & "</td>"
        html = html & "<td>" & Format(purchasePrice, "#,##0.00") & "</td>"
        html = html & "<td>" & Format(avgSalePrice, "#,##0.00") & "</td>"
        html = html & "<td>" & Format(qty, "#,##0.00") & "</td>"
        html = html & "<td>" & Format(totalSales, "#,##0.00") & "</td>"
        html = html & "<td>" & Format(totalCost, "#,##0.00") & "</td>"
        html = html & "<td>" & Format(profit, "#,##0.00") & "</td>"
        html = html & "<td>" & Format(margin, "#,##0.00") & "%</td>"
        html = html & "</tr>"
        
        totalProfit = totalProfit + profit
    Next key
    
    html = html & "</tbody>"
    html = html & "<tfoot><tr><td colspan='8'><strong>إجمالي الربح</strong></td><td><strong>" & Format(totalProfit, "#,##0.00") & " ريال</strong></td></tr></tfoot>"
    html = html & "</table>"
    html = html & "</div>" & GetHTMLFooter
    
    SaveAndOpenHTML html, "ProfitLossReport"
End Sub

' ============================================
' تقرير الأصناف المطلوبة لإعادة الطلب
' ============================================
Public Sub GenerateReorderReport()
    Dim html As String
    Dim tbl As ListObject
    Dim i As Long
    
    Set tbl = GetTableByName("tlbInventory")
    If tbl Is Nothing Then Exit Sub
    
    html = GetHTMLHeader("الأصناف المطلوبة لإعادة الطلب")
    html = html & "<div class='container'>"
    html = html & "<h1>الأصناف المطلوبة لإعادة الطلب</h1>"
    html = html & "<p><strong>التاريخ:</strong> " & Format(Date, "yyyy/mm/dd") & "</p>"
    html = html & "<table class='data-table'>"
    html = html & "<thead><tr>"
    html = html & "<th>رقم الصنف</th>"
    html = html & "<th>اسم الصنف</th>"
    html = html & "<th>المخزون الحالي</th>"
    html = html & "<th>حد التنبية</th>"
    html = html & "<th>الكمية المطلوبة</th>"
    html = html & "</tr></thead><tbody>"
    
    For i = 1 To tbl.ListRows.count
        Dim currentStock As Double
        Dim alertLimit As Double
        Dim requiredQty As Double
        
        ' التحقق من أن القيم رقمية قبل التحويل
        If Not IsNumeric(tbl.ListRows(i).Range(7).Value) Or Not IsNumeric(tbl.ListRows(i).Range(10).Value) Then
            GoTo NextRow
        End If
        
        currentStock = CDbl(tbl.ListRows(i).Range(7).Value)
        alertLimit = CDbl(tbl.ListRows(i).Range(10).Value)
        
        If currentStock <= alertLimit Then
            requiredQty = alertLimit * 2 - currentStock ' ضعف الحد كحد أدنى
            
            html = html & "<tr>"
            html = html & "<td>" & tbl.ListRows(i).Range(1).Value & "</td>"
            html = html & "<td>" & tbl.ListRows(i).Range(2).Value & "</td>"
            html = html & "<td>" & Format(currentStock, "#,##0.00") & "</td>"
            html = html & "<td>" & Format(alertLimit, "#,##0.00") & "</td>"
            html = html & "<td>" & Format(requiredQty, "#,##0.00") & "</td>"
            html = html & "</tr>"
        End If
NextRow:
    Next i
    
    html = html & "</tbody></table>"
    html = html & "</div>" & GetHTMLFooter
    
    SaveAndOpenHTML html, "ReorderReport"
End Sub

' ============================================
' تقرير المنتجات الراكدة
' ============================================
Public Sub GenerateSlowMovingProductsReport()
    Dim html As String
    Dim inventoryTbl As ListObject
    Dim transactionTbl As ListObject
    Dim i As Long
    Dim j As Long
    Dim productCode As String
    Dim productName As String
    Dim currentStock As Double
    Dim lastSaleDate As Date
    Dim daysSinceLastSale As Long
    Dim hasSales As Boolean
    Dim minDays As Long ' الحد الأدنى للأيام بدون بيع
    
    ' تحديد الحد الأدنى للأيام (30 يوم)
    minDays = 30
    
    Set inventoryTbl = GetTableByName("tlbInventory")
    If inventoryTbl Is Nothing Then Exit Sub
    
    Set transactionTbl = GetTableByName("tlbTransaction")
    If transactionTbl Is Nothing Then Exit Sub
    
    html = GetHTMLHeader("تقرير المنتجات الراكدة")
    html = html & "<div class='container'>"
    html = html & "<h1>تقرير المنتجات الراكدة في المخزون</h1>"
    html = html & "<p><strong>التاريخ:</strong> " & Format(Date, "yyyy/mm/dd") & "</p>"
    html = html & "<p><strong>المنتجات التي لم تُباع منذ " & minDays & " يوم أو أكثر</strong></p>"
    html = html & "<table class='data-table'>"
    html = html & "<thead><tr>"
    html = html & "<th>رقم الصنف</th>"
    html = html & "<th>اسم الصنف</th>"
    html = html & "<th>المخزون الحالي</th>"
    html = html & "<th>قيمة المخزون</th>"
    html = html & "<th>آخر تاريخ بيع</th>"
    html = html & "<th>عدد الأيام بدون بيع</th>"
    html = html & "<th>الحالة</th>"
    html = html & "</tr></thead><tbody>"
    
    Dim totalValue As Double
    Dim itemCount As Long
    totalValue = 0
    itemCount = 0
    
    ' فحص كل منتج في المخزون
    For i = 1 To inventoryTbl.ListRows.count
        productCode = CStr(inventoryTbl.ListRows(i).Range(1).Value)
        productName = CStr(inventoryTbl.ListRows(i).Range(2).Value)
        
        ' التحقق من أن المخزون الحالي رقماً صحيحاً
        If Not IsNumeric(inventoryTbl.ListRows(i).Range(7).Value) Then
            GoTo NextProduct
        End If
        
        currentStock = CDbl(inventoryTbl.ListRows(i).Range(7).Value)
        
        ' تخطي المنتجات التي ليس لها مخزون
        If currentStock <= 0 Then GoTo NextProduct
        
        ' البحث عن آخر تاريخ بيع لهذا المنتج
        lastSaleDate = DateSerial(1900, 1, 1) ' تاريخ افتراضي قديم
        hasSales = False
        
        For j = 1 To transactionTbl.ListRows.count
            If UCase(Trim(transactionTbl.ListRows(j).Range(4).Value)) = UCase(Trim(productCode)) Then
                If UCase(transactionTbl.ListRows(j).Range(3).Value) = "صادر" Then
                    Dim saleDate As Date
                    saleDate = transactionTbl.ListRows(j).Range(2).Value
                    If saleDate > lastSaleDate Then
                        lastSaleDate = saleDate
                        hasSales = True
                    End If
                End If
            End If
        Next j
        
        ' حساب عدد الأيام منذ آخر بيع
        If hasSales Then
            daysSinceLastSale = DateDiff("d", lastSaleDate, Date)
        Else
            ' إذا لم يُباع أبداً، استخدم تاريخ آخر حركة من المخزون
            Dim lastMovement As Date
            If IsDate(inventoryTbl.ListRows(i).Range(9).Value) Then
                lastMovement = inventoryTbl.ListRows(i).Range(9).Value
                daysSinceLastSale = DateDiff("d", lastMovement, Date)
            Else
                daysSinceLastSale = 9999 ' عدد كبير جداً
            End If
        End If
        
        ' إذا لم يُباع منذ minDays يوم أو أكثر، أضفه إلى القائمة
        If daysSinceLastSale >= minDays Then
            Dim stockValue As Double
            ' التحقق من أن قيمة المخزون رقماً صحيحاً
            If IsNumeric(inventoryTbl.ListRows(i).Range(8).Value) Then
                stockValue = CDbl(inventoryTbl.ListRows(i).Range(8).Value)
            Else
                stockValue = 0
            End If
            totalValue = totalValue + stockValue
            
            html = html & "<tr>"
            html = html & "<td>" & productCode & "</td>"
            html = html & "<td>" & productName & "</td>"
            html = html & "<td>" & Format(currentStock, "#,##0.00") & "</td>"
            html = html & "<td>" & Format(stockValue, "#,##0.00") & " ريال</td>"
            
            If hasSales Then
                html = html & "<td>" & Format(lastSaleDate, "yyyy/mm/dd") & "</td>"
            Else
                html = html & "<td style='color: #e74c3c;'>لم يُباع أبداً</td>"
            End If
            
            html = html & "<td style='color: #e74c3c; font-weight: bold;'>" & daysSinceLastSale & " يوم</td>"
            
            If daysSinceLastSale >= 90 Then
                html = html & "<td style='color: #e74c3c; font-weight: bold;'>راكد جداً</td>"
            ElseIf daysSinceLastSale >= 60 Then
                html = html & "<td style='color: #f39c12; font-weight: bold;'>راكد</td>"
            Else
                html = html & "<td style='color: #f39c12;'>بطيء</td>"
            End If
            
            html = html & "</tr>"
            itemCount = itemCount + 1
        End If
        
NextProduct:
    Next i
    
    html = html & "</tbody></table>"
    
    ' ملخص
    html = html & "<div class='summary'>"
    html = html & "<h2>ملخص التقرير</h2>"
    html = html & "<p><strong>عدد المنتجات الراكدة:</strong> " & itemCount & " منتج</p>"
    html = html & "<p><strong>إجمالي قيمة المخزون الراكد:</strong> " & Format(totalValue, "#,##0.00") & " ريال</p>"
    html = html & "<p style='color: #e74c3c;'><strong>ملاحظة:</strong> يُنصح بمراجعة هذه المنتجات واتخاذ إجراءات مثل التخفيضات أو الترويج.</p>"
    html = html & "</div>"
    
    html = html & "</div>" & GetHTMLFooter
    
    SaveAndOpenHTML html, "SlowMovingProductsReport"
End Sub

' ============================================
' دوال مساعدة HTML
' ============================================

Public Function GetHTMLHeader(title As String) As String
    GetHTMLHeader = "<!DOCTYPE html>" & vbCrLf
    GetHTMLHeader = GetHTMLHeader & "<html dir='rtl' lang='ar'>" & vbCrLf
    GetHTMLHeader = GetHTMLHeader & "<head>" & vbCrLf
    GetHTMLHeader = GetHTMLHeader & "<meta charset='UTF-8'>" & vbCrLf
    GetHTMLHeader = GetHTMLHeader & "<meta name='viewport' content='width=device-width, initial-scale=1.0'>" & vbCrLf
    GetHTMLHeader = GetHTMLHeader & "<title>" & title & "</title>" & vbCrLf
    GetHTMLHeader = GetHTMLHeader & "<style>" & vbCrLf
    GetHTMLHeader = GetHTMLHeader & "body { font-family: 'Arial', 'Tahoma', 'Segoe UI', 'Arabic Typesetting', 'Simplified Arabic', sans-serif; margin: 0; padding: 20px; background: #f5f5f5; direction: rtl; }" & vbCrLf
    GetHTMLHeader = GetHTMLHeader & ".container { max-width: 1200px; margin: 0 auto; background: white; padding: 30px; border-radius: 10px; box-shadow: 0 2px 10px rgba(0,0,0,0.1); }" & vbCrLf
    GetHTMLHeader = GetHTMLHeader & "h1 { color: #2c3e50; border-bottom: 3px solid #3498db; padding-bottom: 10px; }" & vbCrLf
    GetHTMLHeader = GetHTMLHeader & "h2 { color: #34495e; margin-top: 20px; }" & vbCrLf
    GetHTMLHeader = GetHTMLHeader & ".data-table, .invoice-table { width: 100%; border-collapse: collapse; margin: 20px 0; }" & vbCrLf
    GetHTMLHeader = GetHTMLHeader & ".data-table th, .invoice-table th { background: #3498db; color: white; padding: 12px; text-align: right; }" & vbCrLf
    GetHTMLHeader = GetHTMLHeader & ".data-table td, .invoice-table td { padding: 10px; border: 1px solid #ddd; text-align: right; }" & vbCrLf
    GetHTMLHeader = GetHTMLHeader & ".data-table tr:nth-child(even), .invoice-table tr:nth-child(even) { background: #f9f9f9; }" & vbCrLf
    GetHTMLHeader = GetHTMLHeader & ".data-table tr:hover, .invoice-table tr:hover { background: #e8f4f8; }" & vbCrLf
    GetHTMLHeader = GetHTMLHeader & ".summary { background: #ecf0f1; padding: 20px; border-radius: 5px; margin-top: 20px; }" & vbCrLf
    GetHTMLHeader = GetHTMLHeader & ".invoice-header { text-align: center; margin-bottom: 30px; border-bottom: 2px solid #3498db; padding-bottom: 20px; }" & vbCrLf
    GetHTMLHeader = GetHTMLHeader & ".invoice-info { margin: 20px 0; }" & vbCrLf
    GetHTMLHeader = GetHTMLHeader & "tfoot { background: #34495e; color: white; font-weight: bold; }" & vbCrLf
    GetHTMLHeader = GetHTMLHeader & "@media print { body { background: white; } .container { box-shadow: none; } }" & vbCrLf
    GetHTMLHeader = GetHTMLHeader & "</style>" & vbCrLf
    GetHTMLHeader = GetHTMLHeader & "</head>" & vbCrLf
    GetHTMLHeader = GetHTMLHeader & "<body>" & vbCrLf
End Function

Public Function GetHTMLFooter() As String
    GetHTMLFooter = "</body>" & vbCrLf & "</html>"
End Function

Public Sub SaveAndOpenHTML(htmlContent As String, fileName As String)
    Dim filePath As String
    Dim fileNum As Integer
    Dim utf8Content As String
    Dim stream As Object
    
    filePath = ThisWorkbook.Path & "\" & fileName & "_" & Format(Now, "yyyymmdd_hhmmss") & ".html"
    
    ' حفظ الملف بترميز UTF-8
    On Error Resume Next
    Set stream = CreateObject("ADODB.Stream")
    stream.Type = 2 ' adTypeText
    stream.Charset = "UTF-8"
    stream.Open
    stream.WriteText htmlContent
    stream.SaveToFile filePath, 2 ' adSaveCreateOverWrite
    stream.Close
    Set stream = Nothing
    On Error GoTo 0
    
    ' فتح الملف في المتصفح
    Shell "cmd.exe /c start """" """ & filePath & """", vbHide
End Sub

Private Function GetProductNameByCode(productCode As String) As String
    Dim productData As Variant
    productData = GetProductByCode(productCode)
    If Not IsEmpty(productData) Then
        GetProductNameByCode = productData(2)
    Else
        GetProductNameByCode = ""
    End If
End Function

' ============================================
' تقرير كارت الصنف
' ============================================
Public Sub GenerateItemCardReport(productCode As String, Optional fromDate As Variant = Empty, Optional toDate As Variant = Empty)
    Dim html As String
    Dim tbl As ListObject
    Dim i As Long
    Dim productData As Variant
    Dim productName As String
    Dim fromDateVal As Date
    Dim toDateVal As Date
    Dim openingQty As Double
    Dim inQty As Double
    Dim outQty As Double
    Dim balanceQty As Double
    Dim avgCost As Double
    Dim stockValue As Double
    Dim runningBalance As Double
    
    productData = GetProductByCode(productCode)
    If IsEmpty(productData) Then Exit Sub
    
    productName = productData(2)
    avgCost = GetAverageCost(productCode)
    
    ' تحديد التواريخ
    If IsDate(fromDate) Then
        fromDateVal = CDate(fromDate)
    Else
        fromDateVal = DateSerial(1900, 1, 1)
    End If
    
    If IsDate(toDate) Then
        toDateVal = CDate(toDate)
    Else
        toDateVal = Date
    End If
    
    Set tbl = GetTableByName("tlbTransaction")
    If tbl Is Nothing Then Exit Sub
    
    ' حساب رصيد أول المدة
    openingQty = 0
    For i = 1 To tbl.ListRows.count
        If UCase(Trim(tbl.ListRows(i).Range(4).Value)) = UCase(Trim(productCode)) Then
            If IsDate(tbl.ListRows(i).Range(2).Value) Then
                Dim transDate As Date
                transDate = tbl.ListRows(i).Range(2).Value
                If transDate < fromDateVal Then
                    If UCase(tbl.ListRows(i).Range(3).Value) = "وارد" Then
                        If IsNumeric(tbl.ListRows(i).Range(6).Value) Then
                            openingQty = openingQty + CDbl(tbl.ListRows(i).Range(6).Value)
                        End If
                    ElseIf UCase(tbl.ListRows(i).Range(3).Value) = "صادر" Then
                        If IsNumeric(tbl.ListRows(i).Range(6).Value) Then
                            openingQty = openingQty - CDbl(tbl.ListRows(i).Range(6).Value)
                        End If
                    End If
                End If
            End If
        End If
    Next i
    
    ' حساب الوارد والصادر
    inQty = 0
    outQty = 0
    runningBalance = openingQty
    
    html = GetHTMLHeader("كشف حركة صنف")
    html = html & "<div class='container invoice'>"
    html = html & "<div class='invoice-header'>"
    html = html & "<h1>" & GetCompanySetting("COMPANYNAME") & "</h1>"
    html = html & "<h2>كشف حركة صنف</h2>"
    html = html & "</div>"
    html = html & "<div class='invoice-info'>"
    html = html & "<p><strong>رمز الصنف:</strong> " & productCode & "</p>"
    html = html & "<p><strong>اسم الصنف:</strong> " & productName & "</p>"
    html = html & "<p><strong>من تاريخ:</strong> " & Format(fromDateVal, "yyyy/mm/dd") & "</p>"
    html = html & "<p><strong>إلى تاريخ:</strong> " & Format(toDateVal, "yyyy/mm/dd") & "</p>"
    html = html & "</div>"
    html = html & "<table class='invoice-table'>"
    html = html & "<thead><tr>"
    html = html & "<th>التاريخ</th>"
    html = html & "<th>رقم المستند</th>"
    html = html & "<th>نوع الحركة</th>"
    html = html & "<th>وارد</th>"
    html = html & "<th>صادر</th>"
    html = html & "<th>الرصيد</th>"
    html = html & "<th>متوسط التكلفة</th>"
    html = html & "</tr></thead><tbody>"
    
    ' رصيد أول المدة
    html = html & "<tr style='background: #e8f4f8; font-weight: bold;'>"
    html = html & "<td>" & Format(fromDateVal, "yyyy/mm/dd") & "</td>"
    html = html & "<td>-</td>"
    html = html & "<td>رصيد أول المدة</td>"
    html = html & "<td>-</td>"
    html = html & "<td>-</td>"
    html = html & "<td>" & Format(openingQty, "#,##0.00") & "</td>"
    html = html & "<td>" & Format(avgCost, "#,##0.00") & "</td>"
    html = html & "</tr>"
    
    ' جمع الحركات وترتيبها
    Dim transactions As Collection
    Set transactions = New Collection
    Dim transData As Variant
    Dim j As Long
    Dim inserted As Boolean
    
    For i = 1 To tbl.ListRows.count
        If UCase(Trim(tbl.ListRows(i).Range(4).Value)) = UCase(Trim(productCode)) Then
            If IsDate(tbl.ListRows(i).Range(2).Value) Then
                transDate = tbl.ListRows(i).Range(2).Value
                If transDate >= fromDateVal And transDate <= toDateVal Then
                    Dim itemData(1 To 4) As Variant
                    itemData(1) = transDate
                    itemData(2) = CStr(tbl.ListRows(i).Range(11).Value)
                    itemData(3) = CStr(tbl.ListRows(i).Range(3).Value)
                    If IsNumeric(tbl.ListRows(i).Range(6).Value) Then
                        itemData(4) = CDbl(tbl.ListRows(i).Range(6).Value)
                    Else
                        itemData(4) = 0
                    End If
                    
                    ' إدراج مرتب حسب التاريخ
                    inserted = False
                    For j = 1 To transactions.count
                        If transDate < transactions(j)(1) Then
                            transactions.Add itemData, , j
                            inserted = True
                            Exit For
                        End If
                    Next j
                    If Not inserted Then
                        transactions.Add itemData
                    End If
                End If
            End If
        End If
    Next i
    
    ' عرض الحركات
    For i = 1 To transactions.count
        transData = transactions(i)
        
        If UCase(transData(3)) = "وارد" Then
            runningBalance = runningBalance + transData(4)
            inQty = inQty + transData(4)
            html = html & "<tr>"
            html = html & "<td>" & Format(transData(1), "yyyy/mm/dd") & "</td>"
            html = html & "<td>" & transData(2) & "</td>"
            html = html & "<td>" & transData(3) & "</td>"
            html = html & "<td>" & Format(transData(4), "#,##0.00") & "</td>"
            html = html & "<td>-</td>"
            html = html & "<td>" & Format(runningBalance, "#,##0.00") & "</td>"
            html = html & "<td>" & Format(avgCost, "#,##0.00") & "</td>"
            html = html & "</tr>"
        ElseIf UCase(transData(3)) = "صادر" Then
            runningBalance = runningBalance - transData(4)
            outQty = outQty + transData(4)
            html = html & "<tr>"
            html = html & "<td>" & Format(transData(1), "yyyy/mm/dd") & "</td>"
            html = html & "<td>" & transData(2) & "</td>"
            html = html & "<td>" & transData(3) & "</td>"
            html = html & "<td>-</td>"
            html = html & "<td>" & Format(transData(4), "#,##0.00") & "</td>"
            html = html & "<td>" & Format(runningBalance, "#,##0.00") & "</td>"
            html = html & "<td>" & Format(avgCost, "#,##0.00") & "</td>"
            html = html & "</tr>"
        End If
    Next i
    
    balanceQty = openingQty + inQty - outQty
    stockValue = balanceQty * avgCost
    
    html = html & "</tbody>"
    html = html & "<tfoot>"
    html = html & "<tr><td colspan='3'><strong>الإجمالي</strong></td>"
    html = html & "<td><strong>" & Format(inQty, "#,##0.00") & "</strong></td>"
    html = html & "<td><strong>" & Format(outQty, "#,##0.00") & "</strong></td>"
    html = html & "<td><strong>" & Format(balanceQty, "#,##0.00") & "</strong></td>"
    html = html & "<td><strong>" & Format(avgCost, "#,##0.00") & "</strong></td></tr>"
    html = html & "</tfoot>"
    html = html & "</table>"
    
    ' الملخص
    html = html & "<div class='summary'>"
    html = html & "<h2>ملخص الصنف</h2>"
    html = html & "<p><strong>رصيد أول المدة:</strong> " & Format(openingQty, "#,##0.00") & "</p>"
    html = html & "<p><strong>إجمالي الوارد:</strong> " & Format(inQty, "#,##0.00") & "</p>"
    html = html & "<p><strong>إجمالي الصادر:</strong> " & Format(outQty, "#,##0.00") & "</p>"
    html = html & "<p><strong>الرصيد الحالي:</strong> " & Format(balanceQty, "#,##0.00") & "</p>"
    html = html & "<p><strong>متوسط التكلفة:</strong> " & Format(avgCost, "#,##0.00") & " ريال</p>"
    html = html & "<p><strong>قيمة المخزون:</strong> " & Format(stockValue, "#,##0.00") & " ريال</p>"
    html = html & "</div>"
    
    html = html & "</div>" & GetHTMLFooter
    
    SaveAndOpenHTML html, "ItemCard_" & productCode
End Sub



