<?php
/**
 * Scheduled scans and email reports.
 *
 * @package AIAltTextGenerator
 * @since 1.6.0
 */

namespace AIAltTextGenerator;

if ( ! defined( 'ABSPATH' ) ) {
	exit;
}

/**
 * @since 1.6.0
 */
class Scheduler {

	public const CRON_HOOK = 'wpps_ai_alt_scheduled_scan';

	public function register(): void {
		add_action( self::CRON_HOOK, [ $this, 'runScan' ] );
		add_action( 'init', [ $this, 'maybeSchedule' ], 30 );
		add_action( 'wp_powersuite_module_settings_saved', [ $this, 'onSettingsSaved' ], 10, 2 );
	}

	public function onSettingsSaved( string $module_id, array $settings ): void {
		if ( $module_id !== 'ai-alt-text-generator' ) {
			return;
		}

		$this->maybeSchedule();
	}

	public function maybeSchedule(): void {
		$settings = Settings::get();
		$schedule = (string) ( $settings['scan_schedule'] ?? 'manual' );

		wp_clear_scheduled_hook( self::CRON_HOOK );

		if ( $schedule === 'manual' ) {
			return;
		}

		$recurrence = match ( $schedule ) {
			'daily'   => 'daily',
			'weekly'  => 'weekly',
			'monthly' => 'monthly',
			default   => 'weekly',
		};

		if ( ! wp_next_scheduled( self::CRON_HOOK ) ) {
			wp_schedule_event( time() + HOUR_IN_SECONDS, $recurrence, self::CRON_HOOK );
		}
	}

	public function runScan(): void {
		$summary = Scanner::getSummary( true, true );
		DuplicateDetector::getDuplicateGroups( true );

		$settings = Settings::get();
		if ( empty( $settings['email_reports'] ) ) {
			return;
		}

		$to = trim( (string) ( $settings['report_email'] ?? '' ) );
		if ( $to === '' ) {
			$to = (string) get_option( 'admin_email' );
		}

		$subject = sprintf(
			/* translators: %s: site name */
			__( '[%s] AI Alt Text scan report', 'wp-powersuite' ),
			wp_specialchars_decode( get_bloginfo( 'name' ), ENT_QUOTES )
		);

		$dashboard = admin_url( 'admin.php?page=' . Module::DASHBOARD_SLUG );
		$plain_body = sprintf(
			"%s\n\n%s: %d\n%s: %d\n%s: %d\n%s: %d\n%s: %d\n%s: %d\n\n%s",
			__( 'Alt text scan completed.', 'wp-powersuite' ),
			__( 'Total images', 'wp-powersuite' ),
			(int) ( $summary['total'] ?? 0 ),
			__( 'Missing alt text', 'wp-powersuite' ),
			(int) ( $summary['missing'] ?? 0 ),
			__( 'Weak alt text', 'wp-powersuite' ),
			(int) ( $summary['weak'] ?? 0 ),
			__( 'Duplicate alt groups', 'wp-powersuite' ),
			(int) ( $summary['duplicates'] ?? 0 ),
			__( 'Pending review', 'wp-powersuite' ),
			(int) ( $summary['pending_review'] ?? 0 ),
			__( 'Optimized', 'wp-powersuite' ),
			(int) ( $summary['optimized'] ?? 0 ),
			$dashboard
		);

		if ( class_exists( '\WP_PowerSuite\Email\EmailRenderer' ) ) {
			$rows = [
				[ 'label' => __( 'Total images', 'wp-powersuite' ), 'value' => (string) (int) ( $summary['total'] ?? 0 ) ],
				[ 'label' => __( 'Missing alt text', 'wp-powersuite' ), 'value' => (string) (int) ( $summary['missing'] ?? 0 ) ],
				[ 'label' => __( 'Weak alt text', 'wp-powersuite' ), 'value' => (string) (int) ( $summary['weak'] ?? 0 ) ],
				[ 'label' => __( 'Duplicate alt groups', 'wp-powersuite' ), 'value' => (string) (int) ( $summary['duplicates'] ?? 0 ) ],
				[ 'label' => __( 'Pending review', 'wp-powersuite' ), 'value' => (string) (int) ( $summary['pending_review'] ?? 0 ) ],
				[ 'label' => __( 'Optimized', 'wp-powersuite' ), 'value' => (string) (int) ( $summary['optimized'] ?? 0 ) ],
			];
			$content  = \WP_PowerSuite\Email\EmailComponents::paragraph( esc_html__( 'Alt text scan completed.', 'wp-powersuite' ) );
			$content .= \WP_PowerSuite\Email\EmailComponents::detailsBox( __( 'Scan summary', 'wp-powersuite' ), $rows );
			$content .= \WP_PowerSuite\Email\EmailComponents::button(
				$dashboard,
				__( 'Open AI Alt Text dashboard', 'wp-powersuite' ),
				[ 'color' => \WP_PowerSuite\Email\EmailRenderer::accentColor() ]
			);
			$html_body = \WP_PowerSuite\Email\EmailRenderer::wrap(
				[
					'title'        => __( 'AI Alt Text scan report', 'wp-powersuite' ),
					'content'      => $content,
					'footer_brand' => __( 'Sent via WP PowerSuite AI Alt Text Generator', 'wp-powersuite' ),
				]
			);
			$headers = \WP_PowerSuite\Email\EmailRenderer::headers();

			\WP_PowerSuite\Email\EmailRenderer::withPlainAltBody(
				$plain_body,
				static function () use ( $to, $subject, $html_body, $headers ): bool {
					return wp_mail( $to, $subject, $html_body, $headers );
				}
			);
			return;
		}

		wp_mail( $to, $subject, $plain_body );
	}

	public static function unschedule(): void {
		wp_clear_scheduled_hook( self::CRON_HOOK );
	}
}
