<?php

namespace UltraguardPro\modules\reputation_monitor;

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

use UltraguardPro\Plugin;
use UltraguardPro\core\MailManager;

class ReputationMonitorNotifications {

    private Plugin $plugin;

    public function __construct( Plugin $plugin ) {
        $this->plugin = $plugin;
    }

    public function register(): void {
        add_action( 'ultraguard_pro/reputation_monitor/check_complete', [ $this, 'maybe_notify_blacklist' ], 10, 1 );
    }

    public function maybe_notify_blacklist( array $summary ): void {
        if ( empty( $summary['blacklisted_sources'] ) ) {
            return;
        }

        if ( $this->plugin->settings->get_option( 'reputation_monitor_email_alert', true ) ) {
            $this->send_email_alert( $summary );
        }

        if ( $this->plugin->settings->get_option( 'reputation_monitor_webhook_alert', false ) ) {
            $this->send_webhook_alert( $summary );
        }
    }

    private function send_email_alert( array $summary ): void {
        $recipients = array_filter( array_map( 'sanitize_email', (array) $this->plugin->settings->get_option( 'reputation_monitor_alert_recipients', [] ) ) );
        $admin      = get_option( 'admin_email' );

        if ( is_email( $admin ) ) {
            $recipients[] = $admin;
        }

        $recipients = array_values( array_unique( array_filter( $recipients, 'is_email' ) ) );
        if ( empty( $recipients ) ) {
            return;
        }

        $subject = sprintf(
            /* translators: Placeholder values are inserted into this string. */
            __( 'UltraGuard Alert: %1$s blacklisted on %2$d source(s)', 'ultraguard-security-suite' ),
            wp_parse_url( home_url(), PHP_URL_HOST ),
            count( (array) $summary['blacklisted_sources'] )
        );

        MailManager::notification( [
            'to'        => $recipients,
            'subject'   => $subject,
            'title'     => __( 'Blacklist activity detected', 'ultraguard-security-suite' ),
            'message'   => __( 'UltraGuard Reputation Monitor found one or more blacklist hits for this site.', 'ultraguard-security-suite' ),
            'tone'      => 'danger',
            'details'   => [
                __( 'Overall status', 'ultraguard-security-suite' ) => (string) $summary['overall_status'],
                __( 'Checked at', 'ultraguard-security-suite' )     => (string) $summary['checked_at'],
                __( 'Sources', 'ultraguard-security-suite' )        => array_map( static function ( $source ) {
                    return sprintf(
                        '%1$s (%2$s) [%3$s]',
                        (string) ( $source['source_name'] ?? $source['source_id'] ?? __( 'Unknown source', 'ultraguard-security-suite' ) ),
                        (string) ( $source['target'] ?? '' ),
                        (string) ( $source['status'] ?? 'blacklisted' )
                    );
                }, (array) $summary['blacklisted_sources'] ),
            ],
            'cta_url'   => admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=reputation-monitor' ),
            'cta_label' => __( 'Open Reputation Monitor', 'ultraguard-security-suite' ),
        ] );
    }

    private function send_webhook_alert( array $summary ): void {
        $url = esc_url_raw( (string) $this->plugin->settings->get_option( 'reputation_monitor_webhook_url', '' ) );
        if ( empty( $url ) ) {
            return;
        }

        wp_remote_post( $url, [
            'timeout' => 12,
            'headers' => [ 'Content-Type' => 'application/json' ],
            'body'    => wp_json_encode( [
                'event'   => 'reputation_monitor_blacklisted',
                'site'    => home_url(),
                'summary' => $summary,
            ] ),
        ] );
    }
}
