<?php

namespace WPSN\Modules\Notifications;

use WPSN\Core\AbstractModule;
use WPSN\Core\Queue\QueueRunner;

defined('ABSPATH') || exit;

/**
 * Notifications Center (trust feature).
 *
 * Captures important plugin events (queue failures, head diff after update, audit critical issues)
 * and can send best-effort notifications via email / Slack / webhook.
 *
 * This is NOT related to licensing/upsell — it's operational trust & support.
 */
final class NotificationsModule extends AbstractModule
{
    public function id(): string
    {
        return 'notifications';
    }

    public function name(): string
    {
        return __('Notifications', 'wp-seo-next');
    }

    public function description(): string
    {
        return __('Central notifications for critical SEO/operational events (email/Slack/webhook) with ack + mute.', 'wp-seo-next');
    }

    public function defaultEnabled(): bool
    {
        return true;
    }

    public function register(): void
    {
        // DB installer.
        add_action('init', [NotificationsInstaller::class, 'maybeInstall'], 1);

        // Queue handler.
        $jobs = new NotificationsJobs($this->container);
        add_filter('wpsn_queue_handle_' . NotificationsJobs::JOB_SEND, [$jobs, 'handleSend'], 10, 3);
        add_filter('wpsn_queue_handle_' . NotificationsJobs::JOB_SEND_DIGEST, [$jobs, 'handleSendDigest'], 10, 3);

        // Event hooks (sources).
        add_action('wpsn/queue/job_failed', [$jobs, 'onQueueJobFailed'], 10, 5);
        add_action('wpsn/head_diff/detected', [$jobs, 'onHeadDiffDetected'], 10, 1);
        add_action('wpsn/audit/scan_completed', [$jobs, 'onAuditScanCompleted'], 10, 2);
        add_action('wpsn/quality_gate/run_completed', [$jobs, 'onQualityGateRunCompleted'], 10, 2);
        add_action('wpsn/platform_ops/run_completed', [$jobs, 'onPlatformOpsRunCompleted'], 10, 2);
        add_action('wpsn/saas_sync/failed', [$jobs, 'onSaaSSyncFailed'], 10, 2);
        add_action('wpsn/saas_dashboard/failed', [$jobs, 'onSaaSDashboardFailed'], 10, 3);
        add_action('wpsn/serp_gap/run_failed', [$jobs, 'onSerpGapFailed'], 10, 3);

        // Integrations (optional / opt-in): unify legacy notification sources.
        add_action('wpsn/drift_monitor/event_created', [$jobs, 'onDriftMonitorEventCreated'], 10, 7);
        add_action('wpsn/search_console/alert_digest_built', [$jobs, 'onGscAlertDigestBuilt'], 10, 1);

        // Cron: digest tick (hourly) to enqueue daily/weekly digest jobs.
        add_action('init', [$this, 'ensureCron'], 20);
        add_action('wpsn_notifications_digest_tick', [$jobs, 'onDigestTick']);

        // Admin UI.
        if (is_admin()) {
            $runner = new QueueRunner($this->container->get('queue'), $this->container->get('logger'));
            $admin = new Admin\NotificationsAdmin($this->container, $runner);
            $admin->register();
        }
    }

    public function ensureCron(): void
    {
        $settings = $this->container->get('settings');
        $enabled = (bool) $settings->get('notifications.enabled', true);

        $dig = $settings->get('notifications.digests', []);
        $hasDigest = is_array($dig) && (!empty($dig['daily_enabled']) || !empty($dig['weekly_enabled']));

        // Respect manual queue mode to avoid accumulating jobs when background processing is disabled.
        $queueMode = (string) $settings->get('performance.queue.mode', 'auto');
        if ($queueMode === 'manual' || !$enabled || !$hasDigest) {
            if (function_exists('wp_clear_scheduled_hook')) {
                wp_clear_scheduled_hook('wpsn_notifications_digest_tick');
            }
            return;
        }

        if (!wp_next_scheduled('wpsn_notifications_digest_tick')) {
            wp_schedule_event(time() + HOUR_IN_SECONDS, 'hourly', 'wpsn_notifications_digest_tick');
        }
    }

}