<?php
class OrderController
{
    private $order;

    function __construct()
    {
        if (is_admin()) {
            $this->init();
        }
    }

    public function init()
    {
        add_action( 'woocommerce_admin_order_data_after_order_details',  [$this, 'get_order_data'], 60, 1 );

        add_filter( 'woocommerce_enable_order_notes_field', [$this, 'show_notify'], 60, 1 );
    }

    public function get_order_data($order){
        $this->order = $order;
    }

    public function show_notify(){

        // 檢查 order 是否存在
        if (!$this->order || !is_a($this->order, 'WC_Order')) {
            return true;
        }
        try {
            $order_id = $this->order->get_id();
            $cvs_address = get_post_meta($order_id, 'boxful_cvs_store_address', true);
            $cvs_store_id = get_post_meta($order_id, 'boxful_cvs_store_id', true);
            $cvs_store_name = get_post_meta($order_id, 'boxful_cvs_store_name', true);
            $shipping_method = $this->order->get_shipping_method();
            if (!empty($cvs_store_id)) {
                echo '<h3>超取門市資訊</h3>';
                echo '<p>';
                echo '服務超商：' . esc_html($shipping_method) . '</br>';
                echo '取件地址：' . esc_html($cvs_address) . '</br>';
                echo '取件店鋪：' . esc_html($cvs_store_name) . '</br>';
                echo '取件店號：' . esc_html($cvs_store_id) . '</br>';
                echo '</p>';
            }
        } catch (Exception $e) {
            error_log('Boxful Fulfillment Error: ' . $e->getMessage());
        }
        return true;
    }
}

new OrderController();