<?php

namespace Storeplugin\PDFInvoice\Framework\Forms;

defined('ABSPATH') || exit;

use Storeplugin\PDFInvoice\Framework\Abstracts\AbstractMeta;
use Storeplugin\PDFInvoice\Framework\Contracts\MetaInterface;
use Storeplugin\PDFInvoice\Framework\Rest\OrderMetaRegistrar;

/**
 * WooCommerce order meta box implementation (HPOS-compatible).
 *
 * Uses $order->get_meta() / $order->update_meta_data() + $order->save()
 * and hooks into woocommerce_process_shop_order_meta.
 *
 * @package Storeplugin\PDFInvoice\Framework\Forms
 * @since 1.0.0
 */
class OrderMeta extends AbstractMeta
{
    /**
     * Create a new order metabox instance.
     *
     * @param string      $id          Unique metabox ID
     * @param string      $title       Display title
     * @param string      $optionGroup Prefix for form field names (required)
     * @param string      $context     Where the box should show up ('normal', 'side', 'advanced')
     * @param string      $priority    Priority within the context
     *
     * @return MetaInterface
     */
    public static function create(string $id, string $title, string $optionGroup, string $context = 'normal', string $priority = 'default'): MetaInterface
    {
        return new self($id, $title, $optionGroup, [], $context, $priority);
    }

    /**
     * Register WooCommerce order REST support alongside the normal metabox flow.
     *
     * @return void
     */
    public function render(): void
    {
        if (\did_action('rest_api_init')) {
            $this->registerMeta();
        } else {
            \add_action('rest_api_init', [$this, 'registerMeta']);
        }

        parent::render();
    }

    /**
     * Register the order metabox with the WooCommerce REST adapter.
     *
     * @return void
     */
    public function registerMeta(): void
    {
        OrderMetaRegistrar::register($this);
    }

    /**
     * @inheritDoc
     */
    protected function getScreens(): array
    {
        $screens = ['shop_order', 'woocommerce_page_wc-orders'];

        if (function_exists('wc_get_page_screen_id')) {
            $hposScreen = \wc_get_page_screen_id('shop-order');
            if (is_string($hposScreen) && $hposScreen !== '' && !in_array($hposScreen, $screens, true)) {
                $screens[] = $hposScreen;
            }
        }

        return $screens;
    }

    /**
     * @inheritDoc
     */
    protected function getMetaValues($object): array
    {
        $order = $this->resolveOrder($object);
        if (!$order) {
            return [];
        }

        $values = [];
        foreach ($this->getAllFields() as $field) {
            $id = \sanitize_key((string) ($field['id'] ?? ''));
            if ($id === '') { continue; }
            $exists = method_exists($order, 'meta_exists')
                ? $order->meta_exists($id)
                : \metadata_exists('post', $order->get_id(), $id);
            if ($exists) {
                $values[$id] = $order->get_meta($id, true);
            }
        }
        return $values;
    }

    /**
     * Resolve a WP_Post or WC_Order into a WC_Order instance.
     *
     * @param \WP_Post|object $object
     *
     * @return \WC_Order|null
     */
    private function resolveOrder($object)
    {
        if ($object instanceof \WC_Order) {
            return $object;
        }

        if ($object instanceof \WP_Post) {
            return \wc_get_order($object->ID);
        }

        return null;
    }

}
