<?php

namespace WP_Defender\Model\Notification;

use WP_Defender\Model\Scan as Model_Scan;
use WP_Defender\Traits\Scan_Email_Template;

class Malware_Report extends \WP_Defender\Model\Notification {
	use Scan_Email_Template;

	protected $table = 'wd_malware_scanning_report';

	public const SLUG = 'malware-report';

	protected function before_load(): void {
		$default = [
			'slug' => self::SLUG,
			'title' => __( 'Malware Scanning - Reporting', 'defender-security' ),
			'status' => self::STATUS_DISABLED,
			'description' => __( 'Automatically run regular scans of your website and email you reports.', 'defender-security' ),
			// @since 3.0.0 Fix 'Guest'-line.
			'in_house_recipients' => is_user_logged_in() ? [ $this->get_default_user() ] : [],
			'out_house_recipients' => [],
			'type' => 'report',
			// @since 2.7.0 Add Scheduled Scanning to Malware settings.
			// Hide Schedule and 'dry_run' fields on UI but no delete for backward compatibility with Scan settings, the config structure and the Hub.
			'frequency' => 'weekly',
			'day' => 'sunday',
			'day_n' => '1',
			'time' => '4:00',
			'dry_run' => false,
			'configs' => [
				'always_send' => false,
				'error_send' => false,
				'template' => $this->get_email_template(),
			],
		];
		$this->import( $default );
	}

	/**
	 * @return bool
	 * @throws \Exception
	 */
	public function maybe_send(): bool {
		// @since 2.7.0 First, check "Scheduled Scan" is checked or not.
		if ( ! ( new \WP_Defender\Model\Setting\Scan() )->scheduled_scanning ) {
			return false;
		}

		if ( empty( $this->last_sent ) || empty( $this->est_timestamp ) ) {
			$this->last_sent = $this->est_timestamp;
			$this->est_timestamp = $this->get_next_run()->getTimestamp();
			$this->save();
		}
		$time = apply_filters( 'defender_current_time_for_report', new \DateTime( 'now', wp_timezone() ) );
		// Testing.
		if ( defined( 'WP_DEFENDER_TESTING' ) && true === constant( 'WP_DEFENDER_TESTING' ) ) {
			return true;
		}
		// Check by 'always_send' will be after scanning is complete.
		return $time->getTimestamp() >= $this->est_timestamp;
	}

	/**
	 * Steps:
	 * 1) check the current active scan,
	 * 2) if there isn't active scan then check the latest scan,
	 * 3) save the report settings,
	 * 4) run new scan.
	*/
	public function send() {
		// The current status.
		$active = Model_Scan::get_active();
		if ( is_object( $active ) ) {
			// Scan is running.
			return;
		}
		// Check the latest scan.
		$model = Model_Scan::get_last();
		if ( ! is_object( $model ) ) {
			return;
		}
		// Save the report settings.
		$this->last_sent = $this->est_timestamp;
		$this->est_timestamp = $this->get_next_run()->getTimestamp();
		$this->save();
		// Run scan.
		$scan = Model_Scan::create( true );
		if ( is_object( $scan ) && ! is_wp_error( $scan ) ) {
			/**
			 * @var \WP_Defender\Controller\Scan
			 */
			$scan_controller = wd_di()->get( \WP_Defender\Controller\Scan::class );

			$scan_controller->scan_started_analytics(
				[
					'Triggered From' => 'Plugin',
					'Scan Type' => 'Scheduled',
				]
			);

			$scan_controller->do_async_scan( 'report' );
		}
	}

	/**
	 * Define settings labels.
	 *
	 * @return array
	 */
	public function labels(): array {
		return [
			'report' => __( 'Malware Scanning - Reporting', 'defender-security' ),
			'always_send' => __( 'Send notifications when no issues are detected', 'defender-security' ),
			'report_subscribers' => __( 'Recipients', 'defender-security' ),
			'day' => __( 'Day of', 'defender-security' ),
			'day_n' => __( 'Day of', 'defender-security' ),
			'time' => __( 'Time of day', 'defender-security' ),
			'frequency' => __( 'Frequency', 'defender-security' ),
		];
	}

	/**
	 * @return string
	 */
	public function get_next_run_for_hub(): string {
		return self::STATUS_ACTIVE === $this->status
			? $this->persistent_hub_datetime_format( $this->est_timestamp )
			: __( 'Never', 'defender-security' );
	}

	/**
	 * Additional converting rules.
	 *
	 * @param array $configs
	 *
	 * @return array
	 * @since 3.1.0
	 */
	public function type_casting( $configs ): array {
		$configs['always_send'] = (bool) $configs['always_send'];
		$configs['error_send'] = (bool) $configs['error_send'];

		return $configs;
	}
}
