<?php

namespace WP_Defender\Model\Notification;

use WP_Defender\Model\Scan;
use WP_Defender\Model\Scan_Item;
use WP_Defender\Traits\IO;

/**
 * Class Firewall_Notification
 * @package WP_Defender\Model\Notification
 */
class Malware_Notification extends \WP_Defender\Model\Notification {
	use IO;

	/**
	 * Option name
	 * @var string
	 */
	protected $table = 'wd_malware_scanning_notification';

	public function before_load() {
		$default = [
			'slug'                 => 'malware-notification',
			'title'                => __( 'Malware Scanning - Notification', 'wpdef' ),
			'status'               => self::STATUS_DISABLED,
			'description'          => __( 'Get email notifications when Defender has finished manual malware scans.', 'wpdef' ),
			'in_house_recipients'  => [
				$this->get_default_user()
			],
			'out_house_recipients' => [],
			'type'                 => 'notification',
			'dry_run'              => false,
			'configs'              => [
				'always_send' => false,
				'error_send'  => false,
				'template'    => [
					'found'     => [
						'subject' => __( 'Scan of {SITE_URL} complete. {ISSUES_COUNT} issues found.', 'wpdef' ),
						'body'    => __( 'Hi {USER_NAME},

WP Defender here, reporting back from the front.

I\'ve finished scanning {SITE_URL} for vulnerabilities and I found {ISSUES_COUNT} issues that you should take a closer look at!
{ISSUES_LIST}

Stay Safe,
WP Defender
Official WPMU DEV Superhero
', 'wpdef' )
					],
					'not_found' => [
						'subject' => __( 'Scan of {SITE_URL} complete. {ISSUES_COUNT} issues found.', 'wpdef' ),
						'body'    => __( 'Hi {USER_NAME},

WP Defender here, reporting back from the front.

I\'ve finished scanning {SITE_URL} for vulnerabilities and I found nothing. Well done for running such a tight ship!

		Keep up the good work! With regular security scans and a well-hardened installation you\'ll be just fine.

Stay safe,
WP Defender
', 'wpdef' )
					],
					'error'     => [
						'subject' => __( 'Couldn’t scan {SITE_URL} for vulnerabilities. ', 'wpdef' ),
						'body'    => __( 'Hi {USER_NAME},

WP Defender here, reporting back from the front.

I couldn’t scan {SITE_URL} for vulnerabilities. Please {follow this link} and check the logs to see what casued the failure.

Stay Safe,
WP Defender
Official WPMU DEV Superhero
', 'wpdef' )
					]
				]
			]
		];
		$this->import( $default );
	}

	/**
	 * @param Scan $scan
	 */
	public function send( Scan $scan ) {
		$object = $this;
		if ( $scan->is_automation ) {
			$object = wd_di()->get( Malware_Report::class );
			if ( true === $object->dry_run ) {
				//no send because the report option without recipients is enabled
				return;
			}
		}
		$issues = $scan->get_issues( null, Scan_Item::STATUS_ACTIVE );
		//Sometimes value may be as empty string for disabled 'always_send'
		if (
			( '' === $object->configs['always_send'] || false === $object->configs['always_send'] )
			&& 0 === count( $issues )
		) {
			return;
		}
		$templates  = count( $issues ) ? $object->configs['template']['found'] : $object->configs['template']['not_found'];
		$subject    = $templates['subject'];
		$content    = nl2br( $templates['body'] );
		$slug       = $scan->is_automation ? '#malware_report' : '#malware-notification';
		$report_url = apply_filters( 'wp_defender/scan/email_report_link', network_admin_url( "admin.php?page=wdf-notification" . $slug ) );
		foreach ( $object->in_house_recipients as $user ) {
			if ( $user['status'] !== \WP_Defender\Model\Notification::USER_SUBSCRIBED ) {
				continue;
			}
			$this->send_to_user( $user['email'], $user['name'], $subject, $content, $issues, $report_url );
		}
		foreach ( $object->out_house_recipients as $user ) {
			if ( $user['status'] !== \WP_Defender\Model\Notification::USER_SUBSCRIBED ) {
				continue;
			}
			$this->send_to_user( $user['email'], $user['name'], $subject, $content, $issues, $report_url );
		}
	}

	/**
	 * @param $email
	 * @param $name
	 * @param $subject
	 * @param $content
	 * @param $issues
	 *
	 * @throws \DI\DependencyException
	 * @throws \DI\NotFoundException
	 */
	private function send_to_user( $email, $name, $subject, $content, $issues, $report_url ) {
		$replacers = [
			'issues_count' => count( $issues ),
			'issues_list'  => $this->render_issue_table( $issues ),
			'site_url'     => network_site_url(),
			'user_name'    => $name
		];
		// Not use the filter 'report_email_logs_link' because SCAN_PAGE_LINK doesn't exist
		$replacers   = apply_filters( 'wd_notification_email_params', $replacers );
		$filter_name = count( $issues ) > 0
			? 'wd_notification_email_subject_issue'
			: 'wd_notification_email_subject';
		$subject     = apply_filters( $filter_name, $subject );
		$content     = apply_filters( 'wd_notification_email_content_before', $content );
		foreach ( $replacers as $key => $replacer ) {
			$content = str_replace( "{{$key}}", $replacer, $content );
			$content = str_replace( "{" . strtoupper( $key ) . "}", $replacer, $content );
			$subject = str_replace( "{{$key}}", $replacer, $subject );
			$subject = str_replace( "{" . strtoupper( $key ) . "}", $replacer, $subject );
		}
		$content     = apply_filters( 'wd_notification_email_content_after', $content );

		$template       = wd_di()->get( \WP_Defender\Controller\Scan::class )->render_partial( 'email/scan', [
			'subject'    => $subject,
			'content'    => $content,
			'report_url' => $report_url
		], false );
		$no_reply_email = "noreply@" . parse_url( get_site_url(), PHP_URL_HOST );
		$no_reply_email = apply_filters( 'wd_scan_noreply_email', $no_reply_email );
		$headers        = array(
			'From: Defender <' . $no_reply_email . '>',
			'Content-Type: text/html; charset=UTF-8'
		);
		$ret            = wp_mail( $email, $subject, $template, $headers );
		if ( $ret ) {
			$this->save_log( $email );
		}
	}

	private function render_issue_table( $issues ) {
		ob_start();
		?>
        <table class="results-list"
               style="border-collapse: collapse; border-spacing: 0; padding: 0; text-align: left; vertical-align: top;">
            <thead class="results-list-header"
                   style="border-bottom: 2px solid #ff5c28;">
            <tr style="padding: 0; text-align: left; vertical-align: top;">
                <th class="result-list-label-title"
                    style="Margin: 0; color: #ff5c28; font-family: Helvetica, Arial, sans-serif; font-size: 22px; font-weight: 700; line-height: 48px; margin: 0; padding: 0; text-align: left; width: 35%;"><?php esc_html_e( "File",
						'wpdef' ) ?></th>
                <th class="result-list-data-title"
                    style="Margin: 0; color: #ff5c28; font-family: Helvetica, Arial, sans-serif; font-size: 22px; font-weight: 700; line-height: 48px; margin: 0; padding: 0; text-align: left;"><?php esc_html_e( "Issue",
						'wpdef' ) ?></th>
            </tr>
            </thead>
            <tbody class="results-list-content">
			<?php foreach ( $issues as $k => $item ): ?>
				<?php $detail = $item->to_array();
				?>
				<?php if ( $k == 0 ): ?>
                    <tr style="padding: 0; text-align: left; vertical-align: top;">
                        <td class="result-list-label"
                            style="-moz-hyphens: auto; -webkit-hyphens: auto; Margin: 0; border-collapse: collapse !important; color: #555555; font-family: Helvetica, Arial, sans-serif; font-size: 15px; font-weight: 700; hyphens: auto; line-height: 28px; margin: 0; padding: 20px 5px; text-align: left; vertical-align: top; word-wrap: break-word;">
							<?php echo $detail['file_name'] ?>
                            <span
                                    style="display: inline-block; font-weight: 400; width: 100%;"><?php echo isset( $detail['full_path'] ) ? $detail['full_path'] : null ?></span>
                        </td>
                        <td class="result-list-data"
                            style="-moz-hyphens: auto; -webkit-hyphens: auto; Margin: 0; border-collapse: collapse !important; color: #555555; font-family: Helvetica, Arial, sans-serif; font-size: 15px; font-weight: 700; hyphens: auto; line-height: 28px; margin: 0; padding: 20px 5px; text-align: left; vertical-align: top; word-wrap: break-word;">
							<?php echo $detail['short_desc'] ?></td>
                    </tr>
				<?php else: ?>
                    <tr style="padding: 0; text-align: left; vertical-align: top;">
                        <td class="result-list-label <?php echo $k > 0 ? " bordered" : null ?>"
                            style="-moz-hyphens: auto; -webkit-hyphens: auto; Margin: 0; border-collapse: collapse !important; border-top: 2px solid #ff5c28; color: #555555; font-family: Helvetica, Arial, sans-serif; font-size: 15px; font-weight: 700; hyphens: auto; line-height: 28px; margin: 0; padding: 20px 5px; text-align: left; vertical-align: top; word-wrap: break-word;">
							<?php echo $detail['file_name'] ?>
                            <span
                                    style="display: inline-block; font-weight: 400; width: 100%;"><?php echo isset( $detail['full_path'] ) ? $detail['full_path'] : null ?></span>
                        </td>
                        <td class="result-list-data <?php echo $k > 0 ? " bordered" : null ?>"
                            style="-moz-hyphens: auto; -webkit-hyphens: auto; Margin: 0; border-collapse: collapse !important; border-top: 2px solid #ff5c28; color: #555555; font-family: Helvetica, Arial, sans-serif; font-size: 15px; font-weight: 700; hyphens: auto; line-height: 28px; margin: 0; padding: 20px 5px; text-align: left; vertical-align: top; word-wrap: break-word;">
							<?php echo $detail['short_desc'] ?></td>
                    </tr>
				<?php endif; ?>
			<?php endforeach; ?>
            </tbody>
            <tfoot class="results-list-footer">
            <tr style="padding: 0; text-align: left; vertical-align: top;">
                <td colspan="2"
                    style="-moz-hyphens: auto; -webkit-hyphens: auto; Margin: 0; border-collapse: collapse !important; color: #555555; font-family: Helvetica, Arial, sans-serif; font-size: 15px; font-weight: normal; hyphens: auto; line-height: 26px; margin: 0; padding: 10px 0 0; text-align: left; vertical-align: top; word-wrap: break-word;">
                    <p style="Margin: 0; Margin-bottom: 0; color: #555555; font-family: Helvetica, Arial, sans-serif; font-size: 15px; font-weight: normal; line-height: 26px; margin: 0; margin-bottom: 0; padding: 0 0 24px; text-align: left;">
                        <a class="plugin-brand"
                           href="<?php echo network_admin_url( 'admin.php?page=wdf-scan' ) ?>"
                           style="Margin: 0; color: #ff5c28; display: inline-block; font: inherit; font-family: Helvetica, Arial, sans-serif; font-weight: normal; line-height: 1.3; margin: 0; padding: 0; text-align: left; text-decoration: none;"><?php esc_html_e( "Let's get your site patched up.",
								'wpdef' ) ?>
                            <img class="icon-arrow-right"
                                 src="<?php echo defender_asset_url( '/assets/email-images/icon-arrow-right-defender.png' ) ?>"
                                 alt="Arrow"
                                 style="-ms-interpolation-mode: bicubic; border: none; clear: both; display: inline-block; margin: -2px 0 0 5px; max-width: 100%; outline: none; text-decoration: none; vertical-align: middle; width: auto;"></a>
                    </p>
                </td>
            </tr>
            </tfoot>
        </table>
		<?php
		return ob_get_clean();
	}

	/**
	 * Define labels for settings key
	 *
	 * @param  string|null $key
	 *
	 * @return string|array|null
	 */
	public function labels( $key = null ) {
		$labels = array(
			'notification'                  => __( 'Malware Scanning - Notification', 'wpdef' ),
			'always_send_notification'      => __( 'Send notifications when no issues are detected', 'wpdef' ),
			'error_send'                    => __( "Send notifications when Defender couldn't scan the files", 'wpdef' ),
			'email_subject_issue_found'     => __( 'Email subject when an issue is found', 'wpdef' ),
			'email_subject_issue_not_found' => __( 'Email subject when no issues are found', 'wpdef' ),
			'email_subject_error'           => __( 'Email subject when failed to scan', 'wpdef' ),
			'email_content_issue_found'     => __( 'Email body when an issue is found', 'wpdef' ),
			'email_content_issue_not_found' => __( 'Email body when no issues are found', 'wpdef' ),
			'email_content_error'           => __( 'When failed to scan', 'wpdef' ),
			'notification_subscribers'      => __( 'Recipients', 'wpdef' ),
		);

		if ( ! is_null( $key ) ) {
			return isset( $labels[ $key ] ) ? $labels[ $key ] : null;
		}

		return $labels;
	}
}