<?php

declare(strict_types=1);

namespace CloudXM\NFe\Admin\Controllers;

use CloudXM\NFe\Services\NFeQueueService;
use CloudXM\SDK\Support\HasLogger;

/**
 * Admin Notice Controller
 *
 * Displays admin notices based on queue status
 */
class AdminNoticeController
{
    use HasLogger;

    public function __construct(
        private NFeQueueService $queueService
    ) {
        add_action('admin_notices', [$this, 'renderNotices']);
    }

    /**
     * Render admin notices for NFe operations
     */
    public function renderNotices(): void
    {
        if (!$this->isNFeOrderPage()) {
            return;
        }

        $orderId = $this->getOrderIdFromUrl();
        if (!$orderId) {
            return;
        }

        if ($this->queueService->hasPendingTasks($orderId)) {
            $this->renderNotice('info', 
                __('NFe is being processed in the background. You can navigate away and check back later.', 'woocommerce-cloudxm-nfe'),
                false
            );
        }
    }

    /**
     * Check if current page is an NFe order page
     *
     * @return bool
     */
    private function isNFeOrderPage(): bool
    {
        if (!is_admin()) {
            return false;
        }

        $screen = get_current_screen();
        if (!$screen) {
            return false;
        }

        // Check if we're on order edit page
        return in_array($screen->id, ['shop_order', 'woocommerce_page_wc-orders'], true);
    }

    /**
     * Get order ID from current URL
     *
     * @return int|null
     */
    private function getOrderIdFromUrl(): ?int
    {
        if (isset($_GET['post']) && is_numeric($_GET['post'])) {
            return (int) $_GET['post'];
        }

        if (isset($_GET['id']) && is_numeric($_GET['id'])) {
            return (int) $_GET['id'];
        }

        return null;
    }

    /**
     * Render admin notice
     *
     * @param string $type Notice type (success, error, warning, info)
     * @param string $message Notice message
     * @param bool $dismissible Whether notice can be dismissed
     */
    private function renderNotice(string $type, string $message, bool $dismissible = true): void
    {
        $classes = [
            'notice',
            'notice-' . $type,
            'cloudxm-nfe-notice',
        ];

        if ($dismissible) {
            $classes[] = 'is-dismissible';
        }

        echo '<div class="' . implode(' ', $classes) . '">';
        echo '<p>' . esc_html($message) . '</p>';
        echo '</div>';
    }
}
