<?php

namespace Formatrica\Admin;

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

final class Notices
{
    public function boot(): void
    {
        add_action('admin_notices', [$this, 'maybe_show_email_warning']);
        add_action('network_admin_notices', [$this, 'maybe_show_email_warning']);
        add_action('admin_notices', [$this, 'maybe_show_php_warning']);
        add_action('network_admin_notices', [$this, 'maybe_show_php_warning']);
        add_action('admin_notices', [$this, 'maybe_show_delete_notices']);
        add_action('admin_notices', [$this, 'maybe_show_queue_overflow']);
        add_action('network_admin_notices', [$this, 'maybe_show_queue_overflow']);
        add_action('admin_init', [$this, 'handle_dismissals']);
    }

    /**
     * Warn admins when the integration queue overflowed and dropped jobs
     * (F-04): the option-backed queue is capped, so a stalled WP-Cron or an
     * unreachable provider raises this flag instead of growing without bound.
     */
    public function maybe_show_queue_overflow(): void
    {
        if (!current_user_can('manage_options')) {
            return;
        }

        // Only surface on Formatrica screens — wp.org discourages plugins
        // showing notices across the whole admin.
        $screen = function_exists('get_current_screen') ? get_current_screen() : null;
        if ($screen === null || strpos((string) $screen->id, 'formatrica') === false) {
            return;
        }

        $overflow = get_option('formatrica_integration_queue_overflow', false);
        if (!is_array($overflow)) {
            return;
        }

        echo '<div class="notice notice-warning"><p>';
        echo '<strong>Formatrica:</strong> ';
        echo esc_html__(
            'The integration queue is full, so some integration deliveries were dropped. This usually means WP-Cron is not running or an integration endpoint is unreachable. Check your scheduled tasks and integration settings.',
            'formatrica'
        );
        echo '</p></div>';
    }

    public function handle_dismissals(): void
    {
        if (!current_user_can('manage_options')) {
            return;
        }

        if (isset($_GET['formatrica_dismiss_email'])) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- nonce verified on next line
            check_admin_referer('formatrica_dismiss_email');
            delete_transient('formatrica_email_warning');
            delete_transient('formatrica_email_sender_warning');
            delete_transient('formatrica_wp_mail_error_details');
            delete_transient('formatrica_wp_mail_last_success');
            wp_safe_redirect(remove_query_arg(['formatrica_dismiss_email', '_wpnonce']));
            exit;
        }

        if (isset($_GET['formatrica_dismiss_php'])) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- nonce verified on next line
            check_admin_referer('formatrica_dismiss_php');
            update_option('formatrica_php_warning_dismissed', PHP_VERSION, false);
            wp_safe_redirect(remove_query_arg(['formatrica_dismiss_php', '_wpnonce']));
            exit;
        }
    }

    public function maybe_show_email_warning(): void
    {
        if (!current_user_can('manage_options')) {
            return;
        }

        // Only show on Formatrica admin pages to avoid dashboard clutter.
        if (!$this->is_plugin_screen()) {
            return;
        }

        $email_warning_active = (bool) get_transient('formatrica_email_warning');
        $sender_warning = get_transient('formatrica_email_sender_warning');
        $error_details = get_transient('formatrica_wp_mail_error_details');
        $last_success = get_transient('formatrica_wp_mail_last_success');

        if (!$email_warning_active && !$sender_warning && !$error_details) {
            return;
        }

        $dismiss_url = wp_nonce_url(add_query_arg('formatrica_dismiss_email', '1'), 'formatrica_dismiss_email');

        echo '<div class="notice notice-warning is-dismissible">';
        echo '<p>' . esc_html__('We detected a deliverability issue with Formatrica emails.', 'formatrica') . '</p>';

        if ($email_warning_active) {
            echo '<p>' . esc_html__('Emails may not be delivering. Open the form’s notification settings and select one of the built-in SMTP or API delivery methods for better reliability.', 'formatrica') . '</p>';
        }

        if (is_array($sender_warning)) {
            $reason = $sender_warning['reason'] ?? '';
            if ($reason === 'invalid') {
                $attempted = isset($sender_warning['attempted']) && is_string($sender_warning['attempted']) ? $sender_warning['attempted'] : '';
                $expected = isset($sender_warning['expected_domain']) && is_string($sender_warning['expected_domain']) ? $sender_warning['expected_domain'] : '';
                echo '<p>' . sprintf(
                    /* translators: 1: attempted sender email, 2: expected domain */
                    esc_html__('The “From email” value (%1$s) is not a valid address. Use an address on %2$s to improve SPF/DKIM alignment.', 'formatrica'),
                    esc_html($attempted ?: \__('the configured address', 'formatrica')),
                    esc_html($expected)
                ) . '</p>';
            } elseif ($reason === 'mismatch') {
                $attempted = isset($sender_warning['attempted']) && is_string($sender_warning['attempted']) ? $sender_warning['attempted'] : '';
                $expected = isset($sender_warning['expected_domain']) && is_string($sender_warning['expected_domain']) ? $sender_warning['expected_domain'] : '';
                echo '<p>' . sprintf(
                    /* translators: 1: attempted sender email, 2: expected domain */
                    esc_html__('We switched the sender back to noreply@%2$s because %1$s uses a different domain. Update your DNS (SPF/DKIM) and use an address on the site domain.', 'formatrica'),
                    esc_html($attempted),
                    esc_html($expected)
                ) . '</p>';
            }
        }

        if (is_array($error_details) && !empty($error_details['message'])) {
            $message = is_string($error_details['message']) ? $error_details['message'] : '';
            $code = is_string($error_details['code'] ?? '') ? $error_details['code'] : '';
            $recorded_at = isset($error_details['recorded_at']) ? (int) $error_details['recorded_at'] : 0;
            $timestamp_text = $recorded_at > 0
                ? sprintf(
                    /* translators: %s: human time diff */
                    __('Logged %s ago.', 'formatrica'),
                    \human_time_diff($recorded_at)
                )
                : '';

            echo '<p>';
            echo esc_html__('Last wp_mail() error:', 'formatrica') . ' ' . esc_html($message);
            if ($code !== '') {
                echo ' (' . esc_html($code) . ')';
            }
            if ($timestamp_text !== '') {
                echo ' ' . esc_html($timestamp_text);
            }
            echo '</p>';

            if (!empty($error_details['details']) && is_array($error_details['details'])) {
                if (!empty($error_details['details']['subject'])) {
                    echo '<p>' . sprintf(
                        /* translators: %s: email subject */
                        esc_html__('Subject: %s', 'formatrica'),
                        esc_html($error_details['details']['subject'])
                    ) . '</p>';
                }
                if (!empty($error_details['details']['to'])) {
                    echo '<p>' . sprintf(
                        /* translators: %s: email recipients */
                        esc_html__('Recipients: %s', 'formatrica'),
                        esc_html($error_details['details']['to'])
                    ) . '</p>';
                }
            }
        }

        if (is_array($last_success) && !empty($last_success['recorded_at'])) {
            $recorded_at = (int) $last_success['recorded_at'];
            $success_to = isset($last_success['to']) && is_string($last_success['to']) ? $last_success['to'] : '';
            $success_subject = isset($last_success['subject']) && is_string($last_success['subject']) ? $last_success['subject'] : '';
            echo '<p>' . sprintf(
                /* translators: 1: time since last success, 2: recipients, 3: subject */
                esc_html__('Last successful send was %1$s ago to %2$s (subject: %3$s).', 'formatrica'),
                esc_html(\human_time_diff($recorded_at)),
                esc_html($success_to ?: \__('configured recipients', 'formatrica')),
                esc_html($success_subject ?: \__('not specified', 'formatrica'))
            ) . '</p>';
        }

        echo '<p><a href="' . esc_url($dismiss_url) . '" class="button">' . esc_html__('Dismiss notice', 'formatrica') . '</a></p>';
        echo '</div>';
    }

    public function maybe_show_php_warning(): void
    {
        if (!current_user_can('manage_options')) {
            return;
        }

        // Only show on Formatrica admin pages to avoid dashboard clutter.
        if (!$this->is_plugin_screen()) {
            return;
        }

        // Check if running on PHP < 8.3
        if (version_compare(PHP_VERSION, '8.3.0', '>=')) {
            return;
        }

        // Check if already dismissed for this PHP version
        $dismissed_version = get_option('formatrica_php_warning_dismissed', '');
        if ($dismissed_version === PHP_VERSION) {
            return;
        }

        $dismiss_url = wp_nonce_url(
            add_query_arg('formatrica_dismiss_php', '1'),
            'formatrica_dismiss_php'
        );

        echo '<div class="notice notice-info is-dismissible">';
        echo '<p><strong>' . esc_html__('Formatrica', 'formatrica') . ':</strong> ';
        echo sprintf(
            /* translators: %s: current PHP version */
            esc_html__('You are running PHP %s. For better performance and security, we recommend upgrading to PHP 8.3 or higher.', 'formatrica'),
            esc_html(PHP_VERSION)
        );
        echo '</p>';
        echo '<p><a href="' . esc_url($dismiss_url) . '" class="button">' . esc_html__('Dismiss', 'formatrica') . '</a></p>';
        echo '</div>';
    }

    public function maybe_show_delete_notices(): void
    {
        if (!current_user_can('manage_options')) {
            return;
        }

        // Only on Forms list page
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- admin page check, no data modification
        if (!isset($_GET['page']) || sanitize_key(wp_unslash((string) $_GET['page'])) !== 'formatrica') {
            return;
        }

        if (isset($_GET['deactivated'])) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- display-only flag
            echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__('Form deactivated. Submissions were retained.', 'formatrica') . '</p></div>';
        }

        if (isset($_GET['activated'])) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- display-only flag
            echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__('Form activated.', 'formatrica') . '</p></div>';
        }

        if (isset($_GET['deleted'])) { // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- display-only flag
            $permanent = isset($_GET['permanent']); // phpcs:ignore WordPress.Security.NonceVerification.Recommended
            if ($permanent) {
                echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__('Form and all its submissions were permanently deleted.', 'formatrica') . '</p></div>';
            } else {
                echo '<div class="notice notice-success is-dismissible"><p>' . esc_html__('Form deleted.', 'formatrica') . '</p></div>';
            }
        }
    }

    /**
     * Check whether the current admin screen belongs to Formatrica.
     *
     * Notices are limited to plugin screens so they never clutter the
     * main WordPress dashboard or unrelated admin pages.
     */
    private function is_plugin_screen(): bool
    {
        // phpcs:ignore WordPress.Security.NonceVerification.Recommended -- read-only admin page check
        $page = isset($_GET['page']) ? sanitize_key(wp_unslash((string) $_GET['page'])) : '';

        return str_starts_with($page, 'formatrica');
    }
}
