<?php
/**
 * Admin notice surfaced when the queue is disabled but still has rows.
 *
 * @package NimblyMail\SMTP
 */

namespace NimblyMail\SMTP\Queue;

use NimblyMail\SMTP\Options;

defined( 'ABSPATH' ) || exit;

/**
 * Class DrainNotice
 *
 * Reassures admins that already-queued mail will continue to drain in
 * the background after they switch the queue off, and points them to
 * the Queue page if they want to cancel the rest manually.
 *
 * @since 1.0.0
 */
class DrainNotice {

    /**
     * Register the admin_notices hook.
     *
     * @since 1.0.0
     *
     * @return void
     */
    public function init(): void {
        add_action( 'admin_notices', array( $this, 'maybe_render' ) );
    }

    /**
     * Render the notice when applicable.
     *
     * Gated so the markup only appears on NimblyMail admin pages — other
     * plugin authors should not see queue-state chatter on their screens.
     *
     * @since 1.0.0
     *
     * @return void
     */
    public function maybe_render(): void {
        if ( ! $this->is_nimblymail_screen() ) {
            return;
        }

        if ( Options::init()->get( 'queue', 'enabled' ) ) {
            return;
        }

        $stats   = Model::count_by_status();
        $pending = $stats['pending'] + $stats['processing'];

        if ( $pending <= 0 ) {
            return;
        }

        $queue_url = admin_url( 'admin.php?page=nimblymail-smtp-queue' );

        /* translators: %d: number of in-flight queue items. */
        $template = _n(
            'The queue is disabled but %d item is still draining in the background. New mail will send synchronously.',
            'The queue is disabled but %d items are still draining in the background. New mail will send synchronously.',
            $pending,
            'nimblymail-smtp'
        );

        $message = sprintf( $template, (int) $pending );

        echo '<div class="notice notice-info">';
        echo '<p>';
        echo '<strong>' . esc_html__( 'NimblyMail:', 'nimblymail-smtp' ) . '</strong> ';
        echo esc_html( $message );
        echo ' <a href="' . esc_url( $queue_url ) . '">' . esc_html__( 'View queue', 'nimblymail-smtp' ) . '</a>';
        echo '</p>';
        echo '</div>';
    }

    /**
     * Whether the current admin screen belongs to NimblyMail.
     *
     * @since 1.0.0
     *
     * @return bool
     */
    private function is_nimblymail_screen(): bool {
        if ( ! function_exists( 'get_current_screen' ) ) {
            return false;
        }

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

        return false !== strpos( (string) $screen->id, 'nimblymail-smtp' );
    }
}
