|
| 1 | +<?php |
| 2 | + |
| 3 | +declare(strict_types=1); |
| 4 | + |
| 5 | +namespace Cdek\UI { |
| 6 | + |
| 7 | + use Cdek\Config; |
| 8 | + use Cdek\Helpers\Logger; |
| 9 | + use Cdek\Helpers\UI; |
| 10 | + use Cdek\MetaKeys; |
| 11 | + use WC_Order_Item; |
| 12 | + use WC_Product; |
| 13 | + use WC_Order; |
| 14 | + |
| 15 | + class AdminOrderProductFields |
| 16 | + { |
| 17 | + public function __invoke(int $itemId, ?WC_Order_Item $item, ?WC_Product $product): void |
| 18 | + { |
| 19 | + if ($item === null || $product === null) { |
| 20 | + return; |
| 21 | + } |
| 22 | + |
| 23 | + $order = $item->get_order(); |
| 24 | + |
| 25 | + if (!$order instanceof WC_Order) { |
| 26 | + return; |
| 27 | + } |
| 28 | + |
| 29 | + if (!$this->checkShipping($order->get_shipping_methods())) { |
| 30 | + return; |
| 31 | + } |
| 32 | + |
| 33 | + try { |
| 34 | + $jewel_uin_value = wc_get_order_item_meta($itemId, MetaKeys::JEWEL_UIN); |
| 35 | + } catch (\Exception $e) { |
| 36 | + Logger::warning( |
| 37 | + sprintf( |
| 38 | + 'Failed to get UIN for item %d: %s', |
| 39 | + $itemId, |
| 40 | + $e->getMessage() |
| 41 | + ) |
| 42 | + ); |
| 43 | + $jewel_uin_value = null; |
| 44 | + } |
| 45 | + |
| 46 | + echo '<br/>'; |
| 47 | + |
| 48 | + if (empty($jewel_uin_value)){ |
| 49 | + echo wc_render_action_buttons( |
| 50 | + [ |
| 51 | + [ |
| 52 | + 'action' => Config::DELIVERY_NAME . "-show_uin", |
| 53 | + 'url' => '#', |
| 54 | + 'name' => __('Add jewel UIN', 'cdekdelivery'), |
| 55 | + ] |
| 56 | + ] |
| 57 | + ); |
| 58 | + } |
| 59 | + |
| 60 | + echo sprintf( |
| 61 | + '<div class="%s-uin-input-container%s" data-id="%s">', |
| 62 | + Config::DELIVERY_NAME, |
| 63 | + empty($jewel_uin_value) ? ' hidden' : '', |
| 64 | + $itemId, |
| 65 | + ); |
| 66 | + |
| 67 | + woocommerce_wp_text_input( |
| 68 | + [ |
| 69 | + 'id' => Config::DELIVERY_NAME . "_jewel_uin_$itemId", |
| 70 | + 'class' => Config::DELIVERY_NAME . '-jewel-uin', |
| 71 | + 'label' => __('UIN: ', 'cdekdelivery'), |
| 72 | + 'value' => $jewel_uin_value, |
| 73 | + ] |
| 74 | + ); |
| 75 | + |
| 76 | + echo wc_render_action_buttons( |
| 77 | + [ |
| 78 | + [ |
| 79 | + 'action' => Config::DELIVERY_NAME . '-save_uin', |
| 80 | + 'url' => '#', |
| 81 | + 'name' => __('Save', 'cdekdelivery'), |
| 82 | + ] |
| 83 | + ] |
| 84 | + ); |
| 85 | + echo '</div>'; |
| 86 | + |
| 87 | + $this->enqueueScript(); |
| 88 | + } |
| 89 | + |
| 90 | + private function checkShipping(array $shipping_methods): bool |
| 91 | + { |
| 92 | + foreach ($shipping_methods as $shipping_method) { |
| 93 | + if (strpos($shipping_method->get_method_id(), Config::DELIVERY_NAME) !== false) { |
| 94 | + return true; |
| 95 | + } |
| 96 | + } |
| 97 | + |
| 98 | + return false; |
| 99 | + } |
| 100 | + |
| 101 | + private function enqueueScript(): void |
| 102 | + { |
| 103 | + UI::enqueueScript('cdek-order-item', 'cdek-order-item', true, false, true); |
| 104 | + } |
| 105 | + } |
| 106 | +} |
0 commit comments