<?php
/**
 * Mailer — Security Alert Emails
 *
 * Sends HTML alert emails for brute-force, malware, file changes,
 * and critical attack events. Rate-limited to 1 per event-type per hour.
 *
 * @package GuardianShield
 */

namespace GuardianShield;

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

class Mailer {

	private string $admin_email;

	public function __construct() {
		$this->admin_email = (string) gs_get_option( 'alert_email', get_option( 'admin_email' ) );

		// Hook into Guardian Shield events.
		add_action( 'gs_brute_force_detected',   [ $this, 'send_brute_force_alert' ], 10, 3 );
		add_action( 'gs_malware_detected',        [ $this, 'send_malware_alert' ],     10, 1 );
		add_action( 'gs_file_changes_detected',   [ $this, 'send_file_change_alert' ], 10, 1 );
		add_action( 'gs_critical_attack_detected',[ $this, 'send_critical_alert' ],    10, 3 );
		add_action( 'gs_username_renamed',        [ $this, 'send_username_renamed_alert' ], 10, 2 );
	}

	public function send_brute_force_alert( string $ip, string $username, int $attempts ): void {
		if ( ! (bool) gs_get_option( 'alert_on_bruteforce', true ) ) {
			return;
		}

		$subject = sprintf( '[Guardian Shield] Brute Force Detected — %s', get_bloginfo( 'name' ) );
		$body    = $this->wrap_email( sprintf(
			"<h2>⚠️ Brute Force Attack Detected</h2>
			<p>Multiple failed login attempts have been recorded:</p>
			<table>
				<tr><th>IP Address</th><td>%s</td></tr>
				<tr><th>Username</th><td>%s</td></tr>
				<tr><th>Failed Attempts</th><td>%d</td></tr>
				<tr><th>Time</th><td>%s</td></tr>
				<tr><th>Action</th><td>IP Temporarily Blocked</td></tr>
			</table>
			<p><a href='%s'>View Login Logs</a></p>",
			esc_html( $ip ),
			esc_html( $username ),
			$attempts,
			current_time( 'mysql' ),
			esc_url( admin_url( 'admin.php?page=guardian-shield-logs&tab=login' ) )
		) );

		$this->send( $subject, $body );
	}

	public function send_malware_alert( array $threats ): void {
		if ( ! (bool) gs_get_option( 'alert_on_malware', true ) || empty( $threats ) ) {
			return;
		}

		$count   = count( $threats );
		$subject = sprintf( '[Guardian Shield] ⚠️ Malware Detected — %d file(s)', $count );

		$rows = '';
		foreach ( array_slice( $threats, 0, 10 ) as $t ) {
			$rows .= sprintf(
				'<tr><td>%s</td><td>%s</td><td>%s</td></tr>',
				esc_html( $t['file_path'] ),
				esc_html( $t['threat_type'] ),
				esc_html( $t['status'] )
			);
		}

		$body = $this->wrap_email( sprintf(
			"<h2>🦠 Malware Detected</h2>
			<p>Guardian Shield found <strong>%d</strong> suspicious file(s):</p>
			<table><thead><tr><th>File</th><th>Threat</th><th>Status</th></tr></thead><tbody>%s</tbody></table>
			<p><a href='%s'>View Scan Report</a></p>",
			$count,
			$rows,
			esc_url( admin_url( 'admin.php?page=guardian-shield-scanner' ) )
		) );

		$this->send( $subject, $body );
	}

	public function send_file_change_alert( array $changes ): void {
		if ( ! (bool) gs_get_option( 'alert_on_file_change', true ) || empty( $changes ) ) {
			return;
		}

		$count   = count( $changes );
		$subject = sprintf( '[Guardian Shield] File Modification Detected — %d file(s)', $count );

		$rows = '';
		foreach ( array_slice( $changes, 0, 10 ) as $c ) {
			$rows .= sprintf(
				'<tr><td>%s</td><td>%s</td><td>%s</td></tr>',
				esc_html( $c['file_path'] ),
				esc_html( $c['type'] ),
				esc_html( $c['status'] )
			);
		}

		$body = $this->wrap_email( sprintf(
			"<h2>📁 File Integrity Alert</h2>
			<p><strong>%d</strong> file(s) have been modified:</p>
			<table><thead><tr><th>File</th><th>Type</th><th>Status</th></tr></thead><tbody>%s</tbody></table>
			<p><a href='%s'>View Integrity Report</a></p>",
			$count,
			$rows,
			esc_url( admin_url( 'admin.php?page=guardian-shield-monitor' ) )
		) );

		$this->send( $subject, $body );
	}

	public function send_critical_alert( string $ip, string $type, string $reason ): void {
		$subject = sprintf( '[Guardian Shield] 🚨 Critical Attack — %s', get_bloginfo( 'name' ) );
		$body    = $this->wrap_email( sprintf(
			"<h2>🚨 Critical Security Event</h2>
			<table>
				<tr><th>IP Address</th><td>%s</td></tr>
				<tr><th>Attack Type</th><td>%s</td></tr>
				<tr><th>Details</th><td>%s</td></tr>
				<tr><th>Time</th><td>%s</td></tr>
				<tr><th>Action</th><td>Request Blocked</td></tr>
			</table>
			<p><a href='%s'>View Attack Logs</a></p>",
			esc_html( $ip ),
			esc_html( $type ),
			esc_html( $reason ),
			current_time( 'mysql' ),
			esc_url( admin_url( 'admin.php?page=guardian-shield-logs' ) )
		) );

		$this->send( $subject, $body );
	}

	// ── Username Renamed Alert ───────────────────
	public function send_username_renamed_alert( string $old_username, string $new_username ): void {
		if ( ! (bool) gs_get_option( 'alert_on_username_rename', true ) ) {
			return;
		}

		$subject = sprintf( '[Guardian Shield] 🔑 Admin Gebruikersnaam Gewijzigd — %s', get_bloginfo( 'name' ) );
		$body    = $this->wrap_email( sprintf(
			"<h2>🔑 Admin Gebruikersnaam Gewijzigd</h2>
			<p>Guardian Shield heeft om veiligheidsredenen de admin gebruikersnaam automatisch gewijzigd.</p>
			<table>
				<tr><th>Oude gebruikersnaam</th><td>%s</td></tr>
				<tr><th>Nieuwe gebruikersnaam</th><td><strong style='font-size:16px;color:#0e1b33'>%s</strong></td></tr>
				<tr><th>Tijdstip</th><td>%s</td></tr>
				<tr><th>Reden</th><td>Bescherming tegen brute force aanvallen op standaard 'admin' accounts</td></tr>
			</table>
			<p style='background:#fff3cd;border:1px solid #ffc107;padding:12px;border-radius:6px'>
				⚠️ <strong>Bewaar deze gebruikersnaam!</strong> Je kunt voortaan inloggen met <strong>%s</strong> of je e-mailadres.
			</p>
			<p><a href='%s'>Inloggen op WordPress</a></p>",
			esc_html( $old_username ),
			esc_html( $new_username ),
			current_time( 'mysql' ),
			esc_html( $new_username ),
			esc_url( wp_login_url() )
		) );

		// Gebruik een eigen throttle-key zodat deze mail niet wordt geblokkeerd door andere rate-limits.
		$throttle_key = 'gs_email_username_renamed';
		delete_transient( $throttle_key ); // Altijd versturen, niet throttlen.

		add_filter( 'wp_mail_content_type', fn() => 'text/html' );
		wp_mail( $this->admin_email, $subject, $body );
		remove_filter( 'wp_mail_content_type', fn() => 'text/html' );
	}

	// ── Internal Helpers ─────────────────────────
	private function send( string $subject, string $html_body ): bool {
		if ( empty( $this->admin_email ) || ! (bool) gs_get_option( 'email_alerts', true ) ) {
			return false;
		}

		// Rate-limit outgoing emails to prevent alert storms (max 1 per type per hour via transient).
		$throttle_key = 'gs_email_' . md5( $subject );
		if ( get_transient( $throttle_key ) ) {
			return false;
		}
		set_transient( $throttle_key, 1, HOUR_IN_SECONDS );

		add_filter( 'wp_mail_content_type', fn() => 'text/html' );
		$result = wp_mail( $this->admin_email, $subject, $html_body );
		remove_filter( 'wp_mail_content_type', fn() => 'text/html' );

		return $result;
	}

	private function wrap_email( string $content ): string {
		$site = esc_html( get_bloginfo( 'name' ) );
		$url  = esc_url( site_url() );
		return "
		<div style='font-family:Arial,sans-serif;max-width:600px;margin:0 auto;background:#f5f5f5;padding:20px'>
			<div style='background:#0e1b33;padding:20px;border-radius:8px 8px 0 0;text-align:center'>
				<h1 style='color:#fff;margin:0'>🛡 Guardian Shield</h1>
				<p style='color:#aaa;margin:5px 0 0'>{$site} &mdash; <a href='{$url}' style='color:#60a5fa'>{$url}</a></p>
			</div>
			<div style='background:#fff;padding:25px;border-radius:0 0 8px 8px'>
				{$content}
				<hr style='border:none;border-top:1px solid #eee;margin:20px 0'>
				<p style='color:#888;font-size:12px'>This is an automated alert from Guardian Shield WordPress Security Plugin. Do not reply to this email.</p>
			</div>
		</div>";
	}
}
