<?php

namespace KaizenCoders\MagicLink\EmailDigest;

class EmailSender {

	public function send( $data, $override_email = null ) {
		$recipients = $this->get_recipients( $override_email );
		if ( empty( $recipients ) ) {
			return;
		}

		wp_mail(
			$recipients,
			$this->get_subject( $data ),
			$this->generate_email_html( $data ),
			[ 'Content-Type: text/html; charset=UTF-8' ]
		);
	}

	public function generate_email_html( $data ) {
		ob_start();
		$template = KC_ML_PLUGIN_DIR . 'lite/includes/EmailDigest/EmailTemplate.php';
		if ( file_exists( $template ) ) {
			include $template;
		}

		return ob_get_clean();
	}

	private function get_recipients( $override_email = null ) {
		if ( ! empty( $override_email ) && is_email( $override_email ) ) {
			return [ $override_email ];
		}

		$settings        = KC_ML()->get_settings();
		$recipients_raw  = \KaizenCoders\MagicLink\Helper::get_data( $settings, 'reports|email_digest|email_digest_recipients', '' );
		$recipient_lines = preg_split( '/[\r\n,]+/', (string) $recipients_raw );
		$emails          = [];

		foreach ( $recipient_lines as $line ) {
			$email = sanitize_email( trim( $line ) );
			if ( is_email( $email ) ) {
				$emails[] = $email;
			}
		}

		if ( empty( $emails ) ) {
			$emails[] = get_option( 'admin_email' );
		}

		return array_values( array_unique( $emails ) );
	}

	private function get_subject( $data ) {
		$frequency = ! empty( $data['frequency'] ) ? ucfirst( (string) $data['frequency'] ) : __( 'Weekly', 'magic-link' );
		$site_name = ! empty( $data['site_name'] ) ? (string) $data['site_name'] : get_bloginfo( 'name' );
		$subject   = sprintf( __( 'Magic Link %1$s Activity Summary - %2$s', 'magic-link' ), $frequency, $site_name );

		if ( ! empty( $data['is_preview'] ) ) {
			$subject = '[Preview] ' . $subject;
		}

		return $subject;
	}
}
