<?php

namespace Fitsmart\PaypalParcels;

use Monolog\Handler\StreamHandler;
use Monolog\Logger;

class Plugin
{
    const LOG_FILE_NAME = 'paypal_parcels_registration.log';

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

    public static function bootstrap(): void
    {
        $upload_dir = wp_upload_dir()['basedir'];
        $log_file = trailingslashit($upload_dir) . self::LOG_FILE_NAME;

        $logger = new Logger('parcels');
        $logger->pushHandler(new StreamHandler($log_file, Logger::WARNING));

        $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_paypal'], 10, 2);
    }

    public function transfer_tracking_number_from_note_to_paypal($noteId, $order): void
    {
        $orderId = $order->get_id();
        $noteStd = wc_get_order_note($noteId);
        if (!$noteStd) {
            return;
        }

        if (!in_array($order->get_payment_method(), ConfigHelper::getPayPalMethods())) {
            return;
        }

        $transactionId = $order->get_transaction_id();
        if (!$transactionId) {
            return;
        }

        $trackingData = $this->parser->parse($noteStd->content, ConfigHelper::getParseData());
        if (!$trackingData) {
            return;
        }
        if ($trackingData['courier_code'] == ConfigHelper::getPayPalOtherCarrier())
        {
            $trackingData['carrier_name_other'] = '';
        }



        $trackingData['transaction_id'] = $transactionId;

        $this->apiClient->create_tracking($orderId, $trackingData);
    }
}