<?php

namespace BWDK\Admin;

use BWDK\Support\BwdkOrderNote;

if (!defined('ABSPATH')) {
    exit;
}

class OrderNoteStyles
{
    public function register(): void
    {
        add_filter('woocommerce_order_note_class', [$this, 'filter_note_class'], 10, 2);
        add_action('woocommerce_new_order_note', [$this, 'tag_new_note'], 10, 2);
        add_action('admin_enqueue_scripts', [$this, 'enqueue_assets']);
    }

    public function filter_note_class(array $classes, $note): array
    {
        if (BwdkOrderNote::should_style($note)) {
            $classes[] = 'bwdk-order-note';
        }

        return $classes;
    }

    public function tag_new_note(int $comment_id, $order): void
    {
        $comment = get_comment($comment_id);
        if (!$comment instanceof \WP_Comment) {
            return;
        }

        if (BwdkOrderNote::content_matches((string) $comment->comment_content)) {
            BwdkOrderNote::mark_note($comment_id);
        }
    }

    public function enqueue_assets(): void
    {
        $screen = get_current_screen();
        if (!$screen || (strpos($screen->id, 'shop_order') === false && strpos($screen->id, 'woocommerce_page_wc-orders') === false)) {
            return;
        }

        if (!defined('BWDK_ADMIN_CSS') || !defined('BWDK_ADMIN_IMG')) {
            return;
        }

        wp_enqueue_style(
            'bwdk-order-notes',
            BWDK_ADMIN_CSS . 'bwdk-order-notes.css',
            [],
            '1.0.0'
        );

        $logo_url = BWDK_ADMIN_IMG . 'BWDKLogo.svg';
        $inline_css = sprintf(
            ':root { --bwdk-note-logo: url(%s); }',
            wp_json_encode(esc_url($logo_url), JSON_UNESCAPED_SLASHES)
        );
        wp_add_inline_style('bwdk-order-notes', $inline_css);
    }
}
