<?php

namespace Fitsmart\ParcelPanel;

class Plugin
{
    public const COURIER_PATTERNS = [
        // Huboo with keys as courier acronym
        'deutsche-post' => '~Tracking:\s*([A-Z0-9]+).*deutschepost\.com~i',
        'hermes-uk' =>     '~Tracking:\s*([A-Z0-9]+).*evri\.com~i',
        'royal-mail' =>    '~Tracking:\s*([A-Z0-9]+).*royalmail\.com~i',
        'postnl-3s' =>     '~Tracking:\s*([A-Z0-9]+).*postnl\.nl~i',
        'fedex' =>         '~Tracking:\s*([A-Z0-9]+).*fedex\.com~i',
        'dpd' =>           '~Tracking:\s*([A-Z0-9]+).*dpd\.de~i',
        'gls' =>           '~Tracking:\s*([A-Z0-9]+).*gls-group\.eu~i',
        // Universal for Huboo, without courier
        '~Tracking:\s*([A-Z0-9]+)\s*Url~i',
        // ShipBob, without courier acronym as a key
        '~\([^)]+mailingtechnology\.com[^)]+tn=([A-Z0-9]+)[^)]*\)~',
        '~\([^)]+ups\.com[^)]+trackNums=([A-Z0-9]+)[^)]*\)~',
    ];


    public function __construct(
        private ApiClient $apiClient,
        private TrackingNoteParser $parser,
    ) {
    }

    public static function bootstrap(): void
    {
        $logger = new Logger();
        $apiClient = new ApiClient($logger);
        $parser = new TrackingNoteParser();

        $plugin = new self($apiClient, $parser);
        $plugin->register_hooks();
    }

    public function register_hooks(): void
    {
        add_action('woocommerce_order_note_added', [$this, 'transfer_tracking_number_from_note_to_parcelpanel'], 10, 2);
    }

    public function transfer_tracking_number_from_note_to_parcelpanel($note_id, $order): void
    {
        $order_id = $order->get_id();
        $note_std = wc_get_order_note($note_id);
        if (!$note_std) {
            return;
        }

        $tracking_data = $this->parser->parse($note_std->content, self::COURIER_PATTERNS);
        if (!$tracking_data) {
            return;
        }

        // $tracking_std = $this->apiClient->get_tracking_by_order_id($order_id);
        // if (!empty($tracking_std->data)) {
        //     return;
        // }

        $this->apiClient->create_tracking($order_id, $tracking_data);
    }
}