<?php
function getInvoiceItems($conn, $invoice_id, $invoice) {
    $invoice_items = [];
    
    // First try to get items from invoice_items table if it exists
    $items_query = "SELECT * FROM invoice_items WHERE invoice_id = ? ORDER BY id ASC";
    
    try {
        $items_stmt = $conn->prepare($items_query);
        if ($items_stmt) {
            $items_stmt->bind_param('i', $invoice_id);
            $items_stmt->execute();
            $items_result = $items_stmt->get_result();
            
            if ($items_result && $items_result->num_rows > 0) {
                while ($row = $items_result->fetch_assoc()) {
                    $invoice_items[] = [
                        'name' => $row['name'],
                        'description' => $row['description'],
                        'quantity' => $row['quantity'],
                        'price' => $row['price'],
                        'total' => $row['quantity'] * $row['price']
                    ];
                }
                return $invoice_items;
            }
            $items_stmt->close();
        }
    } catch (mysqli_sql_exception $e) {
        // Table doesn't exist, let's continue to the fallback
    }
    
    // Fallback to using fields from the main invoice table
    $item_name = $invoice['name'] ?? 'Shipping Services';
    $item_description = $invoice['description'] ?? 'Services for shipment ' . ($invoice['file_number'] ?? '');
    $item_quantity = $invoice['quantity'] ?? 1;
    $item_price = $invoice['price'] ?? $invoice['total_amount'] ?? 0;
    
    $invoice_items[] = [
        'name' => $item_name,
        'description' => $item_description,
        'quantity' => $item_quantity,
        'price' => $item_price,
        'total' => $item_quantity * $item_price
    ];
    
    return $invoice_items;
}
?>