' ============================================
' frmSader - حركة الصادر
' ============================================

Option Explicit
Private cartItems As Collection
Private currentInvoiceNum As String
Private currentCustomerName As String
Private isEditMode As Boolean
Private editInvoiceNum As String

Private Sub UserForm_Initialize()
    Set cartItems = New Collection
    isEditMode = False
    editInvoiceNum = ""
    txtInvoiceNumOut.Value = GetNewInvoiceOutNumber
    currentInvoiceNum = txtInvoiceNumOut.Value
    LoadProductCodes
    LoadCustomers
    LoadTransactions
    ClearFields
End Sub

' تحميل رموز المنتجات
Private Sub LoadProductCodes()
    Dim tbl As ListObject
    Dim i As Long
    
    comProductCodeout.Clear
    Set tbl = GetTableByName("tlbproduct")
    If tbl Is Nothing Then Exit Sub
    
    For i = 1 To tbl.ListRows.count
        If UCase(Trim(tbl.ListRows(i).Range(7).Value)) = "نشط" Then
            comProductCodeout.AddItem tbl.ListRows(i).Range(1).Value
        End If
    Next i
End Sub

' تحميل أسماء المنتجات
Private Sub LoadProductNames()
    Dim tbl As ListObject
    Dim i As Long
    
    comProductNameOut.Clear
    Set tbl = GetTableByName("tlbproduct")
    If tbl Is Nothing Then Exit Sub
    
    For i = 1 To tbl.ListRows.count
        If UCase(Trim(tbl.ListRows(i).Range(7).Value)) = "نشط" Then
            comProductNameOut.AddItem tbl.ListRows(i).Range(2).Value
        End If
    Next i
End Sub

' تحميل العملاء
Private Sub LoadCustomers()
    Dim tbl As ListObject
    Dim i As Long
    
    comCustomrName.Clear
    Set tbl = GetTableByName("tlbcustomer")
    If tbl Is Nothing Then Exit Sub
    
    For i = 1 To tbl.ListRows.count
        comCustomrName.AddItem tbl.ListRows(i).Range(2).Value
    Next i
End Sub

' عند اختيار رمز المنتج
Private Sub comProductCodeout_Change()
    If comProductCodeout.ListIndex >= 0 Then
        Dim productData As Variant
        productData = GetProductByCode(comProductCodeout.Value)
        If Not IsEmpty(productData) Then
            comProductNameOut.Value = productData(2)
            comunitsOut.Value = productData(3)
            txtSalepriceOut.Value = productData(5)
            lblQtyStock.Caption = Format(GetCurrentStock(comProductCodeout.Value), "#,##0.00")
            CalculateTotalAmount
        End If
    End If
End Sub

' عند اختيار اسم المنتج
Private Sub comProductNameOut_Change()
    If comProductNameOut.ListIndex >= 0 Then
        Dim productData As Variant
        productData = GetProductByName(comProductNameOut.Value)
        If Not IsEmpty(productData) Then
            comProductCodeout.Value = productData(1)
            comunitsOut.Value = productData(3)
            txtSalepriceOut.Value = productData(5)
            lblQtyStock.Caption = Format(GetCurrentStock(CStr(productData(1))), "#,##0.00")
            CalculateTotalAmount
        End If
    End If
End Sub

' حساب الإجمالي
Private Sub CalculateTotalAmount()
    If IsNumeric(txtQtyOut.Value) And IsNumeric(txtSalepriceOut.Value) Then
        lbltotalAmount.Caption = Format(CDbl(txtQtyOut.Value) * CDbl(txtSalepriceOut.Value), "#,##0.00")
    Else
        lbltotalAmount.Caption = "0.00"
    End If
End Sub

Private Sub txtQtyOut_Change()
    CalculateTotalAmount
    
    ' التحقق من المخزون
    If IsNumeric(txtQtyOut.Value) Then
        Dim currentStock As Double
        currentStock = GetCurrentStock(comProductCodeout.Value)
        If CDbl(txtQtyOut.Value) > currentStock Then
            MsgBox "الكمية المطلوبة أكبر من المخزون المتاح!", vbExclamation
        End If
    End If
End Sub

Private Sub txtSalepriceOut_Change()
    CalculateTotalAmount
End Sub

' إضافة عميل جديد
Private Sub btnAddCustomer_Click()
    frmCustomer.Show
    LoadCustomers
End Sub

' إضافة صنف لعربة التسوق
Private Sub cmdAddtoCar_Click()
    ' التحقق من اكتمال البيانات قبل أي تحويل (لتجنب خطأ Type mismatch)
    If Trim(comProductCodeout.Value & "") = "" Or Trim(comProductNameOut.Value & "") = "" Then
        MsgBox "يرجى اختيار منتج من القائمة.", vbExclamation, "استكمال البيانات"
        Exit Sub
    End If
    
    If Trim(txtQtyOut.Value & "") = "" Then
        MsgBox "يرجى إدخال الكمية.", vbExclamation, "استكمال البيانات"
        txtQtyOut.SetFocus
        Exit Sub
    End If
    
    If Trim(txtSalepriceOut.Value & "") = "" Then
        MsgBox "يرجى إدخال سعر البيع.", vbExclamation, "استكمال البيانات"
        txtSalepriceOut.SetFocus
        Exit Sub
    End If
    
    ' التحقق من أن القيم رقمية وصحيحة
    If Not IsNumeric(Replace(txtQtyOut.Value, ",", ".")) Then
        MsgBox "يرجى إدخال كمية صحيحة (أرقام فقط).", vbExclamation, "استكمال البيانات"
        txtQtyOut.SetFocus
        Exit Sub
    End If
    
    Dim qtyVal As Double
    Dim priceVal As Double
    On Error Resume Next
    qtyVal = CDbl(Replace(Trim(txtQtyOut.Value), ",", "."))
    priceVal = CDbl(Replace(Trim(txtSalepriceOut.Value), ",", "."))
    On Error GoTo 0
    
    If qtyVal <= 0 Then
        MsgBox "يرجى إدخال كمية أكبر من صفر.", vbExclamation, "استكمال البيانات"
        txtQtyOut.SetFocus
        Exit Sub
    End If
    
    If priceVal <= 0 Then
        MsgBox "يرجى إدخال سعر بيع صحيح وأكبر من صفر.", vbExclamation, "استكمال البيانات"
        txtSalepriceOut.SetFocus
        Exit Sub
    End If
    
    ' التحقق من المخزون
    Dim currentStock As Double
    currentStock = GetCurrentStock(comProductCodeout.Value)
    If qtyVal > currentStock Then
        MsgBox "الكمية المطلوبة أكبر من المخزون المتاح!", vbExclamation
        Exit Sub
    End If
    
    ' إضافة للعربة - قراءة البيانات مباشرة من الجدول مثل frmProduct
    Dim productData As Variant
    productData = GetProductByCode(comProductCodeout.Value)
    
    If IsEmpty(productData) Then
        MsgBox "خطأ في قراءة بيانات المنتج", vbExclamation
        Exit Sub
    End If
    
    Dim itemData(1 To 5) As Variant
    itemData(1) = productData(1)  ' رمز الصنف من الجدول مباشرة
    itemData(2) = productData(2)  ' اسم الصنف من الجدول مباشرة
    itemData(3) = qtyVal
    itemData(4) = priceVal
    itemData(5) = qtyVal * priceVal
    
    cartItems.Add itemData
    
    ' تحديث ListBox2 (عربة التسوق)
    UpdateCartListView
    
    ' الاحتفاظ برقم الفاتورة والعميل
    currentInvoiceNum = txtInvoiceNumOut.Value
    currentCustomerName = comCustomrName.Value
    
    ' مسح الحقول
    comProductCodeout.Value = ""
    comProductNameOut.Value = ""
    comunitsOut.Value = ""
    txtQtyOut.Value = ""
    txtSalepriceOut.Value = ""
    lblQtyStock.Caption = "0.00"
    lbltotalAmount.Caption = "0.00"
End Sub

' تحديث عربة التسوق (ListBox2)
Private Sub UpdateCartListView()
    Dim i As Long
    Dim total As Double
    Dim r As Long
    
    ListBox2.Clear
    ListBox2.ColumnCount = 5
    ListBox2.ColumnWidths = "70;120;50;70;70"
    
    ' صف العناوين
    ListBox2.AddItem "رمز الصنف"
    r = ListBox2.ListCount - 1
    ListBox2.List(r, 1) = "اسم الصنف"
    ListBox2.List(r, 2) = "الكمية"
    ListBox2.List(r, 3) = "السعر"
    ListBox2.List(r, 4) = "الإجمالي"
    
    total = 0
    For i = 1 To cartItems.count
        Dim itemData As Variant
        itemData = cartItems(i)
        
        ListBox2.AddItem itemData(1)
        r = ListBox2.ListCount - 1
        ListBox2.List(r, 1) = itemData(2)
        ListBox2.List(r, 2) = Format(itemData(3), "#,##0.00")
        ListBox2.List(r, 3) = Format(itemData(4), "#,##0.00")
        ListBox2.List(r, 4) = Format(itemData(5), "#,##0.00")
        
        total = total + itemData(5)
    Next i
End Sub

' حفظ الحركة
Private Sub cmdSaveOut_Click()
    If cartItems.count = 0 Then
        MsgBox "يرجى إضافة أصناف للعربة", vbExclamation
        Exit Sub
    End If
    
    If comCustomrName.Value = "" Then
        MsgBox "يرجى اختيار عميل", vbExclamation
        Exit Sub
    End If
    
    If txtCearteBy.Value = "" Then
        MsgBox "يرجى إدخال اسم الموظف", vbExclamation
        Exit Sub
    End If
    
    Dim transactionNum As String
    Dim i As Long
    Dim tbl As ListObject
    Dim customerCode As String
    
    ' الحصول على كود العميل
    Dim customerData As Variant
    Set tbl = GetTableByName("tlbcustomer")
    If Not tbl Is Nothing Then
        For i = 1 To tbl.ListRows.count
            If UCase(Trim(tbl.ListRows(i).Range(2).Value)) = UCase(Trim(comCustomrName.Value)) Then
                customerCode = tbl.ListRows(i).Range(1).Value
                Exit For
            End If
        Next i
    End If
    
    If isEditMode Then
        ' حذف الحركات القديمة
        DeleteTransactionsByInvoice (editInvoiceNum)
        transactionNum = GetNewTransactionNumber
    Else
        transactionNum = GetNewTransactionNumber
    End If
    
    ' حفظ كل صنف كحركة منفصلة
    Set tbl = GetTableByName("tlbTransaction")
    If tbl Is Nothing Then Exit Sub
    
    For i = 1 To cartItems.count
        Dim itemData As Variant
        itemData = cartItems(i)
        
        ' التحقق من المخزون مرة أخرى
        Dim currentStock As Double
        currentStock = GetCurrentStock(CStr(itemData(1)))
        If itemData(3) > currentStock Then
            MsgBox "الكمية المطلوبة للصنف " & itemData(2) & " أكبر من المخزون المتاح!", vbExclamation
            Exit Sub
        End If
        
        Dim newRow As ListRow
        Set newRow = tbl.ListRows.Add
        newRow.Range(1).Value = transactionNum
        newRow.Range(2).Value = Date
        newRow.Range(3).Value = "صادر"
        newRow.Range(4).Value = itemData(1)
        newRow.Range(5).Value = itemData(2)
        newRow.Range(6).Value = itemData(3)
        newRow.Range(7).Value = itemData(4)
        newRow.Range(8).Value = itemData(5)
        newRow.Range(9).Value = customerCode
        newRow.Range(10).Value = comCustomrName.Value
        newRow.Range(11).Value = txtInvoiceNumOut.Value
        newRow.Range(12).Value = txtCearteBy.Value
        newRow.Range(13).Value = txtNots.Value
        
        ' تحديث المخزون
        UpdateInventory CStr(itemData(1)), 0, CDbl(itemData(3)), 0, CDbl(itemData(4))
    Next i
    
    MsgBox "تم حفظ الحركة بنجاح", vbInformation
    
    ' السؤال عن الطباعة
    Dim response As VbMsgBoxResult
    response = MsgBox("هل تريد طباعة الفاتورة؟", vbYesNo + vbQuestion, "طباعة الفاتورة")
    
    If response = vbYes Then
        GenerateInvoiceOut txtInvoiceNumOut.Value
    End If
    
    ' إعادة تعيين
    Set cartItems = New Collection
    isEditMode = False
    editInvoiceNum = ""
    txtInvoiceNumOut.Value = GetNewInvoiceOutNumber
    currentInvoiceNum = txtInvoiceNumOut.Value
    ClearFields
    UpdateCartListView
    LoadTransactions
End Sub

' حذف حركات الفاتورة
Private Sub DeleteTransactionsByInvoice(invoiceNum As String)
    Dim tbl As ListObject
    Dim i As Long
    
    Set tbl = GetTableByName("tlbTransaction")
    If tbl Is Nothing Then Exit Sub
    
    For i = tbl.ListRows.count To 1 Step -1
        If UCase(Trim(tbl.ListRows(i).Range(11).Value)) = UCase(Trim(invoiceNum)) Then
            ' استرجاع المخزون قبل الحذف
            Dim productCode As String
            Dim qty As Double
            productCode = tbl.ListRows(i).Range(4).Value
            qty = CDbl(tbl.ListRows(i).Range(6).Value)
            UpdateInventory CStr(productCode), CDbl(qty), 0 ' استرجاع الكمية
            
            tbl.ListRows(i).Delete
        End If
    Next i
End Sub

' مسح الحقول
Private Sub ClearFields()
    comProductCodeout.Value = ""
    comProductNameOut.Value = ""
    comunitsOut.Value = ""
    txtQtyOut.Value = ""
    txtSalepriceOut.Value = ""
    txtCearteBy.Value = ""
    txtNots.Value = ""
    lblQtyStock.Caption = "0.00"
    lbltotalAmount.Caption = "0.00"
End Sub

' تحميل الحركات (ListBox1)
Private Sub LoadTransactions()
    Dim tbl As ListObject
    Dim i As Long
    Dim invoiceNumbers As Object
    Dim invoiceNum As String
    Dim key As Variant
    Dim r As Long
    
    ListBox1.Clear
    ListBox1.ColumnCount = 6
    ListBox1.ColumnWidths = "80;70;120;60;70;80"
    
    ' صف العناوين
    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("tlbTransaction")
    If tbl Is Nothing Then Exit Sub
    
    Set invoiceNumbers = CreateObject("Scripting.Dictionary")
    
    ' جمع بيانات الفواتير
    For i = 1 To tbl.ListRows.count
        If UCase(tbl.ListRows(i).Range(3).Value) = "صادر" Then
            invoiceNum = tbl.ListRows(i).Range(11).Value
            If Not invoiceNumbers.exists(invoiceNum) Then
                invoiceNumbers.Add invoiceNum, Array(tbl.ListRows(i).Range(2).Value, tbl.ListRows(i).Range(10).Value, 0, 0, tbl.ListRows(i).Range(12).Value)
            End If
            
            Dim invoiceData As Variant
            invoiceData = invoiceNumbers(invoiceNum)
            invoiceData(2) = invoiceData(2) + 1 ' عدد الأصناف
            invoiceData(3) = invoiceData(3) + CDbl(tbl.ListRows(i).Range(8).Value) ' الإجمالي
            invoiceNumbers(invoiceNum) = invoiceData
        End If
    Next i
    
    ' عرض الفواتير
    For Each key In invoiceNumbers.keys
        invoiceData = invoiceNumbers(key)
        ListBox1.AddItem key
        r = ListBox1.ListCount - 1
        ListBox1.List(r, 1) = Format(invoiceData(0), "yyyy/mm/dd")
        ListBox1.List(r, 2) = invoiceData(1)
        ListBox1.List(r, 3) = invoiceData(2)
        ListBox1.List(r, 4) = Format(invoiceData(3), "#,##0.00")
        ListBox1.List(r, 5) = invoiceData(4)
    Next key
End Sub

' البحث عن حركة
Private Sub cmdSearchOut_Click()
    Dim invoiceNum As String
    invoiceNum = InputBox("أدخل رقم الفاتورة:", "بحث عن حركة صادر")
    
    If invoiceNum = "" Then Exit Sub
    
    LoadTransactionByInvoice invoiceNum
End Sub

' تحميل حركة برقم الفاتورة
Private Sub LoadTransactionByInvoice(invoiceNum As String)
    Dim tbl As ListObject
    Dim i As Long
    Dim firstRow As Boolean
    
    Set tbl = GetTableByName("tlbTransaction")
    If tbl Is Nothing Then Exit Sub
    
    Set cartItems = New Collection
    firstRow = True
    
    For i = 1 To tbl.ListRows.count
        If UCase(Trim(tbl.ListRows(i).Range(11).Value)) = UCase(Trim(invoiceNum)) Then
            If UCase(tbl.ListRows(i).Range(3).Value) = "صادر" Then
                If firstRow Then
                    txtInvoiceNumOut.Value = invoiceNum
                    comCustomrName.Value = tbl.ListRows(i).Range(10).Value
                    txtCearteBy.Value = tbl.ListRows(i).Range(12).Value
                    txtNots.Value = tbl.ListRows(i).Range(13).Value
                    firstRow = False
                End If
                
                ' إضافة للعربة
                Dim itemData(1 To 5) As Variant
                itemData(1) = tbl.ListRows(i).Range(4).Value
                itemData(2) = tbl.ListRows(i).Range(5).Value
                itemData(3) = CDbl(tbl.ListRows(i).Range(6).Value)
                itemData(4) = CDbl(tbl.ListRows(i).Range(7).Value)
                itemData(5) = CDbl(tbl.ListRows(i).Range(8).Value)
                cartItems.Add itemData
            End If
        End If
    Next i
    
    If cartItems.count > 0 Then
        isEditMode = True
        editInvoiceNum = invoiceNum
        UpdateCartListView
        MsgBox "تم تحميل الحركة", vbInformation
    Else
        MsgBox "لم يتم العثور على الحركة", vbExclamation
    End If
End Sub

' تعديل حركة
Private Sub cmdEditOut_Click()
    If Not isEditMode Then
        MsgBox "يرجى البحث عن حركة أولاً", vbExclamation
        Exit Sub
    End If
    
    ' حفظ كحركة جديدة
    cmdSaveOut_Click
End Sub

' طباعة فاتورة
Private Sub cmdPrintInvoiceOut_Click()
    If ListBox1.ListIndex < 0 Or ListBox1.ListIndex = 0 Then
        MsgBox "يرجى اختيار فاتورة للطباعة", vbExclamation
        Exit Sub
    End If
    
    GenerateInvoiceOut ListBox1.List(ListBox1.ListIndex, 0)
End Sub

' تحديث
Private Sub cmdRefresh_Click()
    LoadProductCodes
    LoadProductNames
    LoadCustomers
    LoadTransactions
End Sub


