<?php
/**
 * Scan planifié (V+ Premium).
 *
 * @package PCC
 * @license GPL-2.0-or-later
 */

defined( 'ABSPATH' ) || exit;

class PCC_Scheduler {

	const CRON_HOOK = 'pcc_scheduled_scan';
	const OPTION_KEY = 'pcc_scheduled';

	/** @var PCC_Plugin */
	private $plugin;

	public function __construct( PCC_Plugin $plugin ) {
		$this->plugin = $plugin;
		add_action( self::CRON_HOOK, array( $this, 'run_scheduled_scan' ) );
	}

	public static function defaults() {
		return array(
			'enabled'  => false,
			'frequency' => 'weekly',
			'email'    => '',
		);
	}

	public function get_settings() {
		return wp_parse_args( get_option( self::OPTION_KEY, array() ), self::defaults() );
	}

	public function save_settings( array $input ) {
		$clean = array(
			'enabled'   => ! empty( $input['enabled'] ),
			'frequency' => in_array( $input['frequency'] ?? '', array( 'weekly', 'monthly' ), true ) ? $input['frequency'] : 'weekly',
			'email'     => sanitize_email( $input['email'] ?? '' ),
		);
		if ( '' === $clean['email'] ) {
			$clean['email'] = get_option( 'admin_email' );
		}
		update_option( self::OPTION_KEY, $clean );
		$this->reschedule( $clean );
		return $clean;
	}

	public function reschedule( $settings = null ) {
		$timestamp = wp_next_scheduled( self::CRON_HOOK );
		if ( $timestamp ) {
			wp_unschedule_event( $timestamp, self::CRON_HOOK );
		}

		$settings = $settings ?? $this->get_settings();
		if ( empty( $settings['enabled'] ) || ! $this->plugin->has_feature( 'scheduled_scan' ) ) {
			return;
		}

		$recurrence = ( 'monthly' === $settings['frequency'] ) ? 'monthly' : 'weekly';
		if ( ! wp_next_scheduled( self::CRON_HOOK ) ) {
			wp_schedule_event( time() + HOUR_IN_SECONDS, $recurrence, self::CRON_HOOK );
		}
	}

	public function run_scheduled_scan() {
		if ( ! $this->plugin->has_feature( 'scheduled_scan' ) ) {
			return;
		}

		$settings = $this->get_settings();
		if ( empty( $settings['enabled'] ) ) {
			return;
		}

		$result = $this->plugin->scanner->run_full_scan_cli( true );
		if ( is_wp_error( $result ) ) {
			return;
		}

		$email = $settings['email'] ?: get_option( 'admin_email' );
		$subj  = sprintf(
			/* translators: %s: site name */
			__( '[%s] PHP compatibility scan report', 'php-compatibility-checker-by-volade' ),
			wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES )
		);

		$errors   = (int) ( $result['summary']['errors'] ?? 0 );
		$warnings = (int) ( $result['summary']['warnings'] ?? 0 );
		$verdict  = $this->plugin->scanner->verdict_label( $result['verdict'] ?? 'unknown' );
		$url      = admin_url( PCC_Admin::instance_settings_path( $this->plugin ) );

		$body  = $this->build_html_email( $result, $verdict, $errors, $warnings, $url );
		$headers = array( 'Content-Type: text/html; charset=UTF-8' );
		wp_mail( $email, $subj, $body, $headers );
	}

	/**
	 * @param array<string, mixed> $result
	 */
	private function build_html_email( $result, $verdict, $errors, $warnings, $url ) {
		$target = esc_html( $result['target_php'] ?? '' );
		$rows   = '';
		foreach ( array_slice( (array) ( $result['top_issues'] ?? array_values( (array) ( $result['by_component'] ?? array() ) ) ), 0, 10 ) as $row ) {
			if ( ! is_array( $row ) ) {
				continue;
			}
			$label = esc_html( $row['label'] ?? '' );
			$e     = (int) ( $row['errors'] ?? 0 );
			$w     = (int) ( $row['warnings'] ?? 0 );
			$rows .= "<tr><td>{$label}</td><td>{$e}</td><td>{$w}</td></tr>";
		}

		$view = esc_html__( 'View full report', 'php-compatibility-checker-by-volade' );
		$url  = esc_url( $url );

		return '<html><body style="font-family:sans-serif;color:#1e293b">'
			. '<h2>' . esc_html__( 'PHP compatibility scan', 'php-compatibility-checker-by-volade' ) . '</h2>'
			. '<p><strong>' . esc_html( $verdict ) . '</strong></p>'
			. '<p>PHP ' . $target . ' — '
			/* translators: 1: error count, 2: warning count */
			. esc_html( sprintf( __( '%1$d errors, %2$d warnings', 'php-compatibility-checker-by-volade' ), $errors, $warnings ) )
			. '</p>'
			. ( $rows ? '<table cellpadding="6" cellspacing="0" border="1" style="border-collapse:collapse;border-color:#e2e8f0"><thead><tr><th>'
			. esc_html__( 'Component', 'php-compatibility-checker-by-volade' ) . '</th><th>'
			. esc_html__( 'Errors', 'php-compatibility-checker-by-volade' ) . '</th><th>'
			. esc_html__( 'Warnings', 'php-compatibility-checker-by-volade' ) . '</th></tr></thead><tbody>'
			. $rows . '</tbody></table>' : '' )
			. '<p><a href="' . $url . '">' . $view . '</a></p>'
			. '</body></html>';
	}
}
