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 .= '