productRepository = $productRepository; $this->logger = $logger; } /** * Add variables before filtering */ public function beforeFilter($subject, $value) { if (!$this->costVariablesAdded) { // Get existing variables $variables = []; if (method_exists($subject, 'getVariables')) { $variables = $subject->getVariables(); } else { // Fallback to reflection try { $reflection = new \ReflectionObject($subject); $propNames = ['_templateVars', 'templateVars', 'variables']; // Common property names foreach ($propNames as $propName) { if ($reflection->hasProperty($propName)) { $prop = $reflection->getProperty($propName); $prop->setAccessible(true); $variables = $prop->getValue($subject); break; } } } catch (\Exception $e) { $this->logger->info('FilterPlugin: Could not access variables: ' . $e->getMessage()); } } if (isset($variables['order']) && $variables['order'] instanceof Order) { $this->logger->info('FilterPlugin: Adding cost variables for order ' . $variables['order']->getIncrementId()); $order = $variables['order']; $itemsHtml = ''; $totalCost = 0; foreach ($order->getAllVisibleItems() as $item) { try { $product = $this->productRepository->getById($item->getProductId()); $cost = (float)($product->getCost() ?: $product->getData('cost') ?: 0); } catch (\Exception $e) { $cost = 0; } $qty = (float) $item->getQtyOrdered(); $rowTotal = $cost * $qty; $totalCost += $rowTotal; $itemsHtml .= ''; $itemsHtml .= '' . htmlspecialchars($item->getName()) . ''; $itemsHtml .= '' . htmlspecialchars($item->getSku()) . ''; $itemsHtml .= '' . (int)$qty . ''; $itemsHtml .= '' . $this->formatPrice($cost, $order) . ''; $itemsHtml .= '' . $this->formatPrice($rowTotal, $order) . ''; $itemsHtml .= ''; } $shippingCost = $order->getShippingAmount() ?: 0; // Add new variables to the array $variables['items_html'] = $itemsHtml; $variables['order_subtotal_cost'] = $this->formatPrice($totalCost, $order); $variables['order_total_cost'] = $this->formatPrice($totalCost + $shippingCost, $order); $variables['shipping_cost'] = $this->formatPrice($shippingCost, $order); $variables['raw_subtotal_cost'] = $totalCost; $variables['raw_total_cost'] = $totalCost + $shippingCost; $variables['raw_shipping_cost'] = $shippingCost; // Set the updated variables array $subject->setVariables($variables); $this->costVariablesAdded = true; $this->logger->info('FilterPlugin: Cost variables added successfully'); } } return [$value]; } protected function formatPrice($price, $order) { return $order->getOrderCurrency()->formatPrecision($price, 2, [], false); } }