<?php
/**
 * AntivirusNotifications — Email notifications for antivirus events.
 *
 * Fires on:
 *   • Scan completed with threats         → on_scan_completed
 *   • File quarantined                    → on_file_quarantined
 *   • File restored from quarantine       → on_file_restored
 *   • Critical vulnerability found        → on_critical_vuln
 *
 * @package UltraguardPro\modules\antivirus
 */

namespace UltraguardPro\modules\antivirus;

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

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

class AntivirusNotifications {

    private Plugin $plugin;

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

    /**
     * Register action hooks.
     */
    public function register(): void {
        add_action( 'ultraguard_antivirus_scan_completed',   [ $this, 'on_scan_completed' ],    10, 2 );
        add_action( 'ultraguard_antivirus_file_quarantined', [ $this, 'on_file_quarantined' ],  10, 2 );
        add_action( 'ultraguard_antivirus_file_restored',    [ $this, 'on_file_restored' ],     10, 1 );
        add_action( 'ultraguard_antivirus_critical_vuln',    [ $this, 'on_critical_vuln' ],     10, 2 );
    }

    // ── Event handlers ────────────────────────────────────────────────────────

    /**
     * Send an email when a scan completes with threats.
     *
     * @param string $scan_id  Scan session ID.
     * @param array  $summary  { files_scanned, threats_found, ... }
     */
    public function on_scan_completed( string $scan_id, array $summary ): void {
        if ( (int) ( $summary['threats_found'] ?? 0 ) <= 0 ) { return; }
        if ( ! $this->is_enabled( 'antivirus_notify_on_threat' ) ) { return; }

        $to      = $this->get_email();
        $subject = sprintf(
            /* translators: 1: site name, 2: threat count */
            __( '[%1$s] Security Alert: %2$d malware threat(s) detected', 'ultraguard-security-suite' ),
            get_bloginfo( 'name' ),
            (int) $summary['threats_found']
        );

        $this->send( $to, $subject, $this->build_scan_email( $scan_id, $summary ) );
        $this->log_notification( 'scan_completed', $scan_id, [ 'threats' => $summary['threats_found'] ] );
    }

    /**
     * Send an email when a file is quarantined.
     *
     * @param string $original_path   Original file path.
     * @param string $quarantine_path Quarantine destination path.
     */
    public function on_file_quarantined( string $original_path, string $quarantine_path ): void {
        if ( ! $this->is_enabled( 'antivirus_notify_on_quarantine' ) ) { return; }

        $to      = $this->get_email();
        $subject = sprintf(
            /* translators: %s: site name */
            __( '[%s] Security: File quarantined', 'ultraguard-security-suite' ),
            get_bloginfo( 'name' )
        );

        $this->send( $to, $subject, $this->build_quarantine_email( $original_path ) );
    }

    /**
     * Send an email when a quarantined file is restored.
     *
     * @param string $original_path  Path the file was restored to.
     */
    public function on_file_restored( string $original_path ): void {
        $to      = $this->get_email();
        $subject = sprintf(
            /* translators: %s: site name */
            __( '[%s] Security: Quarantined file restored', 'ultraguard-security-suite' ),
            get_bloginfo( 'name' )
        );

        $this->send( $to, $subject, $this->build_restore_email( $original_path ) );
    }

    /**
     * Send an email when a critical vulnerability is discovered.
     *
     * @param string $component  Component slug.
     * @param array  $vuln       Vulnerability record.
     */
    public function on_critical_vuln( string $component, array $vuln ): void {
        if ( ! $this->is_enabled( 'antivirus_notify_on_vulnerability' ) ) { return; }

        $to      = $this->get_email();
        $subject = sprintf(
            /* translators: 1: site name, 2: component slug */
            __( '[%1$s] Security: Critical vulnerability in %2$s', 'ultraguard-security-suite' ),
            get_bloginfo( 'name' ),
            $component
        );

        $this->send( $to, $subject, $this->build_vuln_email( $component, $vuln ) );
    }

    // ── Email builders ────────────────────────────────────────────────────────

    private function build_scan_email( string $scan_id, array $summary ): string {
        $site    = esc_html( get_bloginfo( 'name' ) );
        $url     = admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=file-scanner' );
        $threats = (int) ( $summary['threats_found'] ?? 0 );
        $scanned = number_format_i18n( (int) ( $summary['files_scanned'] ?? 0 ) );

        return $this->wrap_html_email( sprintf(
            '<h2 style="color:#ef4444;margin:0 0 16px;">&#9888; Malware Detected on %s</h2>
            <table style="width:100%%;border-collapse:collapse;">
              <tr><td style="padding:6px 0;color:#64748b;width:160px;">Scan ID</td><td style="padding:6px 0;"><strong>%s</strong></td></tr>
              <tr><td style="padding:6px 0;color:#64748b;">Threats Found</td><td style="padding:6px 0;"><strong style="color:#ef4444;">%d</strong></td></tr>
              <tr><td style="padding:6px 0;color:#64748b;">Files Scanned</td><td style="padding:6px 0;"><strong>%s</strong></td></tr>
              <tr><td style="padding:6px 0;color:#64748b;">Time</td><td style="padding:6px 0;">%s</td></tr>
            </table>
            <p style="margin:20px 0 0;">Please review and quarantine or delete any infected files immediately.</p>
            <p style="margin:16px 0 0;"><a href="%s" style="background:#0ea5e9;color:#fff;padding:10px 20px;text-decoration:none;border-radius:6px;display:inline-block;">View Scan Results &#8594;</a></p>',
            $site,
            esc_html( $scan_id ),
            $threats,
            $scanned,
            esc_html( current_time( 'mysql', true ) ),
            esc_url( $url )
        ) );
    }

    private function build_quarantine_email( string $path ): string {
        $site = esc_html( get_bloginfo( 'name' ) );
        $url  = admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=quarantine' );

        return $this->wrap_html_email( sprintf(
            '<h2 style="color:#f59e0b;margin:0 0 16px;">&#128274; File Quarantined on %s</h2>
            <p>The following file was moved to quarantine:</p>
            <code style="background:#f1f5f9;padding:8px 12px;display:block;border-radius:4px;font-size:13px;word-break:break-all;margin:12px 0;">%s</code>
            <p>This file was identified as potentially malicious. It has been safely isolated and cannot execute.</p>
            <p><a href="%s" style="background:#0ea5e9;color:#fff;padding:10px 20px;text-decoration:none;border-radius:6px;display:inline-block;">Manage Quarantine &#8594;</a></p>',
            $site,
            esc_html( $path ),
            esc_url( $url )
        ) );
    }

    private function build_restore_email( string $path ): string {
        $site = esc_html( get_bloginfo( 'name' ) );

        return $this->wrap_html_email( sprintf(
            '<h2 style="color:#10b981;margin:0 0 16px;">&#9940; Quarantined File Restored on %s</h2>
            <p>The following file was restored from quarantine to its original location:</p>
            <code style="background:#f1f5f9;padding:8px 12px;display:block;border-radius:4px;font-size:13px;word-break:break-all;margin:12px 0;">%s</code>
            <p style="color:#ef4444;"><strong>Warning:</strong> Restoring a quarantined file may re-introduce a security risk. Ensure the file is genuinely safe.</p>',
            $site,
            esc_html( $path )
        ) );
    }

    private function build_vuln_email( string $component, array $vuln ): string {
        $site = esc_html( get_bloginfo( 'name' ) );
        $url  = admin_url( 'admin.php?page=ultraguard-security-suite-dashboard&ug_page=vulnerability-scanner' );

        return $this->wrap_html_email( sprintf(
            '<h2 style="color:#ef4444;margin:0 0 16px;">&#128680; Critical Vulnerability on %s</h2>
            <table style="width:100%%;border-collapse:collapse;">
              <tr><td style="padding:6px 0;color:#64748b;width:160px;">Component</td><td><strong>%s</strong></td></tr>
              <tr><td style="padding:6px 0;color:#64748b;">Severity</td><td><strong style="color:#ef4444;">%s</strong></td></tr>
              <tr><td style="padding:6px 0;color:#64748b;">Type</td><td>%s</td></tr>
              <tr><td style="padding:6px 0;color:#64748b;">CVE</td><td>%s</td></tr>
              <tr><td style="padding:6px 0;color:#64748b;">Remediation</td><td>%s</td></tr>
            </table>
            <p><a href="%s" style="background:#0ea5e9;color:#fff;padding:10px 20px;text-decoration:none;border-radius:6px;display:inline-block;margin-top:16px;">View Vulnerabilities &#8594;</a></p>',
            $site,
            esc_html( $component ),
            esc_html( ucfirst( $vuln['severity'] ?? 'unknown' ) ),
            esc_html( $vuln['vulnerability_type'] ?? '—' ),
            esc_html( $vuln['cve_id'] ?? '—' ),
            esc_html( $vuln['remediation'] ?? 'Check for available updates.' ),
            esc_url( $url )
        ) );
    }

    private function wrap_html_email( string $body ): string {
        $site = esc_html( get_bloginfo( 'name' ) );
        $home = esc_url( home_url() );

        return sprintf(
            '%s<p style="margin:22px 0 0;color:#64748b;font-size:12px;line-height:1.8;">Automated antivirus message from <a href="%s" style="color:#0891b2;text-decoration:none;">%s</a>. To change delivery preferences, visit Antivirus Settings.</p>',
            $body,
            $home,
            $site
        );
    }

    // ── Private helpers ───────────────────────────────────────────────────────

    /**
     * Send an HTML email via wp_mail, ensuring the content-type filter is
     * added and removed correctly without using anonymous functions.
     *
     * @param  string $to       Recipient email.
     * @param  string $subject  Email subject.
     * @param  string $message  HTML email body.
     * @return bool
     */
    private function send( string $to, string $subject, string $message ): bool {
        if ( ! $to || ! is_email( $to ) ) { return false; }
        return MailManager::make()
            ->to( $to )
            ->subject( wp_specialchars_decode( $subject, ENT_QUOTES ) )
            ->html( $message )
            ->send();
    }

    /**
     * Get the configured notification email address, falling back to admin email.
     *
     * @return string
     */
    private function get_email(): string {
        $custom = $this->plugin->settings->get_option( 'antivirus_notify_email', '' );
        return ( $custom && is_email( $custom ) ) ? $custom : (string) get_option( 'admin_email', '' );
    }

    /**
     * Check if a notification setting is enabled.
     *
     * @param  string $key  Settings option key.
     * @return bool
     */
    private function is_enabled( string $key ): bool {
        return (bool) $this->plugin->settings->get_option( $key, true );
    }

    /**
     * Log a notification event via the UltraGuard event hook.
     *
     * @param string $type  Event type.
     * @param string $ref   Reference (scan ID, path, etc.).
     * @param array  $meta  Extra context.
     */
    private function log_notification( string $type, string $ref, array $meta = [] ): void {
        do_action( 'ultraguard_log_event', [
            'module'    => 'antivirus',
            'type'      => 'notification',
            'event'     => $type,
            'reference' => $ref,
            'meta'      => $meta,
        ] );
    }
}
