<?php

defined( 'ABSPATH' ) || exit;

class ZACLS_Email_Notifications {

	public function __construct() {
		$this->register_hooks();
	}

	private function register_hooks() {
		add_action( 'zacls_successful_login', array( $this, 'check_new_ip_login' ), 10, 1 );
		add_action( 'zacls_ip_blocked_notify', array( $this, 'notify_ip_blocked' ) );
	}

	public function check_new_ip_login( $user ) {
		$settings = get_option( 'zacls_email_notifications', array() );
		if ( empty( $settings['new_ip_login'] ) || 'yes' !== $settings['new_ip_login'] ) {
			return;
		}

		$ip = ZACLS_Main::get_ip();

		$known_ips = get_user_meta( $user->ID, 'zacls_known_ips', true );
		if ( ! is_array( $known_ips ) ) {
			$known_ips = array();
		}
		if ( in_array( $ip, $known_ips, true ) ) {
			return;
		}

		$known_ips[] = $ip;
		update_user_meta( $user->ID, 'zacls_known_ips', $known_ips );

		$vars = array(
			'display_name' => $user->display_name,
			'ip'           => $ip,
			'time'         => current_time( 'mysql' ),
			'user_agent'   => isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : '',
		);

		$subject = sprintf(
			esc_html__( '[%s] New IP Login Detected', 'za-creative-login-shield' ),
			wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES )
		);

		$message = ZACLS_Email_Templates::get_template( 'login-notification', $vars );
		$this->send_admin_email( $subject, $message );
	}

	public function notify_multiple_failed_logins( $username ) {
		$settings = get_option( 'zacls_email_notifications', array() );
		if ( empty( $settings['failed_login'] ) || 'yes' !== $settings['failed_login'] ) {
			return;
		}

		$ip        = ZACLS_Main::get_ip();
		$limits    = get_option( 'zacls_login_limits', array( 'max_attempts' => 5 ) );
		$threshold = $limits['max_attempts'];
		$window    = isset( $limits['time_window'] ) ? $limits['time_window'] : 15;

		$attempts = ZACLS_Login_Limiter::get_attempts_in_window( $ip, $window );
		if ( $attempts < $threshold ) {
			return;
		}

		$subject = sprintf(
			esc_html__( '[%s] Multiple Failed Login Attempts', 'za-creative-login-shield' ),
			wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES )
		);

		$body = '<h2>' . esc_html__( 'Multiple Failed Login Attempts', 'za-creative-login-shield' ) . '</h2>
		<p>' . sprintf( esc_html__( 'There have been %d failed login attempts from IP: %s', 'za-creative-login-shield' ), $attempts, $ip ) . '</p>
		<table class="email-stats-table">
		<tr><td class="label">' . esc_html__( 'IP Address', 'za-creative-login-shield' ) . '</td><td>' . esc_html( $ip ) . '</td></tr>
		<tr><td class="label">' . esc_html__( 'Username Tried', 'za-creative-login-shield' ) . '</td><td>' . esc_html( $username ? $username : esc_html__( 'Unknown', 'za-creative-login-shield' ) ) . '</td></tr>
		<tr><td class="label">' . esc_html__( 'Failed Attempts', 'za-creative-login-shield' ) . '</td><td>' . esc_html( $attempts ) . '</td></tr>
		<tr><td class="label">' . esc_html__( 'Time', 'za-creative-login-shield' ) . '</td><td>' . esc_html( current_time( 'mysql' ) ) . '</td></tr>
		</table>
		<p><a href="' . esc_url( admin_url( 'admin.php?page=zacls&tab=logs' ) ) . '" class="button">' . esc_html__( 'View Login Logs', 'za-creative-login-shield' ) . '</a></p>';

		$message = ZACLS_Email_Templates::get_template( 'default', array( 'message' => $body ) );
		$this->send_admin_email( $subject, $message );
	}

	public function notify_ip_blocked( $ip ) {
		$settings = get_option( 'zacls_email_notifications', array() );
		if ( empty( $settings['ip_blocked'] ) || 'yes' !== $settings['ip_blocked'] ) {
			return;
		}

		$subject = sprintf(
			esc_html__( '[%s] IP Address Blocked', 'za-creative-login-shield' ),
			wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES )
		);

		$vars = array(
			'ip'   => $ip,
			'time' => current_time( 'mysql' ),
		);

		$message = ZACLS_Email_Templates::get_template( 'ip-blocked', $vars );
		$this->send_admin_email( $subject, $message );
	}

	public function send_otp_email( $user, $otp ) {
		$vars = array(
			'display_name' => $user->display_name,
			'code'         => $otp,
		);

		$subject = sprintf(
			esc_html__( '[%s] Your login verification code', 'za-creative-login-shield' ),
			wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES )
		);

		$message = ZACLS_Email_Templates::get_template( 'otp', $vars );
		add_filter( 'wp_mail_content_type', array( $this, 'html_content_type' ) );
		wp_mail( $user->user_email, $subject, $message );
		remove_filter( 'wp_mail_content_type', array( $this, 'html_content_type' ) );
	}

	public function send_verify_device_email( $user, $code, $ip ) {
		$vars = array(
			'display_name' => $user->display_name,
			'code'         => $code,
			'ip'           => $ip,
			'time'         => current_time( 'mysql' ),
		);

		$subject = sprintf(
			esc_html__( '[%s] Verify Your New Device', 'za-creative-login-shield' ),
			wp_specialchars_decode( get_option( 'blogname' ), ENT_QUOTES )
		);

		$message = ZACLS_Email_Templates::get_template( 'verify-device', $vars );
		add_filter( 'wp_mail_content_type', array( $this, 'html_content_type' ) );
		wp_mail( $user->user_email, $subject, $message );
		remove_filter( 'wp_mail_content_type', array( $this, 'html_content_type' ) );
	}

	private function send_admin_email( $subject, $message ) {
		$admin_email = get_option( 'zacls_admin_email', get_option( 'admin_email' ) );
		add_filter( 'wp_mail_content_type', array( $this, 'html_content_type' ) );
		$result = wp_mail( $admin_email, $subject, $message );
		remove_filter( 'wp_mail_content_type', array( $this, 'html_content_type' ) );
		return $result;
	}

	public function html_content_type() {
		return 'text/html';
	}
}
